[X86] Reordered lowerVectorShuffleAsBitMask before lowerVectorShuffleAsBlend. NFCI.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/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   MVT PtrVT = MVT::getIntegerVT(8 * TM.getPointerSize());
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, PtrVT, 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     setTruncStoreAction(MVT::v8i64,   MVT::v8i8,   Legal);
1352     setTruncStoreAction(MVT::v8i64,   MVT::v8i16,  Legal);
1353     setTruncStoreAction(MVT::v8i64,   MVT::v8i32,  Legal);
1354     setTruncStoreAction(MVT::v16i32,  MVT::v16i8,  Legal);
1355     setTruncStoreAction(MVT::v16i32,  MVT::v16i16, Legal);
1356     if (Subtarget->hasVLX()){
1357       setTruncStoreAction(MVT::v4i64, MVT::v4i8,  Legal);
1358       setTruncStoreAction(MVT::v4i64, MVT::v4i16, Legal);
1359       setTruncStoreAction(MVT::v4i64, MVT::v4i32, Legal);
1360       setTruncStoreAction(MVT::v8i32, MVT::v8i8,  Legal);
1361       setTruncStoreAction(MVT::v8i32, MVT::v8i16, Legal);
1362
1363       setTruncStoreAction(MVT::v2i64, MVT::v2i8,  Legal);
1364       setTruncStoreAction(MVT::v2i64, MVT::v2i16, Legal);
1365       setTruncStoreAction(MVT::v2i64, MVT::v2i32, Legal);
1366       setTruncStoreAction(MVT::v4i32, MVT::v4i8,  Legal);
1367       setTruncStoreAction(MVT::v4i32, MVT::v4i16, Legal);
1368     }
1369     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1370     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1371     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1372     if (Subtarget->hasDQI()) {
1373       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1374       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1375
1376       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1377       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1378       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1379       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1380       if (Subtarget->hasVLX()) {
1381         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1382         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1383         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1384         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1385         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1386         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1387         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1388         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1389       }
1390     }
1391     if (Subtarget->hasVLX()) {
1392       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1393       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1394       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1395       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1396       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1397       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1398       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1399       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1400     }
1401     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1402     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1403     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1404     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1405     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1406     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1407     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1408     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1409     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1410     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1411     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1412     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1413     if (Subtarget->hasDQI()) {
1414       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1415       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1416     }
1417     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1418     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1419     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1420     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1421     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1422     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1423     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1424     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1425     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1426     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1427
1428     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1429     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1430     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1431     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1432     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1433
1434     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1435     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1436
1437     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1438
1439     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1440     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1441     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1442     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1443     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1444     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1445     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1446     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1447     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1448     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1449     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1450
1451     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1452     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1453     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1454     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1455     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1456     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1457     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1458     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1459
1460     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1461     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1462
1463     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1464     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1465
1466     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1467
1468     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1469     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1470
1471     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1472     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1473
1474     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1475     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1476
1477     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1478     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1479     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1480     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1481     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1482     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1483
1484     if (Subtarget->hasCDI()) {
1485       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1486       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1487     }
1488     if (Subtarget->hasDQI()) {
1489       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1490       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1491       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1492     }
1493     // Custom lower several nodes.
1494     for (MVT VT : MVT::vector_valuetypes()) {
1495       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1496       if (EltSize == 1) {
1497         setOperationAction(ISD::AND, VT, Legal);
1498         setOperationAction(ISD::OR,  VT, Legal);
1499         setOperationAction(ISD::XOR,  VT, Legal);
1500       }
1501       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1502         setOperationAction(ISD::MGATHER,  VT, Custom);
1503         setOperationAction(ISD::MSCATTER, VT, Custom);
1504       }
1505       // Extract subvector is special because the value type
1506       // (result) is 256/128-bit but the source is 512-bit wide.
1507       if (VT.is128BitVector() || VT.is256BitVector()) {
1508         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1509       }
1510       if (VT.getVectorElementType() == MVT::i1)
1511         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1512
1513       // Do not attempt to custom lower other non-512-bit vectors
1514       if (!VT.is512BitVector())
1515         continue;
1516
1517       if (EltSize >= 32) {
1518         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1519         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1520         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1521         setOperationAction(ISD::VSELECT,             VT, Legal);
1522         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1523         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1524         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1525         setOperationAction(ISD::MLOAD,               VT, Legal);
1526         setOperationAction(ISD::MSTORE,              VT, Legal);
1527       }
1528     }
1529     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1530       MVT VT = (MVT::SimpleValueType)i;
1531
1532       // Do not attempt to promote non-512-bit vectors.
1533       if (!VT.is512BitVector())
1534         continue;
1535
1536       setOperationAction(ISD::SELECT, VT, Promote);
1537       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1538     }
1539   }// has  AVX-512
1540
1541   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1542     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1543     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1544
1545     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1546     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1547
1548     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1549     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1550     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1551     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1552     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1553     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1554     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1555     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1556     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1557     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1558     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1559     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1560     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1561     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1562     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1563     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1564     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1565     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1566     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1567     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1568     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1569     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1570     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1571     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1572     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1573     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1574     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1575     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1576     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1577     setOperationAction(ISD::TRUNCATE,           MVT::v32i8, Custom);
1578
1579     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1580     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1581     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1582     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1583     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1584     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1585     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1586     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1587
1588     setTruncStoreAction(MVT::v32i16,  MVT::v32i8, Legal);
1589     setTruncStoreAction(MVT::v16i16,  MVT::v16i8, Legal);
1590     if (Subtarget->hasVLX())
1591       setTruncStoreAction(MVT::v8i16,   MVT::v8i8,  Legal);
1592
1593     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1594       const MVT VT = (MVT::SimpleValueType)i;
1595
1596       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1597
1598       // Do not attempt to promote non-512-bit vectors.
1599       if (!VT.is512BitVector())
1600         continue;
1601
1602       if (EltSize < 32) {
1603         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1604         setOperationAction(ISD::VSELECT,             VT, Legal);
1605       }
1606     }
1607   }
1608
1609   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1610     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1611     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1612
1613     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1614     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1615     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1616     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1617     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1618     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1619     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1620     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1621     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1622     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1623
1624     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1625     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1626     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1627     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1628     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1629     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1630     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1631     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1632
1633     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1634     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1635     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1636     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1637     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1638     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1639     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1640     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1641   }
1642
1643   // We want to custom lower some of our intrinsics.
1644   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1645   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1646   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1647   if (!Subtarget->is64Bit())
1648     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1649
1650   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1651   // handle type legalization for these operations here.
1652   //
1653   // FIXME: We really should do custom legalization for addition and
1654   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1655   // than generic legalization for 64-bit multiplication-with-overflow, though.
1656   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1657     // Add/Sub/Mul with overflow operations are custom lowered.
1658     MVT VT = IntVTs[i];
1659     setOperationAction(ISD::SADDO, VT, Custom);
1660     setOperationAction(ISD::UADDO, VT, Custom);
1661     setOperationAction(ISD::SSUBO, VT, Custom);
1662     setOperationAction(ISD::USUBO, VT, Custom);
1663     setOperationAction(ISD::SMULO, VT, Custom);
1664     setOperationAction(ISD::UMULO, VT, Custom);
1665   }
1666
1667
1668   if (!Subtarget->is64Bit()) {
1669     // These libcalls are not available in 32-bit.
1670     setLibcallName(RTLIB::SHL_I128, nullptr);
1671     setLibcallName(RTLIB::SRL_I128, nullptr);
1672     setLibcallName(RTLIB::SRA_I128, nullptr);
1673   }
1674
1675   // Combine sin / cos into one node or libcall if possible.
1676   if (Subtarget->hasSinCos()) {
1677     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1678     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1679     if (Subtarget->isTargetDarwin()) {
1680       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1681       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1682       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1683       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1684     }
1685   }
1686
1687   if (Subtarget->isTargetWin64()) {
1688     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1689     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1690     setOperationAction(ISD::SREM, MVT::i128, Custom);
1691     setOperationAction(ISD::UREM, MVT::i128, Custom);
1692     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1693     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1694   }
1695
1696   // We have target-specific dag combine patterns for the following nodes:
1697   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1698   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1699   setTargetDAGCombine(ISD::BITCAST);
1700   setTargetDAGCombine(ISD::VSELECT);
1701   setTargetDAGCombine(ISD::SELECT);
1702   setTargetDAGCombine(ISD::SHL);
1703   setTargetDAGCombine(ISD::SRA);
1704   setTargetDAGCombine(ISD::SRL);
1705   setTargetDAGCombine(ISD::OR);
1706   setTargetDAGCombine(ISD::AND);
1707   setTargetDAGCombine(ISD::ADD);
1708   setTargetDAGCombine(ISD::FADD);
1709   setTargetDAGCombine(ISD::FSUB);
1710   setTargetDAGCombine(ISD::FMA);
1711   setTargetDAGCombine(ISD::SUB);
1712   setTargetDAGCombine(ISD::LOAD);
1713   setTargetDAGCombine(ISD::MLOAD);
1714   setTargetDAGCombine(ISD::STORE);
1715   setTargetDAGCombine(ISD::MSTORE);
1716   setTargetDAGCombine(ISD::ZERO_EXTEND);
1717   setTargetDAGCombine(ISD::ANY_EXTEND);
1718   setTargetDAGCombine(ISD::SIGN_EXTEND);
1719   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1720   setTargetDAGCombine(ISD::SINT_TO_FP);
1721   setTargetDAGCombine(ISD::UINT_TO_FP);
1722   setTargetDAGCombine(ISD::SETCC);
1723   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1724   setTargetDAGCombine(ISD::BUILD_VECTOR);
1725   setTargetDAGCombine(ISD::MUL);
1726   setTargetDAGCombine(ISD::XOR);
1727
1728   computeRegisterProperties(Subtarget->getRegisterInfo());
1729
1730   // On Darwin, -Os means optimize for size without hurting performance,
1731   // do not reduce the limit.
1732   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1733   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1734   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1735   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1736   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1737   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1738   setPrefLoopAlignment(4); // 2^4 bytes.
1739
1740   // Predictable cmov don't hurt on atom because it's in-order.
1741   PredictableSelectIsExpensive = !Subtarget->isAtom();
1742   EnableExtLdPromotion = true;
1743   setPrefFunctionAlignment(4); // 2^4 bytes.
1744
1745   verifyIntrinsicTables();
1746 }
1747
1748 // This has so far only been implemented for 64-bit MachO.
1749 bool X86TargetLowering::useLoadStackGuardNode() const {
1750   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1751 }
1752
1753 TargetLoweringBase::LegalizeTypeAction
1754 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1755   if (ExperimentalVectorWideningLegalization &&
1756       VT.getVectorNumElements() != 1 &&
1757       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1758     return TypeWidenVector;
1759
1760   return TargetLoweringBase::getPreferredVectorAction(VT);
1761 }
1762
1763 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1764                                           EVT VT) const {
1765   if (!VT.isVector())
1766     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1767
1768   const unsigned NumElts = VT.getVectorNumElements();
1769   const EVT EltVT = VT.getVectorElementType();
1770   if (VT.is512BitVector()) {
1771     if (Subtarget->hasAVX512())
1772       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1773           EltVT == MVT::f32 || EltVT == MVT::f64)
1774         switch(NumElts) {
1775         case  8: return MVT::v8i1;
1776         case 16: return MVT::v16i1;
1777       }
1778     if (Subtarget->hasBWI())
1779       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1780         switch(NumElts) {
1781         case 32: return MVT::v32i1;
1782         case 64: return MVT::v64i1;
1783       }
1784   }
1785
1786   if (VT.is256BitVector() || VT.is128BitVector()) {
1787     if (Subtarget->hasVLX())
1788       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1789           EltVT == MVT::f32 || EltVT == MVT::f64)
1790         switch(NumElts) {
1791         case 2: return MVT::v2i1;
1792         case 4: return MVT::v4i1;
1793         case 8: return MVT::v8i1;
1794       }
1795     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1796       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1797         switch(NumElts) {
1798         case  8: return MVT::v8i1;
1799         case 16: return MVT::v16i1;
1800         case 32: return MVT::v32i1;
1801       }
1802   }
1803
1804   return VT.changeVectorElementTypeToInteger();
1805 }
1806
1807 /// Helper for getByValTypeAlignment to determine
1808 /// the desired ByVal argument alignment.
1809 static void getMaxByValAlign(const Type *Ty, unsigned &MaxAlign) {
1810   if (MaxAlign == 16)
1811     return;
1812   if (const VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1813     if (VTy->getBitWidth() == 128)
1814       MaxAlign = 16;
1815   } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1816     unsigned EltAlign = 0;
1817     getMaxByValAlign(ATy->getElementType(), EltAlign);
1818     if (EltAlign > MaxAlign)
1819       MaxAlign = EltAlign;
1820   } else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
1821     for (const auto *EltTy : STy->elements()) {
1822       unsigned EltAlign = 0;
1823       getMaxByValAlign(EltTy, EltAlign);
1824       if (EltAlign > MaxAlign)
1825         MaxAlign = EltAlign;
1826       if (MaxAlign == 16)
1827         break;
1828     }
1829   }
1830 }
1831
1832 /// Return the desired alignment for ByVal aggregate
1833 /// function arguments in the caller parameter area. For X86, aggregates
1834 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1835 /// are at 4-byte boundaries.
1836 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1837                                                   const DataLayout &DL) const {
1838   if (Subtarget->is64Bit()) {
1839     // Max of 8 and alignment of type.
1840     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1841     if (TyAlign > 8)
1842       return TyAlign;
1843     return 8;
1844   }
1845
1846   unsigned Align = 4;
1847   if (Subtarget->hasSSE1())
1848     getMaxByValAlign(Ty, Align);
1849   return Align;
1850 }
1851
1852 /// Returns the target specific optimal type for load
1853 /// and store operations as a result of memset, memcpy, and memmove
1854 /// lowering. If DstAlign is zero that means it's safe to destination
1855 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1856 /// means there isn't a need to check it against alignment requirement,
1857 /// probably because the source does not need to be loaded. If 'IsMemset' is
1858 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1859 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1860 /// source is constant so it does not need to be loaded.
1861 /// It returns EVT::Other if the type should be determined using generic
1862 /// target-independent logic.
1863 EVT
1864 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1865                                        unsigned DstAlign, unsigned SrcAlign,
1866                                        bool IsMemset, bool ZeroMemset,
1867                                        bool MemcpyStrSrc,
1868                                        MachineFunction &MF) const {
1869   const Function *F = MF.getFunction();
1870   if ((!IsMemset || ZeroMemset) &&
1871       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1872     if (Size >= 16 &&
1873         (Subtarget->isUnalignedMemAccessFast() ||
1874          ((DstAlign == 0 || DstAlign >= 16) &&
1875           (SrcAlign == 0 || SrcAlign >= 16)))) {
1876       if (Size >= 32) {
1877         if (Subtarget->hasInt256())
1878           return MVT::v8i32;
1879         if (Subtarget->hasFp256())
1880           return MVT::v8f32;
1881       }
1882       if (Subtarget->hasSSE2())
1883         return MVT::v4i32;
1884       if (Subtarget->hasSSE1())
1885         return MVT::v4f32;
1886     } else if (!MemcpyStrSrc && Size >= 8 &&
1887                !Subtarget->is64Bit() &&
1888                Subtarget->hasSSE2()) {
1889       // Do not use f64 to lower memcpy if source is string constant. It's
1890       // better to use i32 to avoid the loads.
1891       return MVT::f64;
1892     }
1893   }
1894   if (Subtarget->is64Bit() && Size >= 8)
1895     return MVT::i64;
1896   return MVT::i32;
1897 }
1898
1899 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1900   if (VT == MVT::f32)
1901     return X86ScalarSSEf32;
1902   else if (VT == MVT::f64)
1903     return X86ScalarSSEf64;
1904   return true;
1905 }
1906
1907 bool
1908 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1909                                                   unsigned,
1910                                                   unsigned,
1911                                                   bool *Fast) const {
1912   if (Fast)
1913     *Fast = Subtarget->isUnalignedMemAccessFast();
1914   return true;
1915 }
1916
1917 /// Return the entry encoding for a jump table in the
1918 /// current function.  The returned value is a member of the
1919 /// MachineJumpTableInfo::JTEntryKind enum.
1920 unsigned X86TargetLowering::getJumpTableEncoding() const {
1921   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1922   // symbol.
1923   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1924       Subtarget->isPICStyleGOT())
1925     return MachineJumpTableInfo::EK_Custom32;
1926
1927   // Otherwise, use the normal jump table encoding heuristics.
1928   return TargetLowering::getJumpTableEncoding();
1929 }
1930
1931 bool X86TargetLowering::useSoftFloat() const {
1932   return Subtarget->useSoftFloat();
1933 }
1934
1935 const MCExpr *
1936 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1937                                              const MachineBasicBlock *MBB,
1938                                              unsigned uid,MCContext &Ctx) const{
1939   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1940          Subtarget->isPICStyleGOT());
1941   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1942   // entries.
1943   return MCSymbolRefExpr::create(MBB->getSymbol(),
1944                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1945 }
1946
1947 /// Returns relocation base for the given PIC jumptable.
1948 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1949                                                     SelectionDAG &DAG) const {
1950   if (!Subtarget->is64Bit())
1951     // This doesn't have SDLoc associated with it, but is not really the
1952     // same as a Register.
1953     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1954                        getPointerTy(DAG.getDataLayout()));
1955   return Table;
1956 }
1957
1958 /// This returns the relocation base for the given PIC jumptable,
1959 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1960 const MCExpr *X86TargetLowering::
1961 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1962                              MCContext &Ctx) const {
1963   // X86-64 uses RIP relative addressing based on the jump table label.
1964   if (Subtarget->isPICStyleRIPRel())
1965     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1966
1967   // Otherwise, the reference is relative to the PIC base.
1968   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1969 }
1970
1971 std::pair<const TargetRegisterClass *, uint8_t>
1972 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1973                                            MVT VT) const {
1974   const TargetRegisterClass *RRC = nullptr;
1975   uint8_t Cost = 1;
1976   switch (VT.SimpleTy) {
1977   default:
1978     return TargetLowering::findRepresentativeClass(TRI, VT);
1979   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1980     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1981     break;
1982   case MVT::x86mmx:
1983     RRC = &X86::VR64RegClass;
1984     break;
1985   case MVT::f32: case MVT::f64:
1986   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1987   case MVT::v4f32: case MVT::v2f64:
1988   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1989   case MVT::v4f64:
1990     RRC = &X86::VR128RegClass;
1991     break;
1992   }
1993   return std::make_pair(RRC, Cost);
1994 }
1995
1996 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1997                                                unsigned &Offset) const {
1998   if (!Subtarget->isTargetLinux())
1999     return false;
2000
2001   if (Subtarget->is64Bit()) {
2002     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
2003     Offset = 0x28;
2004     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
2005       AddressSpace = 256;
2006     else
2007       AddressSpace = 257;
2008   } else {
2009     // %gs:0x14 on i386
2010     Offset = 0x14;
2011     AddressSpace = 256;
2012   }
2013   return true;
2014 }
2015
2016 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
2017                                             unsigned DestAS) const {
2018   assert(SrcAS != DestAS && "Expected different address spaces!");
2019
2020   return SrcAS < 256 && DestAS < 256;
2021 }
2022
2023 //===----------------------------------------------------------------------===//
2024 //               Return Value Calling Convention Implementation
2025 //===----------------------------------------------------------------------===//
2026
2027 #include "X86GenCallingConv.inc"
2028
2029 bool
2030 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2031                                   MachineFunction &MF, bool isVarArg,
2032                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2033                         LLVMContext &Context) const {
2034   SmallVector<CCValAssign, 16> RVLocs;
2035   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2036   return CCInfo.CheckReturn(Outs, RetCC_X86);
2037 }
2038
2039 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2040   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2041   return ScratchRegs;
2042 }
2043
2044 SDValue
2045 X86TargetLowering::LowerReturn(SDValue Chain,
2046                                CallingConv::ID CallConv, bool isVarArg,
2047                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2048                                const SmallVectorImpl<SDValue> &OutVals,
2049                                SDLoc dl, SelectionDAG &DAG) const {
2050   MachineFunction &MF = DAG.getMachineFunction();
2051   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2052
2053   SmallVector<CCValAssign, 16> RVLocs;
2054   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2055   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2056
2057   SDValue Flag;
2058   SmallVector<SDValue, 6> RetOps;
2059   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2060   // Operand #1 = Bytes To Pop
2061   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2062                    MVT::i16));
2063
2064   // Copy the result values into the output registers.
2065   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2066     CCValAssign &VA = RVLocs[i];
2067     assert(VA.isRegLoc() && "Can only return in registers!");
2068     SDValue ValToCopy = OutVals[i];
2069     EVT ValVT = ValToCopy.getValueType();
2070
2071     // Promote values to the appropriate types.
2072     if (VA.getLocInfo() == CCValAssign::SExt)
2073       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2074     else if (VA.getLocInfo() == CCValAssign::ZExt)
2075       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2076     else if (VA.getLocInfo() == CCValAssign::AExt) {
2077       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2078         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2079       else
2080         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2081     }
2082     else if (VA.getLocInfo() == CCValAssign::BCvt)
2083       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2084
2085     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2086            "Unexpected FP-extend for return value.");
2087
2088     // If this is x86-64, and we disabled SSE, we can't return FP values,
2089     // or SSE or MMX vectors.
2090     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2091          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2092           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2093       report_fatal_error("SSE register return with SSE disabled");
2094     }
2095     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2096     // llvm-gcc has never done it right and no one has noticed, so this
2097     // should be OK for now.
2098     if (ValVT == MVT::f64 &&
2099         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2100       report_fatal_error("SSE2 register return with SSE2 disabled");
2101
2102     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2103     // the RET instruction and handled by the FP Stackifier.
2104     if (VA.getLocReg() == X86::FP0 ||
2105         VA.getLocReg() == X86::FP1) {
2106       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2107       // change the value to the FP stack register class.
2108       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2109         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2110       RetOps.push_back(ValToCopy);
2111       // Don't emit a copytoreg.
2112       continue;
2113     }
2114
2115     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2116     // which is returned in RAX / RDX.
2117     if (Subtarget->is64Bit()) {
2118       if (ValVT == MVT::x86mmx) {
2119         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2120           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2121           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2122                                   ValToCopy);
2123           // If we don't have SSE2 available, convert to v4f32 so the generated
2124           // register is legal.
2125           if (!Subtarget->hasSSE2())
2126             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2127         }
2128       }
2129     }
2130
2131     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2132     Flag = Chain.getValue(1);
2133     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2134   }
2135
2136   // All x86 ABIs require that for returning structs by value we copy
2137   // the sret argument into %rax/%eax (depending on ABI) for the return.
2138   // We saved the argument into a virtual register in the entry block,
2139   // so now we copy the value out and into %rax/%eax.
2140   //
2141   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2142   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2143   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2144   // either case FuncInfo->setSRetReturnReg() will have been called.
2145   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2146     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2147                                      getPointerTy(MF.getDataLayout()));
2148
2149     unsigned RetValReg
2150         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2151           X86::RAX : X86::EAX;
2152     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2153     Flag = Chain.getValue(1);
2154
2155     // RAX/EAX now acts like a return value.
2156     RetOps.push_back(
2157         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2158   }
2159
2160   RetOps[0] = Chain;  // Update chain.
2161
2162   // Add the flag if we have it.
2163   if (Flag.getNode())
2164     RetOps.push_back(Flag);
2165
2166   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2167 }
2168
2169 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2170   if (N->getNumValues() != 1)
2171     return false;
2172   if (!N->hasNUsesOfValue(1, 0))
2173     return false;
2174
2175   SDValue TCChain = Chain;
2176   SDNode *Copy = *N->use_begin();
2177   if (Copy->getOpcode() == ISD::CopyToReg) {
2178     // If the copy has a glue operand, we conservatively assume it isn't safe to
2179     // perform a tail call.
2180     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2181       return false;
2182     TCChain = Copy->getOperand(0);
2183   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2184     return false;
2185
2186   bool HasRet = false;
2187   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2188        UI != UE; ++UI) {
2189     if (UI->getOpcode() != X86ISD::RET_FLAG)
2190       return false;
2191     // If we are returning more than one value, we can definitely
2192     // not make a tail call see PR19530
2193     if (UI->getNumOperands() > 4)
2194       return false;
2195     if (UI->getNumOperands() == 4 &&
2196         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2197       return false;
2198     HasRet = true;
2199   }
2200
2201   if (!HasRet)
2202     return false;
2203
2204   Chain = TCChain;
2205   return true;
2206 }
2207
2208 EVT
2209 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2210                                             ISD::NodeType ExtendKind) const {
2211   MVT ReturnMVT;
2212   // TODO: Is this also valid on 32-bit?
2213   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2214     ReturnMVT = MVT::i8;
2215   else
2216     ReturnMVT = MVT::i32;
2217
2218   EVT MinVT = getRegisterType(Context, ReturnMVT);
2219   return VT.bitsLT(MinVT) ? MinVT : VT;
2220 }
2221
2222 /// Lower the result values of a call into the
2223 /// appropriate copies out of appropriate physical registers.
2224 ///
2225 SDValue
2226 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2227                                    CallingConv::ID CallConv, bool isVarArg,
2228                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2229                                    SDLoc dl, SelectionDAG &DAG,
2230                                    SmallVectorImpl<SDValue> &InVals) const {
2231
2232   // Assign locations to each value returned by this call.
2233   SmallVector<CCValAssign, 16> RVLocs;
2234   bool Is64Bit = Subtarget->is64Bit();
2235   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2236                  *DAG.getContext());
2237   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2238
2239   // Copy all of the result registers out of their specified physreg.
2240   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2241     CCValAssign &VA = RVLocs[i];
2242     EVT CopyVT = VA.getLocVT();
2243
2244     // If this is x86-64, and we disabled SSE, we can't return FP values
2245     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2246         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2247       report_fatal_error("SSE register return with SSE disabled");
2248     }
2249
2250     // If we prefer to use the value in xmm registers, copy it out as f80 and
2251     // use a truncate to move it from fp stack reg to xmm reg.
2252     bool RoundAfterCopy = false;
2253     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2254         isScalarFPTypeInSSEReg(VA.getValVT())) {
2255       CopyVT = MVT::f80;
2256       RoundAfterCopy = (CopyVT != VA.getLocVT());
2257     }
2258
2259     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2260                                CopyVT, InFlag).getValue(1);
2261     SDValue Val = Chain.getValue(0);
2262
2263     if (RoundAfterCopy)
2264       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2265                         // This truncation won't change the value.
2266                         DAG.getIntPtrConstant(1, dl));
2267
2268     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2269       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2270
2271     InFlag = Chain.getValue(2);
2272     InVals.push_back(Val);
2273   }
2274
2275   return Chain;
2276 }
2277
2278 //===----------------------------------------------------------------------===//
2279 //                C & StdCall & Fast Calling Convention implementation
2280 //===----------------------------------------------------------------------===//
2281 //  StdCall calling convention seems to be standard for many Windows' API
2282 //  routines and around. It differs from C calling convention just a little:
2283 //  callee should clean up the stack, not caller. Symbols should be also
2284 //  decorated in some fancy way :) It doesn't support any vector arguments.
2285 //  For info on fast calling convention see Fast Calling Convention (tail call)
2286 //  implementation LowerX86_32FastCCCallTo.
2287
2288 /// CallIsStructReturn - Determines whether a call uses struct return
2289 /// semantics.
2290 enum StructReturnType {
2291   NotStructReturn,
2292   RegStructReturn,
2293   StackStructReturn
2294 };
2295 static StructReturnType
2296 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2297   if (Outs.empty())
2298     return NotStructReturn;
2299
2300   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2301   if (!Flags.isSRet())
2302     return NotStructReturn;
2303   if (Flags.isInReg())
2304     return RegStructReturn;
2305   return StackStructReturn;
2306 }
2307
2308 /// Determines whether a function uses struct return semantics.
2309 static StructReturnType
2310 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2311   if (Ins.empty())
2312     return NotStructReturn;
2313
2314   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2315   if (!Flags.isSRet())
2316     return NotStructReturn;
2317   if (Flags.isInReg())
2318     return RegStructReturn;
2319   return StackStructReturn;
2320 }
2321
2322 /// Make a copy of an aggregate at address specified by "Src" to address
2323 /// "Dst" with size and alignment information specified by the specific
2324 /// parameter attribute. The copy will be passed as a byval function parameter.
2325 static SDValue
2326 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2327                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2328                           SDLoc dl) {
2329   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2330
2331   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2332                        /*isVolatile*/false, /*AlwaysInline=*/true,
2333                        /*isTailCall*/false,
2334                        MachinePointerInfo(), MachinePointerInfo());
2335 }
2336
2337 /// Return true if the calling convention is one that
2338 /// supports tail call optimization.
2339 static bool IsTailCallConvention(CallingConv::ID CC) {
2340   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2341           CC == CallingConv::HiPE);
2342 }
2343
2344 /// \brief Return true if the calling convention is a C calling convention.
2345 static bool IsCCallConvention(CallingConv::ID CC) {
2346   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2347           CC == CallingConv::X86_64_SysV);
2348 }
2349
2350 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2351   auto Attr =
2352       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2353   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2354     return false;
2355
2356   CallSite CS(CI);
2357   CallingConv::ID CalleeCC = CS.getCallingConv();
2358   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2359     return false;
2360
2361   return true;
2362 }
2363
2364 /// Return true if the function is being made into
2365 /// a tailcall target by changing its ABI.
2366 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2367                                    bool GuaranteedTailCallOpt) {
2368   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2369 }
2370
2371 SDValue
2372 X86TargetLowering::LowerMemArgument(SDValue Chain,
2373                                     CallingConv::ID CallConv,
2374                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2375                                     SDLoc dl, SelectionDAG &DAG,
2376                                     const CCValAssign &VA,
2377                                     MachineFrameInfo *MFI,
2378                                     unsigned i) const {
2379   // Create the nodes corresponding to a load from this parameter slot.
2380   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2381   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2382       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2383   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2384   EVT ValVT;
2385
2386   // If value is passed by pointer we have address passed instead of the value
2387   // itself.
2388   bool ExtendedInMem = VA.isExtInLoc() &&
2389     VA.getValVT().getScalarType() == MVT::i1;
2390
2391   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2392     ValVT = VA.getLocVT();
2393   else
2394     ValVT = VA.getValVT();
2395
2396   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2397   // changed with more analysis.
2398   // In case of tail call optimization mark all arguments mutable. Since they
2399   // could be overwritten by lowering of arguments in case of a tail call.
2400   if (Flags.isByVal()) {
2401     unsigned Bytes = Flags.getByValSize();
2402     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2403     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2404     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2405   } else {
2406     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2407                                     VA.getLocMemOffset(), isImmutable);
2408     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2409     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2410                                MachinePointerInfo::getFixedStack(FI),
2411                                false, false, false, 0);
2412     return ExtendedInMem ?
2413       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2414   }
2415 }
2416
2417 // FIXME: Get this from tablegen.
2418 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2419                                                 const X86Subtarget *Subtarget) {
2420   assert(Subtarget->is64Bit());
2421
2422   if (Subtarget->isCallingConvWin64(CallConv)) {
2423     static const MCPhysReg GPR64ArgRegsWin64[] = {
2424       X86::RCX, X86::RDX, X86::R8,  X86::R9
2425     };
2426     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2427   }
2428
2429   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2430     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2431   };
2432   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2433 }
2434
2435 // FIXME: Get this from tablegen.
2436 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2437                                                 CallingConv::ID CallConv,
2438                                                 const X86Subtarget *Subtarget) {
2439   assert(Subtarget->is64Bit());
2440   if (Subtarget->isCallingConvWin64(CallConv)) {
2441     // The XMM registers which might contain var arg parameters are shadowed
2442     // in their paired GPR.  So we only need to save the GPR to their home
2443     // slots.
2444     // TODO: __vectorcall will change this.
2445     return None;
2446   }
2447
2448   const Function *Fn = MF.getFunction();
2449   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2450   bool isSoftFloat = Subtarget->useSoftFloat();
2451   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2452          "SSE register cannot be used when SSE is disabled!");
2453   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2454     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2455     // registers.
2456     return None;
2457
2458   static const MCPhysReg XMMArgRegs64Bit[] = {
2459     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2460     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2461   };
2462   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2463 }
2464
2465 SDValue
2466 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2467                                         CallingConv::ID CallConv,
2468                                         bool isVarArg,
2469                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2470                                         SDLoc dl,
2471                                         SelectionDAG &DAG,
2472                                         SmallVectorImpl<SDValue> &InVals)
2473                                           const {
2474   MachineFunction &MF = DAG.getMachineFunction();
2475   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2476   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2477
2478   const Function* Fn = MF.getFunction();
2479   if (Fn->hasExternalLinkage() &&
2480       Subtarget->isTargetCygMing() &&
2481       Fn->getName() == "main")
2482     FuncInfo->setForceFramePointer(true);
2483
2484   MachineFrameInfo *MFI = MF.getFrameInfo();
2485   bool Is64Bit = Subtarget->is64Bit();
2486   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2487
2488   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2489          "Var args not supported with calling convention fastcc, ghc or hipe");
2490
2491   // Assign locations to all of the incoming arguments.
2492   SmallVector<CCValAssign, 16> ArgLocs;
2493   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2494
2495   // Allocate shadow area for Win64
2496   if (IsWin64)
2497     CCInfo.AllocateStack(32, 8);
2498
2499   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2500
2501   unsigned LastVal = ~0U;
2502   SDValue ArgValue;
2503   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2504     CCValAssign &VA = ArgLocs[i];
2505     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2506     // places.
2507     assert(VA.getValNo() != LastVal &&
2508            "Don't support value assigned to multiple locs yet");
2509     (void)LastVal;
2510     LastVal = VA.getValNo();
2511
2512     if (VA.isRegLoc()) {
2513       EVT RegVT = VA.getLocVT();
2514       const TargetRegisterClass *RC;
2515       if (RegVT == MVT::i32)
2516         RC = &X86::GR32RegClass;
2517       else if (Is64Bit && RegVT == MVT::i64)
2518         RC = &X86::GR64RegClass;
2519       else if (RegVT == MVT::f32)
2520         RC = &X86::FR32RegClass;
2521       else if (RegVT == MVT::f64)
2522         RC = &X86::FR64RegClass;
2523       else if (RegVT.is512BitVector())
2524         RC = &X86::VR512RegClass;
2525       else if (RegVT.is256BitVector())
2526         RC = &X86::VR256RegClass;
2527       else if (RegVT.is128BitVector())
2528         RC = &X86::VR128RegClass;
2529       else if (RegVT == MVT::x86mmx)
2530         RC = &X86::VR64RegClass;
2531       else if (RegVT == MVT::i1)
2532         RC = &X86::VK1RegClass;
2533       else if (RegVT == MVT::v8i1)
2534         RC = &X86::VK8RegClass;
2535       else if (RegVT == MVT::v16i1)
2536         RC = &X86::VK16RegClass;
2537       else if (RegVT == MVT::v32i1)
2538         RC = &X86::VK32RegClass;
2539       else if (RegVT == MVT::v64i1)
2540         RC = &X86::VK64RegClass;
2541       else
2542         llvm_unreachable("Unknown argument type!");
2543
2544       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2545       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2546
2547       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2548       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2549       // right size.
2550       if (VA.getLocInfo() == CCValAssign::SExt)
2551         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2552                                DAG.getValueType(VA.getValVT()));
2553       else if (VA.getLocInfo() == CCValAssign::ZExt)
2554         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2555                                DAG.getValueType(VA.getValVT()));
2556       else if (VA.getLocInfo() == CCValAssign::BCvt)
2557         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2558
2559       if (VA.isExtInLoc()) {
2560         // Handle MMX values passed in XMM regs.
2561         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2562           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2563         else
2564           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2565       }
2566     } else {
2567       assert(VA.isMemLoc());
2568       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2569     }
2570
2571     // If value is passed via pointer - do a load.
2572     if (VA.getLocInfo() == CCValAssign::Indirect)
2573       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2574                              MachinePointerInfo(), false, false, false, 0);
2575
2576     InVals.push_back(ArgValue);
2577   }
2578
2579   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2580     // All x86 ABIs require that for returning structs by value we copy the
2581     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2582     // the argument into a virtual register so that we can access it from the
2583     // return points.
2584     if (Ins[i].Flags.isSRet()) {
2585       unsigned Reg = FuncInfo->getSRetReturnReg();
2586       if (!Reg) {
2587         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2588         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2589         FuncInfo->setSRetReturnReg(Reg);
2590       }
2591       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2592       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2593       break;
2594     }
2595   }
2596
2597   unsigned StackSize = CCInfo.getNextStackOffset();
2598   // Align stack specially for tail calls.
2599   if (FuncIsMadeTailCallSafe(CallConv,
2600                              MF.getTarget().Options.GuaranteedTailCallOpt))
2601     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2602
2603   // If the function takes variable number of arguments, make a frame index for
2604   // the start of the first vararg value... for expansion of llvm.va_start. We
2605   // can skip this if there are no va_start calls.
2606   if (MFI->hasVAStart() &&
2607       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2608                    CallConv != CallingConv::X86_ThisCall))) {
2609     FuncInfo->setVarArgsFrameIndex(
2610         MFI->CreateFixedObject(1, StackSize, true));
2611   }
2612
2613   MachineModuleInfo &MMI = MF.getMMI();
2614   const Function *WinEHParent = nullptr;
2615   if (MMI.hasWinEHFuncInfo(Fn))
2616     WinEHParent = MMI.getWinEHParent(Fn);
2617   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2618   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2619
2620   // Figure out if XMM registers are in use.
2621   assert(!(Subtarget->useSoftFloat() &&
2622            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2623          "SSE register cannot be used when SSE is disabled!");
2624
2625   // 64-bit calling conventions support varargs and register parameters, so we
2626   // have to do extra work to spill them in the prologue.
2627   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2628     // Find the first unallocated argument registers.
2629     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2630     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2631     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2632     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2633     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2634            "SSE register cannot be used when SSE is disabled!");
2635
2636     // Gather all the live in physical registers.
2637     SmallVector<SDValue, 6> LiveGPRs;
2638     SmallVector<SDValue, 8> LiveXMMRegs;
2639     SDValue ALVal;
2640     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2641       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2642       LiveGPRs.push_back(
2643           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2644     }
2645     if (!ArgXMMs.empty()) {
2646       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2647       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2648       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2649         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2650         LiveXMMRegs.push_back(
2651             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2652       }
2653     }
2654
2655     if (IsWin64) {
2656       // Get to the caller-allocated home save location.  Add 8 to account
2657       // for the return address.
2658       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2659       FuncInfo->setRegSaveFrameIndex(
2660           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2661       // Fixup to set vararg frame on shadow area (4 x i64).
2662       if (NumIntRegs < 4)
2663         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2664     } else {
2665       // For X86-64, if there are vararg parameters that are passed via
2666       // registers, then we must store them to their spots on the stack so
2667       // they may be loaded by deferencing the result of va_next.
2668       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2669       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2670       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2671           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2672     }
2673
2674     // Store the integer parameter registers.
2675     SmallVector<SDValue, 8> MemOps;
2676     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2677                                       getPointerTy(DAG.getDataLayout()));
2678     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2679     for (SDValue Val : LiveGPRs) {
2680       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2681                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2682       SDValue Store =
2683         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2684                      MachinePointerInfo::getFixedStack(
2685                        FuncInfo->getRegSaveFrameIndex(), Offset),
2686                      false, false, 0);
2687       MemOps.push_back(Store);
2688       Offset += 8;
2689     }
2690
2691     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2692       // Now store the XMM (fp + vector) parameter registers.
2693       SmallVector<SDValue, 12> SaveXMMOps;
2694       SaveXMMOps.push_back(Chain);
2695       SaveXMMOps.push_back(ALVal);
2696       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2697                              FuncInfo->getRegSaveFrameIndex(), dl));
2698       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2699                              FuncInfo->getVarArgsFPOffset(), dl));
2700       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2701                         LiveXMMRegs.end());
2702       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2703                                    MVT::Other, SaveXMMOps));
2704     }
2705
2706     if (!MemOps.empty())
2707       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2708   } else if (IsWin64 && IsWinEHOutlined) {
2709     // Get to the caller-allocated home save location.  Add 8 to account
2710     // for the return address.
2711     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2712     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2713         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2714
2715     MMI.getWinEHFuncInfo(Fn)
2716         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2717         FuncInfo->getRegSaveFrameIndex();
2718
2719     // Store the second integer parameter (rdx) into rsp+16 relative to the
2720     // stack pointer at the entry of the function.
2721     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2722                                       getPointerTy(DAG.getDataLayout()));
2723     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2724     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2725     Chain = DAG.getStore(
2726         Val.getValue(1), dl, Val, RSFIN,
2727         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2728         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2729   }
2730
2731   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2732     // Find the largest legal vector type.
2733     MVT VecVT = MVT::Other;
2734     // FIXME: Only some x86_32 calling conventions support AVX512.
2735     if (Subtarget->hasAVX512() &&
2736         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2737                      CallConv == CallingConv::Intel_OCL_BI)))
2738       VecVT = MVT::v16f32;
2739     else if (Subtarget->hasAVX())
2740       VecVT = MVT::v8f32;
2741     else if (Subtarget->hasSSE2())
2742       VecVT = MVT::v4f32;
2743
2744     // We forward some GPRs and some vector types.
2745     SmallVector<MVT, 2> RegParmTypes;
2746     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2747     RegParmTypes.push_back(IntVT);
2748     if (VecVT != MVT::Other)
2749       RegParmTypes.push_back(VecVT);
2750
2751     // Compute the set of forwarded registers. The rest are scratch.
2752     SmallVectorImpl<ForwardedRegister> &Forwards =
2753         FuncInfo->getForwardedMustTailRegParms();
2754     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2755
2756     // Conservatively forward AL on x86_64, since it might be used for varargs.
2757     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2758       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2759       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2760     }
2761
2762     // Copy all forwards from physical to virtual registers.
2763     for (ForwardedRegister &F : Forwards) {
2764       // FIXME: Can we use a less constrained schedule?
2765       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2766       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2767       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2768     }
2769   }
2770
2771   // Some CCs need callee pop.
2772   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2773                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2774     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2775   } else {
2776     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2777     // If this is an sret function, the return should pop the hidden pointer.
2778     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2779         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2780         argsAreStructReturn(Ins) == StackStructReturn)
2781       FuncInfo->setBytesToPopOnReturn(4);
2782   }
2783
2784   if (!Is64Bit) {
2785     // RegSaveFrameIndex is X86-64 only.
2786     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2787     if (CallConv == CallingConv::X86_FastCall ||
2788         CallConv == CallingConv::X86_ThisCall)
2789       // fastcc functions can't have varargs.
2790       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2791   }
2792
2793   FuncInfo->setArgumentStackSize(StackSize);
2794
2795   if (IsWinEHParent) {
2796     if (Is64Bit) {
2797       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2798       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2799       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2800       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2801       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2802                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2803                            /*isVolatile=*/true,
2804                            /*isNonTemporal=*/false, /*Alignment=*/0);
2805     } else {
2806       // Functions using Win32 EH are considered to have opaque SP adjustments
2807       // to force local variables to be addressed from the frame or base
2808       // pointers.
2809       MFI->setHasOpaqueSPAdjustment(true);
2810     }
2811   }
2812
2813   return Chain;
2814 }
2815
2816 SDValue
2817 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2818                                     SDValue StackPtr, SDValue Arg,
2819                                     SDLoc dl, SelectionDAG &DAG,
2820                                     const CCValAssign &VA,
2821                                     ISD::ArgFlagsTy Flags) const {
2822   unsigned LocMemOffset = VA.getLocMemOffset();
2823   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2824   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2825                        StackPtr, PtrOff);
2826   if (Flags.isByVal())
2827     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2828
2829   return DAG.getStore(Chain, dl, Arg, PtrOff,
2830                       MachinePointerInfo::getStack(LocMemOffset),
2831                       false, false, 0);
2832 }
2833
2834 /// Emit a load of return address if tail call
2835 /// optimization is performed and it is required.
2836 SDValue
2837 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2838                                            SDValue &OutRetAddr, SDValue Chain,
2839                                            bool IsTailCall, bool Is64Bit,
2840                                            int FPDiff, SDLoc dl) const {
2841   // Adjust the Return address stack slot.
2842   EVT VT = getPointerTy(DAG.getDataLayout());
2843   OutRetAddr = getReturnAddressFrameIndex(DAG);
2844
2845   // Load the "old" Return address.
2846   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2847                            false, false, false, 0);
2848   return SDValue(OutRetAddr.getNode(), 1);
2849 }
2850
2851 /// Emit a store of the return address if tail call
2852 /// optimization is performed and it is required (FPDiff!=0).
2853 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2854                                         SDValue Chain, SDValue RetAddrFrIdx,
2855                                         EVT PtrVT, unsigned SlotSize,
2856                                         int FPDiff, SDLoc dl) {
2857   // Store the return address to the appropriate stack slot.
2858   if (!FPDiff) return Chain;
2859   // Calculate the new stack slot for the return address.
2860   int NewReturnAddrFI =
2861     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2862                                          false);
2863   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2864   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2865                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2866                        false, false, 0);
2867   return Chain;
2868 }
2869
2870 SDValue
2871 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2872                              SmallVectorImpl<SDValue> &InVals) const {
2873   SelectionDAG &DAG                     = CLI.DAG;
2874   SDLoc &dl                             = CLI.DL;
2875   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2876   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2877   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2878   SDValue Chain                         = CLI.Chain;
2879   SDValue Callee                        = CLI.Callee;
2880   CallingConv::ID CallConv              = CLI.CallConv;
2881   bool &isTailCall                      = CLI.IsTailCall;
2882   bool isVarArg                         = CLI.IsVarArg;
2883
2884   MachineFunction &MF = DAG.getMachineFunction();
2885   bool Is64Bit        = Subtarget->is64Bit();
2886   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2887   StructReturnType SR = callIsStructReturn(Outs);
2888   bool IsSibcall      = false;
2889   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2890   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2891
2892   if (Attr.getValueAsString() == "true")
2893     isTailCall = false;
2894
2895   if (Subtarget->isPICStyleGOT() &&
2896       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2897     // If we are using a GOT, disable tail calls to external symbols with
2898     // default visibility. Tail calling such a symbol requires using a GOT
2899     // relocation, which forces early binding of the symbol. This breaks code
2900     // that require lazy function symbol resolution. Using musttail or
2901     // GuaranteedTailCallOpt will override this.
2902     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2903     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2904                G->getGlobal()->hasDefaultVisibility()))
2905       isTailCall = false;
2906   }
2907
2908   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2909   if (IsMustTail) {
2910     // Force this to be a tail call.  The verifier rules are enough to ensure
2911     // that we can lower this successfully without moving the return address
2912     // around.
2913     isTailCall = true;
2914   } else if (isTailCall) {
2915     // Check if it's really possible to do a tail call.
2916     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2917                     isVarArg, SR != NotStructReturn,
2918                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2919                     Outs, OutVals, Ins, DAG);
2920
2921     // Sibcalls are automatically detected tailcalls which do not require
2922     // ABI changes.
2923     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2924       IsSibcall = true;
2925
2926     if (isTailCall)
2927       ++NumTailCalls;
2928   }
2929
2930   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2931          "Var args not supported with calling convention fastcc, ghc or hipe");
2932
2933   // Analyze operands of the call, assigning locations to each operand.
2934   SmallVector<CCValAssign, 16> ArgLocs;
2935   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2936
2937   // Allocate shadow area for Win64
2938   if (IsWin64)
2939     CCInfo.AllocateStack(32, 8);
2940
2941   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2942
2943   // Get a count of how many bytes are to be pushed on the stack.
2944   unsigned NumBytes = CCInfo.getNextStackOffset();
2945   if (IsSibcall)
2946     // This is a sibcall. The memory operands are available in caller's
2947     // own caller's stack.
2948     NumBytes = 0;
2949   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2950            IsTailCallConvention(CallConv))
2951     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2952
2953   int FPDiff = 0;
2954   if (isTailCall && !IsSibcall && !IsMustTail) {
2955     // Lower arguments at fp - stackoffset + fpdiff.
2956     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2957
2958     FPDiff = NumBytesCallerPushed - NumBytes;
2959
2960     // Set the delta of movement of the returnaddr stackslot.
2961     // But only set if delta is greater than previous delta.
2962     if (FPDiff < X86Info->getTCReturnAddrDelta())
2963       X86Info->setTCReturnAddrDelta(FPDiff);
2964   }
2965
2966   unsigned NumBytesToPush = NumBytes;
2967   unsigned NumBytesToPop = NumBytes;
2968
2969   // If we have an inalloca argument, all stack space has already been allocated
2970   // for us and be right at the top of the stack.  We don't support multiple
2971   // arguments passed in memory when using inalloca.
2972   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2973     NumBytesToPush = 0;
2974     if (!ArgLocs.back().isMemLoc())
2975       report_fatal_error("cannot use inalloca attribute on a register "
2976                          "parameter");
2977     if (ArgLocs.back().getLocMemOffset() != 0)
2978       report_fatal_error("any parameter with the inalloca attribute must be "
2979                          "the only memory argument");
2980   }
2981
2982   if (!IsSibcall)
2983     Chain = DAG.getCALLSEQ_START(
2984         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2985
2986   SDValue RetAddrFrIdx;
2987   // Load return address for tail calls.
2988   if (isTailCall && FPDiff)
2989     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2990                                     Is64Bit, FPDiff, dl);
2991
2992   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2993   SmallVector<SDValue, 8> MemOpChains;
2994   SDValue StackPtr;
2995
2996   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2997   // of tail call optimization arguments are handle later.
2998   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2999   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3000     // Skip inalloca arguments, they have already been written.
3001     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3002     if (Flags.isInAlloca())
3003       continue;
3004
3005     CCValAssign &VA = ArgLocs[i];
3006     EVT RegVT = VA.getLocVT();
3007     SDValue Arg = OutVals[i];
3008     bool isByVal = Flags.isByVal();
3009
3010     // Promote the value if needed.
3011     switch (VA.getLocInfo()) {
3012     default: llvm_unreachable("Unknown loc info!");
3013     case CCValAssign::Full: break;
3014     case CCValAssign::SExt:
3015       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3016       break;
3017     case CCValAssign::ZExt:
3018       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
3019       break;
3020     case CCValAssign::AExt:
3021       if (Arg.getValueType().isVector() &&
3022           Arg.getValueType().getScalarType() == MVT::i1)
3023         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3024       else if (RegVT.is128BitVector()) {
3025         // Special case: passing MMX values in XMM registers.
3026         Arg = DAG.getBitcast(MVT::i64, Arg);
3027         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3028         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3029       } else
3030         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3031       break;
3032     case CCValAssign::BCvt:
3033       Arg = DAG.getBitcast(RegVT, Arg);
3034       break;
3035     case CCValAssign::Indirect: {
3036       // Store the argument.
3037       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3038       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3039       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3040                            MachinePointerInfo::getFixedStack(FI),
3041                            false, false, 0);
3042       Arg = SpillSlot;
3043       break;
3044     }
3045     }
3046
3047     if (VA.isRegLoc()) {
3048       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3049       if (isVarArg && IsWin64) {
3050         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3051         // shadow reg if callee is a varargs function.
3052         unsigned ShadowReg = 0;
3053         switch (VA.getLocReg()) {
3054         case X86::XMM0: ShadowReg = X86::RCX; break;
3055         case X86::XMM1: ShadowReg = X86::RDX; break;
3056         case X86::XMM2: ShadowReg = X86::R8; break;
3057         case X86::XMM3: ShadowReg = X86::R9; break;
3058         }
3059         if (ShadowReg)
3060           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3061       }
3062     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3063       assert(VA.isMemLoc());
3064       if (!StackPtr.getNode())
3065         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3066                                       getPointerTy(DAG.getDataLayout()));
3067       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3068                                              dl, DAG, VA, Flags));
3069     }
3070   }
3071
3072   if (!MemOpChains.empty())
3073     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3074
3075   if (Subtarget->isPICStyleGOT()) {
3076     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3077     // GOT pointer.
3078     if (!isTailCall) {
3079       RegsToPass.push_back(std::make_pair(
3080           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3081                                           getPointerTy(DAG.getDataLayout()))));
3082     } else {
3083       // If we are tail calling and generating PIC/GOT style code load the
3084       // address of the callee into ECX. The value in ecx is used as target of
3085       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3086       // for tail calls on PIC/GOT architectures. Normally we would just put the
3087       // address of GOT into ebx and then call target@PLT. But for tail calls
3088       // ebx would be restored (since ebx is callee saved) before jumping to the
3089       // target@PLT.
3090
3091       // Note: The actual moving to ECX is done further down.
3092       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3093       if (G && !G->getGlobal()->hasLocalLinkage() &&
3094           G->getGlobal()->hasDefaultVisibility())
3095         Callee = LowerGlobalAddress(Callee, DAG);
3096       else if (isa<ExternalSymbolSDNode>(Callee))
3097         Callee = LowerExternalSymbol(Callee, DAG);
3098     }
3099   }
3100
3101   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3102     // From AMD64 ABI document:
3103     // For calls that may call functions that use varargs or stdargs
3104     // (prototype-less calls or calls to functions containing ellipsis (...) in
3105     // the declaration) %al is used as hidden argument to specify the number
3106     // of SSE registers used. The contents of %al do not need to match exactly
3107     // the number of registers, but must be an ubound on the number of SSE
3108     // registers used and is in the range 0 - 8 inclusive.
3109
3110     // Count the number of XMM registers allocated.
3111     static const MCPhysReg XMMArgRegs[] = {
3112       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3113       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3114     };
3115     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3116     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3117            && "SSE registers cannot be used when SSE is disabled");
3118
3119     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3120                                         DAG.getConstant(NumXMMRegs, dl,
3121                                                         MVT::i8)));
3122   }
3123
3124   if (isVarArg && IsMustTail) {
3125     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3126     for (const auto &F : Forwards) {
3127       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3128       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3129     }
3130   }
3131
3132   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3133   // don't need this because the eligibility check rejects calls that require
3134   // shuffling arguments passed in memory.
3135   if (!IsSibcall && isTailCall) {
3136     // Force all the incoming stack arguments to be loaded from the stack
3137     // before any new outgoing arguments are stored to the stack, because the
3138     // outgoing stack slots may alias the incoming argument stack slots, and
3139     // the alias isn't otherwise explicit. This is slightly more conservative
3140     // than necessary, because it means that each store effectively depends
3141     // on every argument instead of just those arguments it would clobber.
3142     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3143
3144     SmallVector<SDValue, 8> MemOpChains2;
3145     SDValue FIN;
3146     int FI = 0;
3147     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3148       CCValAssign &VA = ArgLocs[i];
3149       if (VA.isRegLoc())
3150         continue;
3151       assert(VA.isMemLoc());
3152       SDValue Arg = OutVals[i];
3153       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3154       // Skip inalloca arguments.  They don't require any work.
3155       if (Flags.isInAlloca())
3156         continue;
3157       // Create frame index.
3158       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3159       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3160       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3161       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3162
3163       if (Flags.isByVal()) {
3164         // Copy relative to framepointer.
3165         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3166         if (!StackPtr.getNode())
3167           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3168                                         getPointerTy(DAG.getDataLayout()));
3169         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3170                              StackPtr, Source);
3171
3172         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3173                                                          ArgChain,
3174                                                          Flags, DAG, dl));
3175       } else {
3176         // Store relative to framepointer.
3177         MemOpChains2.push_back(
3178           DAG.getStore(ArgChain, dl, Arg, FIN,
3179                        MachinePointerInfo::getFixedStack(FI),
3180                        false, false, 0));
3181       }
3182     }
3183
3184     if (!MemOpChains2.empty())
3185       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3186
3187     // Store the return address to the appropriate stack slot.
3188     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3189                                      getPointerTy(DAG.getDataLayout()),
3190                                      RegInfo->getSlotSize(), FPDiff, dl);
3191   }
3192
3193   // Build a sequence of copy-to-reg nodes chained together with token chain
3194   // and flag operands which copy the outgoing args into registers.
3195   SDValue InFlag;
3196   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3197     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3198                              RegsToPass[i].second, InFlag);
3199     InFlag = Chain.getValue(1);
3200   }
3201
3202   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3203     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3204     // In the 64-bit large code model, we have to make all calls
3205     // through a register, since the call instruction's 32-bit
3206     // pc-relative offset may not be large enough to hold the whole
3207     // address.
3208   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3209     // If the callee is a GlobalAddress node (quite common, every direct call
3210     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3211     // it.
3212     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3213
3214     // We should use extra load for direct calls to dllimported functions in
3215     // non-JIT mode.
3216     const GlobalValue *GV = G->getGlobal();
3217     if (!GV->hasDLLImportStorageClass()) {
3218       unsigned char OpFlags = 0;
3219       bool ExtraLoad = false;
3220       unsigned WrapperKind = ISD::DELETED_NODE;
3221
3222       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3223       // external symbols most go through the PLT in PIC mode.  If the symbol
3224       // has hidden or protected visibility, or if it is static or local, then
3225       // we don't need to use the PLT - we can directly call it.
3226       if (Subtarget->isTargetELF() &&
3227           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3228           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3229         OpFlags = X86II::MO_PLT;
3230       } else if (Subtarget->isPICStyleStubAny() &&
3231                  !GV->isStrongDefinitionForLinker() &&
3232                  (!Subtarget->getTargetTriple().isMacOSX() ||
3233                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3234         // PC-relative references to external symbols should go through $stub,
3235         // unless we're building with the leopard linker or later, which
3236         // automatically synthesizes these stubs.
3237         OpFlags = X86II::MO_DARWIN_STUB;
3238       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3239                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3240         // If the function is marked as non-lazy, generate an indirect call
3241         // which loads from the GOT directly. This avoids runtime overhead
3242         // at the cost of eager binding (and one extra byte of encoding).
3243         OpFlags = X86II::MO_GOTPCREL;
3244         WrapperKind = X86ISD::WrapperRIP;
3245         ExtraLoad = true;
3246       }
3247
3248       Callee = DAG.getTargetGlobalAddress(
3249           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3250
3251       // Add a wrapper if needed.
3252       if (WrapperKind != ISD::DELETED_NODE)
3253         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3254                              getPointerTy(DAG.getDataLayout()), Callee);
3255       // Add extra indirection if needed.
3256       if (ExtraLoad)
3257         Callee = DAG.getLoad(
3258             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3259             MachinePointerInfo::getGOT(), false, false, false, 0);
3260     }
3261   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3262     unsigned char OpFlags = 0;
3263
3264     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3265     // external symbols should go through the PLT.
3266     if (Subtarget->isTargetELF() &&
3267         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3268       OpFlags = X86II::MO_PLT;
3269     } else if (Subtarget->isPICStyleStubAny() &&
3270                (!Subtarget->getTargetTriple().isMacOSX() ||
3271                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3272       // PC-relative references to external symbols should go through $stub,
3273       // unless we're building with the leopard linker or later, which
3274       // automatically synthesizes these stubs.
3275       OpFlags = X86II::MO_DARWIN_STUB;
3276     }
3277
3278     Callee = DAG.getTargetExternalSymbol(
3279         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3280   } else if (Subtarget->isTarget64BitILP32() &&
3281              Callee->getValueType(0) == MVT::i32) {
3282     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3283     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3284   }
3285
3286   // Returns a chain & a flag for retval copy to use.
3287   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3288   SmallVector<SDValue, 8> Ops;
3289
3290   if (!IsSibcall && isTailCall) {
3291     Chain = DAG.getCALLSEQ_END(Chain,
3292                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3293                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3294     InFlag = Chain.getValue(1);
3295   }
3296
3297   Ops.push_back(Chain);
3298   Ops.push_back(Callee);
3299
3300   if (isTailCall)
3301     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3302
3303   // Add argument registers to the end of the list so that they are known live
3304   // into the call.
3305   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3306     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3307                                   RegsToPass[i].second.getValueType()));
3308
3309   // Add a register mask operand representing the call-preserved registers.
3310   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3311   assert(Mask && "Missing call preserved mask for calling convention");
3312
3313   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3314   // the function clobbers all registers. If an exception is thrown, the runtime
3315   // will not restore CSRs.
3316   // FIXME: Model this more precisely so that we can register allocate across
3317   // the normal edge and spill and fill across the exceptional edge.
3318   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3319     const Function *CallerFn = MF.getFunction();
3320     EHPersonality Pers =
3321         CallerFn->hasPersonalityFn()
3322             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3323             : EHPersonality::Unknown;
3324     if (isMSVCEHPersonality(Pers))
3325       Mask = RegInfo->getNoPreservedMask();
3326   }
3327
3328   Ops.push_back(DAG.getRegisterMask(Mask));
3329
3330   if (InFlag.getNode())
3331     Ops.push_back(InFlag);
3332
3333   if (isTailCall) {
3334     // We used to do:
3335     //// If this is the first return lowered for this function, add the regs
3336     //// to the liveout set for the function.
3337     // This isn't right, although it's probably harmless on x86; liveouts
3338     // should be computed from returns not tail calls.  Consider a void
3339     // function making a tail call to a function returning int.
3340     MF.getFrameInfo()->setHasTailCall();
3341     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3342   }
3343
3344   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3345   InFlag = Chain.getValue(1);
3346
3347   // Create the CALLSEQ_END node.
3348   unsigned NumBytesForCalleeToPop;
3349   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3350                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3351     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3352   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3353            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3354            SR == StackStructReturn)
3355     // If this is a call to a struct-return function, the callee
3356     // pops the hidden struct pointer, so we have to push it back.
3357     // This is common for Darwin/X86, Linux & Mingw32 targets.
3358     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3359     NumBytesForCalleeToPop = 4;
3360   else
3361     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3362
3363   // Returns a flag for retval copy to use.
3364   if (!IsSibcall) {
3365     Chain = DAG.getCALLSEQ_END(Chain,
3366                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3367                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3368                                                      true),
3369                                InFlag, dl);
3370     InFlag = Chain.getValue(1);
3371   }
3372
3373   // Handle result values, copying them out of physregs into vregs that we
3374   // return.
3375   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3376                          Ins, dl, DAG, InVals);
3377 }
3378
3379 //===----------------------------------------------------------------------===//
3380 //                Fast Calling Convention (tail call) implementation
3381 //===----------------------------------------------------------------------===//
3382
3383 //  Like std call, callee cleans arguments, convention except that ECX is
3384 //  reserved for storing the tail called function address. Only 2 registers are
3385 //  free for argument passing (inreg). Tail call optimization is performed
3386 //  provided:
3387 //                * tailcallopt is enabled
3388 //                * caller/callee are fastcc
3389 //  On X86_64 architecture with GOT-style position independent code only local
3390 //  (within module) calls are supported at the moment.
3391 //  To keep the stack aligned according to platform abi the function
3392 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3393 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3394 //  If a tail called function callee has more arguments than the caller the
3395 //  caller needs to make sure that there is room to move the RETADDR to. This is
3396 //  achieved by reserving an area the size of the argument delta right after the
3397 //  original RETADDR, but before the saved framepointer or the spilled registers
3398 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3399 //  stack layout:
3400 //    arg1
3401 //    arg2
3402 //    RETADDR
3403 //    [ new RETADDR
3404 //      move area ]
3405 //    (possible EBP)
3406 //    ESI
3407 //    EDI
3408 //    local1 ..
3409
3410 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3411 /// for a 16 byte align requirement.
3412 unsigned
3413 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3414                                                SelectionDAG& DAG) const {
3415   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3416   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3417   unsigned StackAlignment = TFI.getStackAlignment();
3418   uint64_t AlignMask = StackAlignment - 1;
3419   int64_t Offset = StackSize;
3420   unsigned SlotSize = RegInfo->getSlotSize();
3421   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3422     // Number smaller than 12 so just add the difference.
3423     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3424   } else {
3425     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3426     Offset = ((~AlignMask) & Offset) + StackAlignment +
3427       (StackAlignment-SlotSize);
3428   }
3429   return Offset;
3430 }
3431
3432 /// MatchingStackOffset - Return true if the given stack call argument is
3433 /// already available in the same position (relatively) of the caller's
3434 /// incoming argument stack.
3435 static
3436 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3437                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3438                          const X86InstrInfo *TII) {
3439   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3440   int FI = INT_MAX;
3441   if (Arg.getOpcode() == ISD::CopyFromReg) {
3442     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3443     if (!TargetRegisterInfo::isVirtualRegister(VR))
3444       return false;
3445     MachineInstr *Def = MRI->getVRegDef(VR);
3446     if (!Def)
3447       return false;
3448     if (!Flags.isByVal()) {
3449       if (!TII->isLoadFromStackSlot(Def, FI))
3450         return false;
3451     } else {
3452       unsigned Opcode = Def->getOpcode();
3453       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3454            Opcode == X86::LEA64_32r) &&
3455           Def->getOperand(1).isFI()) {
3456         FI = Def->getOperand(1).getIndex();
3457         Bytes = Flags.getByValSize();
3458       } else
3459         return false;
3460     }
3461   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3462     if (Flags.isByVal())
3463       // ByVal argument is passed in as a pointer but it's now being
3464       // dereferenced. e.g.
3465       // define @foo(%struct.X* %A) {
3466       //   tail call @bar(%struct.X* byval %A)
3467       // }
3468       return false;
3469     SDValue Ptr = Ld->getBasePtr();
3470     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3471     if (!FINode)
3472       return false;
3473     FI = FINode->getIndex();
3474   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3475     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3476     FI = FINode->getIndex();
3477     Bytes = Flags.getByValSize();
3478   } else
3479     return false;
3480
3481   assert(FI != INT_MAX);
3482   if (!MFI->isFixedObjectIndex(FI))
3483     return false;
3484   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3485 }
3486
3487 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3488 /// for tail call optimization. Targets which want to do tail call
3489 /// optimization should implement this function.
3490 bool
3491 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3492                                                      CallingConv::ID CalleeCC,
3493                                                      bool isVarArg,
3494                                                      bool isCalleeStructRet,
3495                                                      bool isCallerStructRet,
3496                                                      Type *RetTy,
3497                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3498                                     const SmallVectorImpl<SDValue> &OutVals,
3499                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3500                                                      SelectionDAG &DAG) const {
3501   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3502     return false;
3503
3504   // If -tailcallopt is specified, make fastcc functions tail-callable.
3505   const MachineFunction &MF = DAG.getMachineFunction();
3506   const Function *CallerF = MF.getFunction();
3507
3508   // If the function return type is x86_fp80 and the callee return type is not,
3509   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3510   // perform a tailcall optimization here.
3511   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3512     return false;
3513
3514   CallingConv::ID CallerCC = CallerF->getCallingConv();
3515   bool CCMatch = CallerCC == CalleeCC;
3516   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3517   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3518
3519   // Win64 functions have extra shadow space for argument homing. Don't do the
3520   // sibcall if the caller and callee have mismatched expectations for this
3521   // space.
3522   if (IsCalleeWin64 != IsCallerWin64)
3523     return false;
3524
3525   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3526     if (IsTailCallConvention(CalleeCC) && CCMatch)
3527       return true;
3528     return false;
3529   }
3530
3531   // Look for obvious safe cases to perform tail call optimization that do not
3532   // require ABI changes. This is what gcc calls sibcall.
3533
3534   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3535   // emit a special epilogue.
3536   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3537   if (RegInfo->needsStackRealignment(MF))
3538     return false;
3539
3540   // Also avoid sibcall optimization if either caller or callee uses struct
3541   // return semantics.
3542   if (isCalleeStructRet || isCallerStructRet)
3543     return false;
3544
3545   // An stdcall/thiscall caller is expected to clean up its arguments; the
3546   // callee isn't going to do that.
3547   // FIXME: this is more restrictive than needed. We could produce a tailcall
3548   // when the stack adjustment matches. For example, with a thiscall that takes
3549   // only one argument.
3550   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3551                    CallerCC == CallingConv::X86_ThisCall))
3552     return false;
3553
3554   // Do not sibcall optimize vararg calls unless all arguments are passed via
3555   // registers.
3556   if (isVarArg && !Outs.empty()) {
3557
3558     // Optimizing for varargs on Win64 is unlikely to be safe without
3559     // additional testing.
3560     if (IsCalleeWin64 || IsCallerWin64)
3561       return false;
3562
3563     SmallVector<CCValAssign, 16> ArgLocs;
3564     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3565                    *DAG.getContext());
3566
3567     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3568     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3569       if (!ArgLocs[i].isRegLoc())
3570         return false;
3571   }
3572
3573   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3574   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3575   // this into a sibcall.
3576   bool Unused = false;
3577   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3578     if (!Ins[i].Used) {
3579       Unused = true;
3580       break;
3581     }
3582   }
3583   if (Unused) {
3584     SmallVector<CCValAssign, 16> RVLocs;
3585     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3586                    *DAG.getContext());
3587     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3588     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3589       CCValAssign &VA = RVLocs[i];
3590       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3591         return false;
3592     }
3593   }
3594
3595   // If the calling conventions do not match, then we'd better make sure the
3596   // results are returned in the same way as what the caller expects.
3597   if (!CCMatch) {
3598     SmallVector<CCValAssign, 16> RVLocs1;
3599     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3600                     *DAG.getContext());
3601     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3602
3603     SmallVector<CCValAssign, 16> RVLocs2;
3604     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3605                     *DAG.getContext());
3606     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3607
3608     if (RVLocs1.size() != RVLocs2.size())
3609       return false;
3610     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3611       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3612         return false;
3613       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3614         return false;
3615       if (RVLocs1[i].isRegLoc()) {
3616         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3617           return false;
3618       } else {
3619         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3620           return false;
3621       }
3622     }
3623   }
3624
3625   // If the callee takes no arguments then go on to check the results of the
3626   // call.
3627   if (!Outs.empty()) {
3628     // Check if stack adjustment is needed. For now, do not do this if any
3629     // argument is passed on the stack.
3630     SmallVector<CCValAssign, 16> ArgLocs;
3631     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3632                    *DAG.getContext());
3633
3634     // Allocate shadow area for Win64
3635     if (IsCalleeWin64)
3636       CCInfo.AllocateStack(32, 8);
3637
3638     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3639     if (CCInfo.getNextStackOffset()) {
3640       MachineFunction &MF = DAG.getMachineFunction();
3641       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3642         return false;
3643
3644       // Check if the arguments are already laid out in the right way as
3645       // the caller's fixed stack objects.
3646       MachineFrameInfo *MFI = MF.getFrameInfo();
3647       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3648       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3649       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3650         CCValAssign &VA = ArgLocs[i];
3651         SDValue Arg = OutVals[i];
3652         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3653         if (VA.getLocInfo() == CCValAssign::Indirect)
3654           return false;
3655         if (!VA.isRegLoc()) {
3656           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3657                                    MFI, MRI, TII))
3658             return false;
3659         }
3660       }
3661     }
3662
3663     // If the tailcall address may be in a register, then make sure it's
3664     // possible to register allocate for it. In 32-bit, the call address can
3665     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3666     // callee-saved registers are restored. These happen to be the same
3667     // registers used to pass 'inreg' arguments so watch out for those.
3668     if (!Subtarget->is64Bit() &&
3669         ((!isa<GlobalAddressSDNode>(Callee) &&
3670           !isa<ExternalSymbolSDNode>(Callee)) ||
3671          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3672       unsigned NumInRegs = 0;
3673       // In PIC we need an extra register to formulate the address computation
3674       // for the callee.
3675       unsigned MaxInRegs =
3676         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3677
3678       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3679         CCValAssign &VA = ArgLocs[i];
3680         if (!VA.isRegLoc())
3681           continue;
3682         unsigned Reg = VA.getLocReg();
3683         switch (Reg) {
3684         default: break;
3685         case X86::EAX: case X86::EDX: case X86::ECX:
3686           if (++NumInRegs == MaxInRegs)
3687             return false;
3688           break;
3689         }
3690       }
3691     }
3692   }
3693
3694   return true;
3695 }
3696
3697 FastISel *
3698 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3699                                   const TargetLibraryInfo *libInfo) const {
3700   return X86::createFastISel(funcInfo, libInfo);
3701 }
3702
3703 //===----------------------------------------------------------------------===//
3704 //                           Other Lowering Hooks
3705 //===----------------------------------------------------------------------===//
3706
3707 static bool MayFoldLoad(SDValue Op) {
3708   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3709 }
3710
3711 static bool MayFoldIntoStore(SDValue Op) {
3712   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3713 }
3714
3715 static bool isTargetShuffle(unsigned Opcode) {
3716   switch(Opcode) {
3717   default: return false;
3718   case X86ISD::BLENDI:
3719   case X86ISD::PSHUFB:
3720   case X86ISD::PSHUFD:
3721   case X86ISD::PSHUFHW:
3722   case X86ISD::PSHUFLW:
3723   case X86ISD::SHUFP:
3724   case X86ISD::PALIGNR:
3725   case X86ISD::MOVLHPS:
3726   case X86ISD::MOVLHPD:
3727   case X86ISD::MOVHLPS:
3728   case X86ISD::MOVLPS:
3729   case X86ISD::MOVLPD:
3730   case X86ISD::MOVSHDUP:
3731   case X86ISD::MOVSLDUP:
3732   case X86ISD::MOVDDUP:
3733   case X86ISD::MOVSS:
3734   case X86ISD::MOVSD:
3735   case X86ISD::UNPCKL:
3736   case X86ISD::UNPCKH:
3737   case X86ISD::VPERMILPI:
3738   case X86ISD::VPERM2X128:
3739   case X86ISD::VPERMI:
3740     return true;
3741   }
3742 }
3743
3744 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3745                                     SDValue V1, unsigned TargetMask,
3746                                     SelectionDAG &DAG) {
3747   switch(Opc) {
3748   default: llvm_unreachable("Unknown x86 shuffle node");
3749   case X86ISD::PSHUFD:
3750   case X86ISD::PSHUFHW:
3751   case X86ISD::PSHUFLW:
3752   case X86ISD::VPERMILPI:
3753   case X86ISD::VPERMI:
3754     return DAG.getNode(Opc, dl, VT, V1,
3755                        DAG.getConstant(TargetMask, dl, MVT::i8));
3756   }
3757 }
3758
3759 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3760                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3761   switch(Opc) {
3762   default: llvm_unreachable("Unknown x86 shuffle node");
3763   case X86ISD::MOVLHPS:
3764   case X86ISD::MOVLHPD:
3765   case X86ISD::MOVHLPS:
3766   case X86ISD::MOVLPS:
3767   case X86ISD::MOVLPD:
3768   case X86ISD::MOVSS:
3769   case X86ISD::MOVSD:
3770   case X86ISD::UNPCKL:
3771   case X86ISD::UNPCKH:
3772     return DAG.getNode(Opc, dl, VT, V1, V2);
3773   }
3774 }
3775
3776 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3777   MachineFunction &MF = DAG.getMachineFunction();
3778   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3779   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3780   int ReturnAddrIndex = FuncInfo->getRAIndex();
3781
3782   if (ReturnAddrIndex == 0) {
3783     // Set up a frame object for the return address.
3784     unsigned SlotSize = RegInfo->getSlotSize();
3785     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3786                                                            -(int64_t)SlotSize,
3787                                                            false);
3788     FuncInfo->setRAIndex(ReturnAddrIndex);
3789   }
3790
3791   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3792 }
3793
3794 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3795                                        bool hasSymbolicDisplacement) {
3796   // Offset should fit into 32 bit immediate field.
3797   if (!isInt<32>(Offset))
3798     return false;
3799
3800   // If we don't have a symbolic displacement - we don't have any extra
3801   // restrictions.
3802   if (!hasSymbolicDisplacement)
3803     return true;
3804
3805   // FIXME: Some tweaks might be needed for medium code model.
3806   if (M != CodeModel::Small && M != CodeModel::Kernel)
3807     return false;
3808
3809   // For small code model we assume that latest object is 16MB before end of 31
3810   // bits boundary. We may also accept pretty large negative constants knowing
3811   // that all objects are in the positive half of address space.
3812   if (M == CodeModel::Small && Offset < 16*1024*1024)
3813     return true;
3814
3815   // For kernel code model we know that all object resist in the negative half
3816   // of 32bits address space. We may not accept negative offsets, since they may
3817   // be just off and we may accept pretty large positive ones.
3818   if (M == CodeModel::Kernel && Offset >= 0)
3819     return true;
3820
3821   return false;
3822 }
3823
3824 /// isCalleePop - Determines whether the callee is required to pop its
3825 /// own arguments. Callee pop is necessary to support tail calls.
3826 bool X86::isCalleePop(CallingConv::ID CallingConv,
3827                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3828   switch (CallingConv) {
3829   default:
3830     return false;
3831   case CallingConv::X86_StdCall:
3832   case CallingConv::X86_FastCall:
3833   case CallingConv::X86_ThisCall:
3834     return !is64Bit;
3835   case CallingConv::Fast:
3836   case CallingConv::GHC:
3837   case CallingConv::HiPE:
3838     if (IsVarArg)
3839       return false;
3840     return TailCallOpt;
3841   }
3842 }
3843
3844 /// \brief Return true if the condition is an unsigned comparison operation.
3845 static bool isX86CCUnsigned(unsigned X86CC) {
3846   switch (X86CC) {
3847   default: llvm_unreachable("Invalid integer condition!");
3848   case X86::COND_E:     return true;
3849   case X86::COND_G:     return false;
3850   case X86::COND_GE:    return false;
3851   case X86::COND_L:     return false;
3852   case X86::COND_LE:    return false;
3853   case X86::COND_NE:    return true;
3854   case X86::COND_B:     return true;
3855   case X86::COND_A:     return true;
3856   case X86::COND_BE:    return true;
3857   case X86::COND_AE:    return true;
3858   }
3859   llvm_unreachable("covered switch fell through?!");
3860 }
3861
3862 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3863 /// specific condition code, returning the condition code and the LHS/RHS of the
3864 /// comparison to make.
3865 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3866                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3867   if (!isFP) {
3868     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3869       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3870         // X > -1   -> X == 0, jump !sign.
3871         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3872         return X86::COND_NS;
3873       }
3874       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3875         // X < 0   -> X == 0, jump on sign.
3876         return X86::COND_S;
3877       }
3878       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3879         // X < 1   -> X <= 0
3880         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3881         return X86::COND_LE;
3882       }
3883     }
3884
3885     switch (SetCCOpcode) {
3886     default: llvm_unreachable("Invalid integer condition!");
3887     case ISD::SETEQ:  return X86::COND_E;
3888     case ISD::SETGT:  return X86::COND_G;
3889     case ISD::SETGE:  return X86::COND_GE;
3890     case ISD::SETLT:  return X86::COND_L;
3891     case ISD::SETLE:  return X86::COND_LE;
3892     case ISD::SETNE:  return X86::COND_NE;
3893     case ISD::SETULT: return X86::COND_B;
3894     case ISD::SETUGT: return X86::COND_A;
3895     case ISD::SETULE: return X86::COND_BE;
3896     case ISD::SETUGE: return X86::COND_AE;
3897     }
3898   }
3899
3900   // First determine if it is required or is profitable to flip the operands.
3901
3902   // If LHS is a foldable load, but RHS is not, flip the condition.
3903   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3904       !ISD::isNON_EXTLoad(RHS.getNode())) {
3905     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3906     std::swap(LHS, RHS);
3907   }
3908
3909   switch (SetCCOpcode) {
3910   default: break;
3911   case ISD::SETOLT:
3912   case ISD::SETOLE:
3913   case ISD::SETUGT:
3914   case ISD::SETUGE:
3915     std::swap(LHS, RHS);
3916     break;
3917   }
3918
3919   // On a floating point condition, the flags are set as follows:
3920   // ZF  PF  CF   op
3921   //  0 | 0 | 0 | X > Y
3922   //  0 | 0 | 1 | X < Y
3923   //  1 | 0 | 0 | X == Y
3924   //  1 | 1 | 1 | unordered
3925   switch (SetCCOpcode) {
3926   default: llvm_unreachable("Condcode should be pre-legalized away");
3927   case ISD::SETUEQ:
3928   case ISD::SETEQ:   return X86::COND_E;
3929   case ISD::SETOLT:              // flipped
3930   case ISD::SETOGT:
3931   case ISD::SETGT:   return X86::COND_A;
3932   case ISD::SETOLE:              // flipped
3933   case ISD::SETOGE:
3934   case ISD::SETGE:   return X86::COND_AE;
3935   case ISD::SETUGT:              // flipped
3936   case ISD::SETULT:
3937   case ISD::SETLT:   return X86::COND_B;
3938   case ISD::SETUGE:              // flipped
3939   case ISD::SETULE:
3940   case ISD::SETLE:   return X86::COND_BE;
3941   case ISD::SETONE:
3942   case ISD::SETNE:   return X86::COND_NE;
3943   case ISD::SETUO:   return X86::COND_P;
3944   case ISD::SETO:    return X86::COND_NP;
3945   case ISD::SETOEQ:
3946   case ISD::SETUNE:  return X86::COND_INVALID;
3947   }
3948 }
3949
3950 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3951 /// code. Current x86 isa includes the following FP cmov instructions:
3952 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3953 static bool hasFPCMov(unsigned X86CC) {
3954   switch (X86CC) {
3955   default:
3956     return false;
3957   case X86::COND_B:
3958   case X86::COND_BE:
3959   case X86::COND_E:
3960   case X86::COND_P:
3961   case X86::COND_A:
3962   case X86::COND_AE:
3963   case X86::COND_NE:
3964   case X86::COND_NP:
3965     return true;
3966   }
3967 }
3968
3969 /// isFPImmLegal - Returns true if the target can instruction select the
3970 /// specified FP immediate natively. If false, the legalizer will
3971 /// materialize the FP immediate as a load from a constant pool.
3972 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3973   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3974     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3975       return true;
3976   }
3977   return false;
3978 }
3979
3980 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3981                                               ISD::LoadExtType ExtTy,
3982                                               EVT NewVT) const {
3983   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3984   // relocation target a movq or addq instruction: don't let the load shrink.
3985   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3986   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3987     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3988       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3989   return true;
3990 }
3991
3992 /// \brief Returns true if it is beneficial to convert a load of a constant
3993 /// to just the constant itself.
3994 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3995                                                           Type *Ty) const {
3996   assert(Ty->isIntegerTy());
3997
3998   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3999   if (BitSize == 0 || BitSize > 64)
4000     return false;
4001   return true;
4002 }
4003
4004 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
4005                                                 unsigned Index) const {
4006   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
4007     return false;
4008
4009   return (Index == 0 || Index == ResVT.getVectorNumElements());
4010 }
4011
4012 bool X86TargetLowering::isCheapToSpeculateCttz() const {
4013   // Speculate cttz only if we can directly use TZCNT.
4014   return Subtarget->hasBMI();
4015 }
4016
4017 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
4018   // Speculate ctlz only if we can directly use LZCNT.
4019   return Subtarget->hasLZCNT();
4020 }
4021
4022 /// isUndefInRange - Return true if every element in Mask, beginning
4023 /// from position Pos and ending in Pos+Size is undef.
4024 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4025   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4026     if (0 <= Mask[i])
4027       return false;
4028   return true;
4029 }
4030
4031 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
4032 /// the specified range (L, H].
4033 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4034   return (Val < 0) || (Val >= Low && Val < Hi);
4035 }
4036
4037 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
4038 /// specified value.
4039 static bool isUndefOrEqual(int Val, int CmpVal) {
4040   return (Val < 0 || Val == CmpVal);
4041 }
4042
4043 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
4044 /// from position Pos and ending in Pos+Size, falls within the specified
4045 /// sequential range (Low, Low+Size]. or is undef.
4046 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4047                                        unsigned Pos, unsigned Size, int Low) {
4048   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4049     if (!isUndefOrEqual(Mask[i], Low))
4050       return false;
4051   return true;
4052 }
4053
4054 /// isVEXTRACTIndex - Return true if the specified
4055 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4056 /// suitable for instruction that extract 128 or 256 bit vectors
4057 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4058   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4059   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4060     return false;
4061
4062   // The index should be aligned on a vecWidth-bit boundary.
4063   uint64_t Index =
4064     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065
4066   MVT VT = N->getSimpleValueType(0);
4067   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4068   bool Result = (Index * ElSize) % vecWidth == 0;
4069
4070   return Result;
4071 }
4072
4073 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4074 /// operand specifies a subvector insert that is suitable for input to
4075 /// insertion of 128 or 256-bit subvectors
4076 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4077   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4078   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4079     return false;
4080   // The index should be aligned on a vecWidth-bit boundary.
4081   uint64_t Index =
4082     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4083
4084   MVT VT = N->getSimpleValueType(0);
4085   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4086   bool Result = (Index * ElSize) % vecWidth == 0;
4087
4088   return Result;
4089 }
4090
4091 bool X86::isVINSERT128Index(SDNode *N) {
4092   return isVINSERTIndex(N, 128);
4093 }
4094
4095 bool X86::isVINSERT256Index(SDNode *N) {
4096   return isVINSERTIndex(N, 256);
4097 }
4098
4099 bool X86::isVEXTRACT128Index(SDNode *N) {
4100   return isVEXTRACTIndex(N, 128);
4101 }
4102
4103 bool X86::isVEXTRACT256Index(SDNode *N) {
4104   return isVEXTRACTIndex(N, 256);
4105 }
4106
4107 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4108   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4109   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4110     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4111
4112   uint64_t Index =
4113     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4114
4115   MVT VecVT = N->getOperand(0).getSimpleValueType();
4116   MVT ElVT = VecVT.getVectorElementType();
4117
4118   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4119   return Index / NumElemsPerChunk;
4120 }
4121
4122 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4123   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4124   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4125     llvm_unreachable("Illegal insert subvector for VINSERT");
4126
4127   uint64_t Index =
4128     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4129
4130   MVT VecVT = N->getSimpleValueType(0);
4131   MVT ElVT = VecVT.getVectorElementType();
4132
4133   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4134   return Index / NumElemsPerChunk;
4135 }
4136
4137 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4138 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4139 /// and VINSERTI128 instructions.
4140 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4141   return getExtractVEXTRACTImmediate(N, 128);
4142 }
4143
4144 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4145 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4146 /// and VINSERTI64x4 instructions.
4147 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4148   return getExtractVEXTRACTImmediate(N, 256);
4149 }
4150
4151 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4152 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4153 /// and VINSERTI128 instructions.
4154 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4155   return getInsertVINSERTImmediate(N, 128);
4156 }
4157
4158 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4159 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4160 /// and VINSERTI64x4 instructions.
4161 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4162   return getInsertVINSERTImmediate(N, 256);
4163 }
4164
4165 /// isZero - Returns true if Elt is a constant integer zero
4166 static bool isZero(SDValue V) {
4167   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4168   return C && C->isNullValue();
4169 }
4170
4171 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4172 /// constant +0.0.
4173 bool X86::isZeroNode(SDValue Elt) {
4174   if (isZero(Elt))
4175     return true;
4176   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4177     return CFP->getValueAPF().isPosZero();
4178   return false;
4179 }
4180
4181 /// getZeroVector - Returns a vector of specified type with all zero elements.
4182 ///
4183 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4184                              SelectionDAG &DAG, SDLoc dl) {
4185   assert(VT.isVector() && "Expected a vector type");
4186
4187   // Always build SSE zero vectors as <4 x i32> bitcasted
4188   // to their dest type. This ensures they get CSE'd.
4189   SDValue Vec;
4190   if (VT.is128BitVector()) {  // SSE
4191     if (Subtarget->hasSSE2()) {  // SSE2
4192       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4193       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4194     } else { // SSE1
4195       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4196       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4197     }
4198   } else if (VT.is256BitVector()) { // AVX
4199     if (Subtarget->hasInt256()) { // AVX2
4200       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4201       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4202       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4203     } else {
4204       // 256-bit logic and arithmetic instructions in AVX are all
4205       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4206       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4207       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4208       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4209     }
4210   } else if (VT.is512BitVector()) { // AVX-512
4211       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4212       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4213                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4214       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4215   } else if (VT.getScalarType() == MVT::i1) {
4216
4217     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4218             && "Unexpected vector type");
4219     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4220             && "Unexpected vector type");
4221     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4222     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4223     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4224   } else
4225     llvm_unreachable("Unexpected vector type");
4226
4227   return DAG.getBitcast(VT, Vec);
4228 }
4229
4230 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4231                                 SelectionDAG &DAG, SDLoc dl,
4232                                 unsigned vectorWidth) {
4233   assert((vectorWidth == 128 || vectorWidth == 256) &&
4234          "Unsupported vector width");
4235   EVT VT = Vec.getValueType();
4236   EVT ElVT = VT.getVectorElementType();
4237   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4238   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4239                                   VT.getVectorNumElements()/Factor);
4240
4241   // Extract from UNDEF is UNDEF.
4242   if (Vec.getOpcode() == ISD::UNDEF)
4243     return DAG.getUNDEF(ResultVT);
4244
4245   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4246   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4247
4248   // This is the index of the first element of the vectorWidth-bit chunk
4249   // we want.
4250   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4251                                * ElemsPerChunk);
4252
4253   // If the input is a buildvector just emit a smaller one.
4254   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4255     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4256                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4257                                     ElemsPerChunk));
4258
4259   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4260   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4261 }
4262
4263 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4264 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4265 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4266 /// instructions or a simple subregister reference. Idx is an index in the
4267 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4268 /// lowering EXTRACT_VECTOR_ELT operations easier.
4269 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4270                                    SelectionDAG &DAG, SDLoc dl) {
4271   assert((Vec.getValueType().is256BitVector() ||
4272           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4273   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4274 }
4275
4276 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4277 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4278                                    SelectionDAG &DAG, SDLoc dl) {
4279   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4280   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4281 }
4282
4283 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4284                                unsigned IdxVal, SelectionDAG &DAG,
4285                                SDLoc dl, unsigned vectorWidth) {
4286   assert((vectorWidth == 128 || vectorWidth == 256) &&
4287          "Unsupported vector width");
4288   // Inserting UNDEF is Result
4289   if (Vec.getOpcode() == ISD::UNDEF)
4290     return Result;
4291   EVT VT = Vec.getValueType();
4292   EVT ElVT = VT.getVectorElementType();
4293   EVT ResultVT = Result.getValueType();
4294
4295   // Insert the relevant vectorWidth bits.
4296   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4297
4298   // This is the index of the first element of the vectorWidth-bit chunk
4299   // we want.
4300   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4301                                * ElemsPerChunk);
4302
4303   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4304   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4305 }
4306
4307 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4308 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4309 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4310 /// simple superregister reference.  Idx is an index in the 128 bits
4311 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4312 /// lowering INSERT_VECTOR_ELT operations easier.
4313 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4314                                   SelectionDAG &DAG, SDLoc dl) {
4315   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4316
4317   // For insertion into the zero index (low half) of a 256-bit vector, it is
4318   // more efficient to generate a blend with immediate instead of an insert*128.
4319   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4320   // extend the subvector to the size of the result vector. Make sure that
4321   // we are not recursing on that node by checking for undef here.
4322   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4323       Result.getOpcode() != ISD::UNDEF) {
4324     EVT ResultVT = Result.getValueType();
4325     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4326     SDValue Undef = DAG.getUNDEF(ResultVT);
4327     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4328                                  Vec, ZeroIndex);
4329
4330     // The blend instruction, and therefore its mask, depend on the data type.
4331     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4332     if (ScalarType.isFloatingPoint()) {
4333       // Choose either vblendps (float) or vblendpd (double).
4334       unsigned ScalarSize = ScalarType.getSizeInBits();
4335       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4336       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4337       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4338       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4339     }
4340
4341     const X86Subtarget &Subtarget =
4342     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4343
4344     // AVX2 is needed for 256-bit integer blend support.
4345     // Integers must be cast to 32-bit because there is only vpblendd;
4346     // vpblendw can't be used for this because it has a handicapped mask.
4347
4348     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4349     // is still more efficient than using the wrong domain vinsertf128 that
4350     // will be created by InsertSubVector().
4351     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4352
4353     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4354     Vec256 = DAG.getBitcast(CastVT, Vec256);
4355     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4356     return DAG.getBitcast(ResultVT, Vec256);
4357   }
4358
4359   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4360 }
4361
4362 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4363                                   SelectionDAG &DAG, SDLoc dl) {
4364   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4365   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4366 }
4367
4368 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4369 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4370 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4371 /// large BUILD_VECTORS.
4372 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4373                                    unsigned NumElems, SelectionDAG &DAG,
4374                                    SDLoc dl) {
4375   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4376   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4377 }
4378
4379 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4380                                    unsigned NumElems, SelectionDAG &DAG,
4381                                    SDLoc dl) {
4382   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4383   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4384 }
4385
4386 /// getOnesVector - Returns a vector of specified type with all bits set.
4387 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4388 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4389 /// Then bitcast to their original type, ensuring they get CSE'd.
4390 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4391                              SDLoc dl) {
4392   assert(VT.isVector() && "Expected a vector type");
4393
4394   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4395   SDValue Vec;
4396   if (VT.is256BitVector()) {
4397     if (HasInt256) { // AVX2
4398       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4399       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4400     } else { // AVX
4401       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4402       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4403     }
4404   } else if (VT.is128BitVector()) {
4405     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4406   } else
4407     llvm_unreachable("Unexpected vector type");
4408
4409   return DAG.getBitcast(VT, Vec);
4410 }
4411
4412 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4413 /// operation of specified width.
4414 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4415                        SDValue V2) {
4416   unsigned NumElems = VT.getVectorNumElements();
4417   SmallVector<int, 8> Mask;
4418   Mask.push_back(NumElems);
4419   for (unsigned i = 1; i != NumElems; ++i)
4420     Mask.push_back(i);
4421   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4422 }
4423
4424 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4425 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4426                           SDValue V2) {
4427   unsigned NumElems = VT.getVectorNumElements();
4428   SmallVector<int, 8> Mask;
4429   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4430     Mask.push_back(i);
4431     Mask.push_back(i + NumElems);
4432   }
4433   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4434 }
4435
4436 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4437 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4438                           SDValue V2) {
4439   unsigned NumElems = VT.getVectorNumElements();
4440   SmallVector<int, 8> Mask;
4441   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4442     Mask.push_back(i + Half);
4443     Mask.push_back(i + NumElems + Half);
4444   }
4445   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4446 }
4447
4448 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4449 /// vector of zero or undef vector.  This produces a shuffle where the low
4450 /// element of V2 is swizzled into the zero/undef vector, landing at element
4451 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4452 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4453                                            bool IsZero,
4454                                            const X86Subtarget *Subtarget,
4455                                            SelectionDAG &DAG) {
4456   MVT VT = V2.getSimpleValueType();
4457   SDValue V1 = IsZero
4458     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4459   unsigned NumElems = VT.getVectorNumElements();
4460   SmallVector<int, 16> MaskVec;
4461   for (unsigned i = 0; i != NumElems; ++i)
4462     // If this is the insertion idx, put the low elt of V2 here.
4463     MaskVec.push_back(i == Idx ? NumElems : i);
4464   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4465 }
4466
4467 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4468 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4469 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4470 /// shuffles which use a single input multiple times, and in those cases it will
4471 /// adjust the mask to only have indices within that single input.
4472 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4473 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4474                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4475   unsigned NumElems = VT.getVectorNumElements();
4476   SDValue ImmN;
4477
4478   IsUnary = false;
4479   bool IsFakeUnary = false;
4480   switch(N->getOpcode()) {
4481   case X86ISD::BLENDI:
4482     ImmN = N->getOperand(N->getNumOperands()-1);
4483     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4484     break;
4485   case X86ISD::SHUFP:
4486     ImmN = N->getOperand(N->getNumOperands()-1);
4487     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4488     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4489     break;
4490   case X86ISD::UNPCKH:
4491     DecodeUNPCKHMask(VT, Mask);
4492     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4493     break;
4494   case X86ISD::UNPCKL:
4495     DecodeUNPCKLMask(VT, Mask);
4496     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4497     break;
4498   case X86ISD::MOVHLPS:
4499     DecodeMOVHLPSMask(NumElems, Mask);
4500     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4501     break;
4502   case X86ISD::MOVLHPS:
4503     DecodeMOVLHPSMask(NumElems, Mask);
4504     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4505     break;
4506   case X86ISD::PALIGNR:
4507     ImmN = N->getOperand(N->getNumOperands()-1);
4508     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4509     break;
4510   case X86ISD::PSHUFD:
4511   case X86ISD::VPERMILPI:
4512     ImmN = N->getOperand(N->getNumOperands()-1);
4513     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4514     IsUnary = true;
4515     break;
4516   case X86ISD::PSHUFHW:
4517     ImmN = N->getOperand(N->getNumOperands()-1);
4518     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4519     IsUnary = true;
4520     break;
4521   case X86ISD::PSHUFLW:
4522     ImmN = N->getOperand(N->getNumOperands()-1);
4523     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4524     IsUnary = true;
4525     break;
4526   case X86ISD::PSHUFB: {
4527     IsUnary = true;
4528     SDValue MaskNode = N->getOperand(1);
4529     while (MaskNode->getOpcode() == ISD::BITCAST)
4530       MaskNode = MaskNode->getOperand(0);
4531
4532     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4533       // If we have a build-vector, then things are easy.
4534       EVT VT = MaskNode.getValueType();
4535       assert(VT.isVector() &&
4536              "Can't produce a non-vector with a build_vector!");
4537       if (!VT.isInteger())
4538         return false;
4539
4540       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4541
4542       SmallVector<uint64_t, 32> RawMask;
4543       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4544         SDValue Op = MaskNode->getOperand(i);
4545         if (Op->getOpcode() == ISD::UNDEF) {
4546           RawMask.push_back((uint64_t)SM_SentinelUndef);
4547           continue;
4548         }
4549         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4550         if (!CN)
4551           return false;
4552         APInt MaskElement = CN->getAPIntValue();
4553
4554         // We now have to decode the element which could be any integer size and
4555         // extract each byte of it.
4556         for (int j = 0; j < NumBytesPerElement; ++j) {
4557           // Note that this is x86 and so always little endian: the low byte is
4558           // the first byte of the mask.
4559           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4560           MaskElement = MaskElement.lshr(8);
4561         }
4562       }
4563       DecodePSHUFBMask(RawMask, Mask);
4564       break;
4565     }
4566
4567     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4568     if (!MaskLoad)
4569       return false;
4570
4571     SDValue Ptr = MaskLoad->getBasePtr();
4572     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4573         Ptr->getOpcode() == X86ISD::WrapperRIP)
4574       Ptr = Ptr->getOperand(0);
4575
4576     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4577     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4578       return false;
4579
4580     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4581       DecodePSHUFBMask(C, Mask);
4582       if (Mask.empty())
4583         return false;
4584       break;
4585     }
4586
4587     return false;
4588   }
4589   case X86ISD::VPERMI:
4590     ImmN = N->getOperand(N->getNumOperands()-1);
4591     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4592     IsUnary = true;
4593     break;
4594   case X86ISD::MOVSS:
4595   case X86ISD::MOVSD:
4596     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4597     break;
4598   case X86ISD::VPERM2X128:
4599     ImmN = N->getOperand(N->getNumOperands()-1);
4600     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4601     if (Mask.empty()) return false;
4602     // Mask only contains negative index if an element is zero.
4603     if (std::any_of(Mask.begin(), Mask.end(),
4604                     [](int M){ return M == SM_SentinelZero; }))
4605       return false;
4606     break;
4607   case X86ISD::MOVSLDUP:
4608     DecodeMOVSLDUPMask(VT, Mask);
4609     IsUnary = true;
4610     break;
4611   case X86ISD::MOVSHDUP:
4612     DecodeMOVSHDUPMask(VT, Mask);
4613     IsUnary = true;
4614     break;
4615   case X86ISD::MOVDDUP:
4616     DecodeMOVDDUPMask(VT, Mask);
4617     IsUnary = true;
4618     break;
4619   case X86ISD::MOVLHPD:
4620   case X86ISD::MOVLPD:
4621   case X86ISD::MOVLPS:
4622     // Not yet implemented
4623     return false;
4624   default: llvm_unreachable("unknown target shuffle node");
4625   }
4626
4627   // If we have a fake unary shuffle, the shuffle mask is spread across two
4628   // inputs that are actually the same node. Re-map the mask to always point
4629   // into the first input.
4630   if (IsFakeUnary)
4631     for (int &M : Mask)
4632       if (M >= (int)Mask.size())
4633         M -= Mask.size();
4634
4635   return true;
4636 }
4637
4638 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4639 /// element of the result of the vector shuffle.
4640 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4641                                    unsigned Depth) {
4642   if (Depth == 6)
4643     return SDValue();  // Limit search depth.
4644
4645   SDValue V = SDValue(N, 0);
4646   EVT VT = V.getValueType();
4647   unsigned Opcode = V.getOpcode();
4648
4649   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4650   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4651     int Elt = SV->getMaskElt(Index);
4652
4653     if (Elt < 0)
4654       return DAG.getUNDEF(VT.getVectorElementType());
4655
4656     unsigned NumElems = VT.getVectorNumElements();
4657     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4658                                          : SV->getOperand(1);
4659     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4660   }
4661
4662   // Recurse into target specific vector shuffles to find scalars.
4663   if (isTargetShuffle(Opcode)) {
4664     MVT ShufVT = V.getSimpleValueType();
4665     unsigned NumElems = ShufVT.getVectorNumElements();
4666     SmallVector<int, 16> ShuffleMask;
4667     bool IsUnary;
4668
4669     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4670       return SDValue();
4671
4672     int Elt = ShuffleMask[Index];
4673     if (Elt < 0)
4674       return DAG.getUNDEF(ShufVT.getVectorElementType());
4675
4676     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4677                                          : N->getOperand(1);
4678     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4679                                Depth+1);
4680   }
4681
4682   // Actual nodes that may contain scalar elements
4683   if (Opcode == ISD::BITCAST) {
4684     V = V.getOperand(0);
4685     EVT SrcVT = V.getValueType();
4686     unsigned NumElems = VT.getVectorNumElements();
4687
4688     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4689       return SDValue();
4690   }
4691
4692   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4693     return (Index == 0) ? V.getOperand(0)
4694                         : DAG.getUNDEF(VT.getVectorElementType());
4695
4696   if (V.getOpcode() == ISD::BUILD_VECTOR)
4697     return V.getOperand(Index);
4698
4699   return SDValue();
4700 }
4701
4702 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4703 ///
4704 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4705                                        unsigned NumNonZero, unsigned NumZero,
4706                                        SelectionDAG &DAG,
4707                                        const X86Subtarget* Subtarget,
4708                                        const TargetLowering &TLI) {
4709   if (NumNonZero > 8)
4710     return SDValue();
4711
4712   SDLoc dl(Op);
4713   SDValue V;
4714   bool First = true;
4715
4716   // SSE4.1 - use PINSRB to insert each byte directly.
4717   if (Subtarget->hasSSE41()) {
4718     for (unsigned i = 0; i < 16; ++i) {
4719       bool isNonZero = (NonZeros & (1 << i)) != 0;
4720       if (isNonZero) {
4721         if (First) {
4722           if (NumZero)
4723             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4724           else
4725             V = DAG.getUNDEF(MVT::v16i8);
4726           First = false;
4727         }
4728         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4729                         MVT::v16i8, V, Op.getOperand(i),
4730                         DAG.getIntPtrConstant(i, dl));
4731       }
4732     }
4733
4734     return V;
4735   }
4736
4737   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4738   for (unsigned i = 0; i < 16; ++i) {
4739     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4740     if (ThisIsNonZero && 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
4748     if ((i & 1) != 0) {
4749       SDValue ThisElt, LastElt;
4750       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4751       if (LastIsNonZero) {
4752         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4753                               MVT::i16, Op.getOperand(i-1));
4754       }
4755       if (ThisIsNonZero) {
4756         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4757         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4758                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4759         if (LastIsNonZero)
4760           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4761       } else
4762         ThisElt = LastElt;
4763
4764       if (ThisElt.getNode())
4765         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4766                         DAG.getIntPtrConstant(i/2, dl));
4767     }
4768   }
4769
4770   return DAG.getBitcast(MVT::v16i8, V);
4771 }
4772
4773 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4774 ///
4775 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4776                                      unsigned NumNonZero, unsigned NumZero,
4777                                      SelectionDAG &DAG,
4778                                      const X86Subtarget* Subtarget,
4779                                      const TargetLowering &TLI) {
4780   if (NumNonZero > 4)
4781     return SDValue();
4782
4783   SDLoc dl(Op);
4784   SDValue V;
4785   bool First = true;
4786   for (unsigned i = 0; i < 8; ++i) {
4787     bool isNonZero = (NonZeros & (1 << i)) != 0;
4788     if (isNonZero) {
4789       if (First) {
4790         if (NumZero)
4791           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4792         else
4793           V = DAG.getUNDEF(MVT::v8i16);
4794         First = false;
4795       }
4796       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4797                       MVT::v8i16, V, Op.getOperand(i),
4798                       DAG.getIntPtrConstant(i, dl));
4799     }
4800   }
4801
4802   return V;
4803 }
4804
4805 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4806 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4807                                      const X86Subtarget *Subtarget,
4808                                      const TargetLowering &TLI) {
4809   // Find all zeroable elements.
4810   std::bitset<4> Zeroable;
4811   for (int i=0; i < 4; ++i) {
4812     SDValue Elt = Op->getOperand(i);
4813     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4814   }
4815   assert(Zeroable.size() - Zeroable.count() > 1 &&
4816          "We expect at least two non-zero elements!");
4817
4818   // We only know how to deal with build_vector nodes where elements are either
4819   // zeroable or extract_vector_elt with constant index.
4820   SDValue FirstNonZero;
4821   unsigned FirstNonZeroIdx;
4822   for (unsigned i=0; i < 4; ++i) {
4823     if (Zeroable[i])
4824       continue;
4825     SDValue Elt = Op->getOperand(i);
4826     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4827         !isa<ConstantSDNode>(Elt.getOperand(1)))
4828       return SDValue();
4829     // Make sure that this node is extracting from a 128-bit vector.
4830     MVT VT = Elt.getOperand(0).getSimpleValueType();
4831     if (!VT.is128BitVector())
4832       return SDValue();
4833     if (!FirstNonZero.getNode()) {
4834       FirstNonZero = Elt;
4835       FirstNonZeroIdx = i;
4836     }
4837   }
4838
4839   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4840   SDValue V1 = FirstNonZero.getOperand(0);
4841   MVT VT = V1.getSimpleValueType();
4842
4843   // See if this build_vector can be lowered as a blend with zero.
4844   SDValue Elt;
4845   unsigned EltMaskIdx, EltIdx;
4846   int Mask[4];
4847   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4848     if (Zeroable[EltIdx]) {
4849       // The zero vector will be on the right hand side.
4850       Mask[EltIdx] = EltIdx+4;
4851       continue;
4852     }
4853
4854     Elt = Op->getOperand(EltIdx);
4855     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4856     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4857     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4858       break;
4859     Mask[EltIdx] = EltIdx;
4860   }
4861
4862   if (EltIdx == 4) {
4863     // Let the shuffle legalizer deal with blend operations.
4864     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4865     if (V1.getSimpleValueType() != VT)
4866       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4867     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4868   }
4869
4870   // See if we can lower this build_vector to a INSERTPS.
4871   if (!Subtarget->hasSSE41())
4872     return SDValue();
4873
4874   SDValue V2 = Elt.getOperand(0);
4875   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4876     V1 = SDValue();
4877
4878   bool CanFold = true;
4879   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4880     if (Zeroable[i])
4881       continue;
4882
4883     SDValue Current = Op->getOperand(i);
4884     SDValue SrcVector = Current->getOperand(0);
4885     if (!V1.getNode())
4886       V1 = SrcVector;
4887     CanFold = SrcVector == V1 &&
4888       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4889   }
4890
4891   if (!CanFold)
4892     return SDValue();
4893
4894   assert(V1.getNode() && "Expected at least two non-zero elements!");
4895   if (V1.getSimpleValueType() != MVT::v4f32)
4896     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4897   if (V2.getSimpleValueType() != MVT::v4f32)
4898     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4899
4900   // Ok, we can emit an INSERTPS instruction.
4901   unsigned ZMask = Zeroable.to_ulong();
4902
4903   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4904   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4905   SDLoc DL(Op);
4906   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4907                                DAG.getIntPtrConstant(InsertPSMask, DL));
4908   return DAG.getBitcast(VT, Result);
4909 }
4910
4911 /// Return a vector logical shift node.
4912 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4913                          unsigned NumBits, SelectionDAG &DAG,
4914                          const TargetLowering &TLI, SDLoc dl) {
4915   assert(VT.is128BitVector() && "Unknown type for VShift");
4916   MVT ShVT = MVT::v2i64;
4917   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4918   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4919   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4920   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4921   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4922   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4923 }
4924
4925 static SDValue
4926 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4927
4928   // Check if the scalar load can be widened into a vector load. And if
4929   // the address is "base + cst" see if the cst can be "absorbed" into
4930   // the shuffle mask.
4931   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4932     SDValue Ptr = LD->getBasePtr();
4933     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4934       return SDValue();
4935     EVT PVT = LD->getValueType(0);
4936     if (PVT != MVT::i32 && PVT != MVT::f32)
4937       return SDValue();
4938
4939     int FI = -1;
4940     int64_t Offset = 0;
4941     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4942       FI = FINode->getIndex();
4943       Offset = 0;
4944     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4945                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4946       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4947       Offset = Ptr.getConstantOperandVal(1);
4948       Ptr = Ptr.getOperand(0);
4949     } else {
4950       return SDValue();
4951     }
4952
4953     // FIXME: 256-bit vector instructions don't require a strict alignment,
4954     // improve this code to support it better.
4955     unsigned RequiredAlign = VT.getSizeInBits()/8;
4956     SDValue Chain = LD->getChain();
4957     // Make sure the stack object alignment is at least 16 or 32.
4958     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4959     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4960       if (MFI->isFixedObjectIndex(FI)) {
4961         // Can't change the alignment. FIXME: It's possible to compute
4962         // the exact stack offset and reference FI + adjust offset instead.
4963         // If someone *really* cares about this. That's the way to implement it.
4964         return SDValue();
4965       } else {
4966         MFI->setObjectAlignment(FI, RequiredAlign);
4967       }
4968     }
4969
4970     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4971     // Ptr + (Offset & ~15).
4972     if (Offset < 0)
4973       return SDValue();
4974     if ((Offset % RequiredAlign) & 3)
4975       return SDValue();
4976     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4977     if (StartOffset) {
4978       SDLoc DL(Ptr);
4979       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4980                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4981     }
4982
4983     int EltNo = (Offset - StartOffset) >> 2;
4984     unsigned NumElems = VT.getVectorNumElements();
4985
4986     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4987     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4988                              LD->getPointerInfo().getWithOffset(StartOffset),
4989                              false, false, false, 0);
4990
4991     SmallVector<int, 8> Mask(NumElems, EltNo);
4992
4993     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4994   }
4995
4996   return SDValue();
4997 }
4998
4999 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
5000 /// elements can be replaced by a single large load which has the same value as
5001 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
5002 ///
5003 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
5004 ///
5005 /// FIXME: we'd also like to handle the case where the last elements are zero
5006 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
5007 /// There's even a handy isZeroNode for that purpose.
5008 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
5009                                         SDLoc &DL, SelectionDAG &DAG,
5010                                         bool isAfterLegalize) {
5011   unsigned NumElems = Elts.size();
5012
5013   LoadSDNode *LDBase = nullptr;
5014   unsigned LastLoadedElt = -1U;
5015
5016   // For each element in the initializer, see if we've found a load or an undef.
5017   // If we don't find an initial load element, or later load elements are
5018   // non-consecutive, bail out.
5019   for (unsigned i = 0; i < NumElems; ++i) {
5020     SDValue Elt = Elts[i];
5021     // Look through a bitcast.
5022     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
5023       Elt = Elt.getOperand(0);
5024     if (!Elt.getNode() ||
5025         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5026       return SDValue();
5027     if (!LDBase) {
5028       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5029         return SDValue();
5030       LDBase = cast<LoadSDNode>(Elt.getNode());
5031       LastLoadedElt = i;
5032       continue;
5033     }
5034     if (Elt.getOpcode() == ISD::UNDEF)
5035       continue;
5036
5037     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5038     EVT LdVT = Elt.getValueType();
5039     // Each loaded element must be the correct fractional portion of the
5040     // requested vector load.
5041     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5042       return SDValue();
5043     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5044       return SDValue();
5045     LastLoadedElt = i;
5046   }
5047
5048   // If we have found an entire vector of loads and undefs, then return a large
5049   // load of the entire vector width starting at the base pointer.  If we found
5050   // consecutive loads for the low half, generate a vzext_load node.
5051   if (LastLoadedElt == NumElems - 1) {
5052     assert(LDBase && "Did not find base load for merging consecutive loads");
5053     EVT EltVT = LDBase->getValueType(0);
5054     // Ensure that the input vector size for the merged loads matches the
5055     // cumulative size of the input elements.
5056     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5057       return SDValue();
5058
5059     if (isAfterLegalize &&
5060         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5061       return SDValue();
5062
5063     SDValue NewLd = SDValue();
5064
5065     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5066                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5067                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5068                         LDBase->getAlignment());
5069
5070     if (LDBase->hasAnyUseOfValue(1)) {
5071       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5072                                      SDValue(LDBase, 1),
5073                                      SDValue(NewLd.getNode(), 1));
5074       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5075       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5076                              SDValue(NewLd.getNode(), 1));
5077     }
5078
5079     return NewLd;
5080   }
5081
5082   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5083   //of a v4i32 / v4f32. It's probably worth generalizing.
5084   EVT EltVT = VT.getVectorElementType();
5085   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5086       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5087     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5088     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5089     SDValue ResNode =
5090         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5091                                 LDBase->getPointerInfo(),
5092                                 LDBase->getAlignment(),
5093                                 false/*isVolatile*/, true/*ReadMem*/,
5094                                 false/*WriteMem*/);
5095
5096     // Make sure the newly-created LOAD is in the same position as LDBase in
5097     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5098     // update uses of LDBase's output chain to use the TokenFactor.
5099     if (LDBase->hasAnyUseOfValue(1)) {
5100       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5101                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5102       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5103       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5104                              SDValue(ResNode.getNode(), 1));
5105     }
5106
5107     return DAG.getBitcast(VT, ResNode);
5108   }
5109   return SDValue();
5110 }
5111
5112 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5113 /// to generate a splat value for the following cases:
5114 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5115 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5116 /// a scalar load, or a constant.
5117 /// The VBROADCAST node is returned when a pattern is found,
5118 /// or SDValue() otherwise.
5119 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5120                                     SelectionDAG &DAG) {
5121   // VBROADCAST requires AVX.
5122   // TODO: Splats could be generated for non-AVX CPUs using SSE
5123   // instructions, but there's less potential gain for only 128-bit vectors.
5124   if (!Subtarget->hasAVX())
5125     return SDValue();
5126
5127   MVT VT = Op.getSimpleValueType();
5128   SDLoc dl(Op);
5129
5130   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5131          "Unsupported vector type for broadcast.");
5132
5133   SDValue Ld;
5134   bool ConstSplatVal;
5135
5136   switch (Op.getOpcode()) {
5137     default:
5138       // Unknown pattern found.
5139       return SDValue();
5140
5141     case ISD::BUILD_VECTOR: {
5142       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5143       BitVector UndefElements;
5144       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5145
5146       // We need a splat of a single value to use broadcast, and it doesn't
5147       // make any sense if the value is only in one element of the vector.
5148       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5149         return SDValue();
5150
5151       Ld = Splat;
5152       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5153                        Ld.getOpcode() == ISD::ConstantFP);
5154
5155       // Make sure that all of the users of a non-constant load are from the
5156       // BUILD_VECTOR node.
5157       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5158         return SDValue();
5159       break;
5160     }
5161
5162     case ISD::VECTOR_SHUFFLE: {
5163       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5164
5165       // Shuffles must have a splat mask where the first element is
5166       // broadcasted.
5167       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5168         return SDValue();
5169
5170       SDValue Sc = Op.getOperand(0);
5171       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5172           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5173
5174         if (!Subtarget->hasInt256())
5175           return SDValue();
5176
5177         // Use the register form of the broadcast instruction available on AVX2.
5178         if (VT.getSizeInBits() >= 256)
5179           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5180         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5181       }
5182
5183       Ld = Sc.getOperand(0);
5184       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5185                        Ld.getOpcode() == ISD::ConstantFP);
5186
5187       // The scalar_to_vector node and the suspected
5188       // load node must have exactly one user.
5189       // Constants may have multiple users.
5190
5191       // AVX-512 has register version of the broadcast
5192       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5193         Ld.getValueType().getSizeInBits() >= 32;
5194       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5195           !hasRegVer))
5196         return SDValue();
5197       break;
5198     }
5199   }
5200
5201   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5202   bool IsGE256 = (VT.getSizeInBits() >= 256);
5203
5204   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5205   // instruction to save 8 or more bytes of constant pool data.
5206   // TODO: If multiple splats are generated to load the same constant,
5207   // it may be detrimental to overall size. There needs to be a way to detect
5208   // that condition to know if this is truly a size win.
5209   const Function *F = DAG.getMachineFunction().getFunction();
5210   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5211
5212   // Handle broadcasting a single constant scalar from the constant pool
5213   // into a vector.
5214   // On Sandybridge (no AVX2), it is still better to load a constant vector
5215   // from the constant pool and not to broadcast it from a scalar.
5216   // But override that restriction when optimizing for size.
5217   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5218   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5219     EVT CVT = Ld.getValueType();
5220     assert(!CVT.isVector() && "Must not broadcast a vector type");
5221
5222     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5223     // For size optimization, also splat v2f64 and v2i64, and for size opt
5224     // with AVX2, also splat i8 and i16.
5225     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5226     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5227         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5228       const Constant *C = nullptr;
5229       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5230         C = CI->getConstantIntValue();
5231       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5232         C = CF->getConstantFPValue();
5233
5234       assert(C && "Invalid constant type");
5235
5236       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5237       SDValue CP =
5238           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5239       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5240       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5241                        MachinePointerInfo::getConstantPool(),
5242                        false, false, false, Alignment);
5243
5244       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5245     }
5246   }
5247
5248   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5249
5250   // Handle AVX2 in-register broadcasts.
5251   if (!IsLoad && Subtarget->hasInt256() &&
5252       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5253     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5254
5255   // The scalar source must be a normal load.
5256   if (!IsLoad)
5257     return SDValue();
5258
5259   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5260       (Subtarget->hasVLX() && ScalarSize == 64))
5261     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5262
5263   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5264   // double since there is no vbroadcastsd xmm
5265   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5266     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5267       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5268   }
5269
5270   // Unsupported broadcast.
5271   return SDValue();
5272 }
5273
5274 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5275 /// underlying vector and index.
5276 ///
5277 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5278 /// index.
5279 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5280                                          SDValue ExtIdx) {
5281   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5282   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5283     return Idx;
5284
5285   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5286   // lowered this:
5287   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5288   // to:
5289   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5290   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5291   //                           undef)
5292   //                       Constant<0>)
5293   // In this case the vector is the extract_subvector expression and the index
5294   // is 2, as specified by the shuffle.
5295   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5296   SDValue ShuffleVec = SVOp->getOperand(0);
5297   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5298   assert(ShuffleVecVT.getVectorElementType() ==
5299          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5300
5301   int ShuffleIdx = SVOp->getMaskElt(Idx);
5302   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5303     ExtractedFromVec = ShuffleVec;
5304     return ShuffleIdx;
5305   }
5306   return Idx;
5307 }
5308
5309 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5310   MVT VT = Op.getSimpleValueType();
5311
5312   // Skip if insert_vec_elt is not supported.
5313   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5314   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5315     return SDValue();
5316
5317   SDLoc DL(Op);
5318   unsigned NumElems = Op.getNumOperands();
5319
5320   SDValue VecIn1;
5321   SDValue VecIn2;
5322   SmallVector<unsigned, 4> InsertIndices;
5323   SmallVector<int, 8> Mask(NumElems, -1);
5324
5325   for (unsigned i = 0; i != NumElems; ++i) {
5326     unsigned Opc = Op.getOperand(i).getOpcode();
5327
5328     if (Opc == ISD::UNDEF)
5329       continue;
5330
5331     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5332       // Quit if more than 1 elements need inserting.
5333       if (InsertIndices.size() > 1)
5334         return SDValue();
5335
5336       InsertIndices.push_back(i);
5337       continue;
5338     }
5339
5340     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5341     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5342     // Quit if non-constant index.
5343     if (!isa<ConstantSDNode>(ExtIdx))
5344       return SDValue();
5345     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5346
5347     // Quit if extracted from vector of different type.
5348     if (ExtractedFromVec.getValueType() != VT)
5349       return SDValue();
5350
5351     if (!VecIn1.getNode())
5352       VecIn1 = ExtractedFromVec;
5353     else if (VecIn1 != ExtractedFromVec) {
5354       if (!VecIn2.getNode())
5355         VecIn2 = ExtractedFromVec;
5356       else if (VecIn2 != ExtractedFromVec)
5357         // Quit if more than 2 vectors to shuffle
5358         return SDValue();
5359     }
5360
5361     if (ExtractedFromVec == VecIn1)
5362       Mask[i] = Idx;
5363     else if (ExtractedFromVec == VecIn2)
5364       Mask[i] = Idx + NumElems;
5365   }
5366
5367   if (!VecIn1.getNode())
5368     return SDValue();
5369
5370   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5371   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5372   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5373     unsigned Idx = InsertIndices[i];
5374     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5375                      DAG.getIntPtrConstant(Idx, DL));
5376   }
5377
5378   return NV;
5379 }
5380
5381 static SDValue ConvertI1VectorToInteger(SDValue Op, SelectionDAG &DAG) {
5382   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5383          Op.getScalarValueSizeInBits() == 1 &&
5384          "Can not convert non-constant vector");
5385   uint64_t Immediate = 0;
5386   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5387     SDValue In = Op.getOperand(idx);
5388     if (In.getOpcode() != ISD::UNDEF)
5389       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5390   }
5391   SDLoc dl(Op);
5392   MVT VT =
5393    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5394   return DAG.getConstant(Immediate, dl, VT);
5395 }
5396 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5397 SDValue
5398 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5399
5400   MVT VT = Op.getSimpleValueType();
5401   assert((VT.getVectorElementType() == MVT::i1) &&
5402          "Unexpected type in LowerBUILD_VECTORvXi1!");
5403
5404   SDLoc dl(Op);
5405   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5406     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5407     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5408     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5409   }
5410
5411   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5412     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5413     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5414     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5415   }
5416
5417   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5418     SDValue Imm = ConvertI1VectorToInteger(Op, DAG);
5419     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5420       return DAG.getBitcast(VT, Imm);
5421     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5422     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5423                         DAG.getIntPtrConstant(0, dl));
5424   }
5425
5426   // Vector has one or more non-const elements
5427   uint64_t Immediate = 0;
5428   SmallVector<unsigned, 16> NonConstIdx;
5429   bool IsSplat = true;
5430   bool HasConstElts = false;
5431   int SplatIdx = -1;
5432   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5433     SDValue In = Op.getOperand(idx);
5434     if (In.getOpcode() == ISD::UNDEF)
5435       continue;
5436     if (!isa<ConstantSDNode>(In))
5437       NonConstIdx.push_back(idx);
5438     else {
5439       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5440       HasConstElts = true;
5441     }
5442     if (SplatIdx == -1)
5443       SplatIdx = idx;
5444     else if (In != Op.getOperand(SplatIdx))
5445       IsSplat = false;
5446   }
5447
5448   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5449   if (IsSplat)
5450     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5451                        DAG.getConstant(1, dl, VT),
5452                        DAG.getConstant(0, dl, VT));
5453
5454   // insert elements one by one
5455   SDValue DstVec;
5456   SDValue Imm;
5457   if (Immediate) {
5458     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5459     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5460   }
5461   else if (HasConstElts)
5462     Imm = DAG.getConstant(0, dl, VT);
5463   else
5464     Imm = DAG.getUNDEF(VT);
5465   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5466     DstVec = DAG.getBitcast(VT, Imm);
5467   else {
5468     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5469     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5470                          DAG.getIntPtrConstant(0, dl));
5471   }
5472
5473   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5474     unsigned InsertIdx = NonConstIdx[i];
5475     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5476                          Op.getOperand(InsertIdx),
5477                          DAG.getIntPtrConstant(InsertIdx, dl));
5478   }
5479   return DstVec;
5480 }
5481
5482 /// \brief Return true if \p N implements a horizontal binop and return the
5483 /// operands for the horizontal binop into V0 and V1.
5484 ///
5485 /// This is a helper function of LowerToHorizontalOp().
5486 /// This function checks that the build_vector \p N in input implements a
5487 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5488 /// operation to match.
5489 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5490 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5491 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5492 /// arithmetic sub.
5493 ///
5494 /// This function only analyzes elements of \p N whose indices are
5495 /// in range [BaseIdx, LastIdx).
5496 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5497                               SelectionDAG &DAG,
5498                               unsigned BaseIdx, unsigned LastIdx,
5499                               SDValue &V0, SDValue &V1) {
5500   EVT VT = N->getValueType(0);
5501
5502   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5503   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5504          "Invalid Vector in input!");
5505
5506   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5507   bool CanFold = true;
5508   unsigned ExpectedVExtractIdx = BaseIdx;
5509   unsigned NumElts = LastIdx - BaseIdx;
5510   V0 = DAG.getUNDEF(VT);
5511   V1 = DAG.getUNDEF(VT);
5512
5513   // Check if N implements a horizontal binop.
5514   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5515     SDValue Op = N->getOperand(i + BaseIdx);
5516
5517     // Skip UNDEFs.
5518     if (Op->getOpcode() == ISD::UNDEF) {
5519       // Update the expected vector extract index.
5520       if (i * 2 == NumElts)
5521         ExpectedVExtractIdx = BaseIdx;
5522       ExpectedVExtractIdx += 2;
5523       continue;
5524     }
5525
5526     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5527
5528     if (!CanFold)
5529       break;
5530
5531     SDValue Op0 = Op.getOperand(0);
5532     SDValue Op1 = Op.getOperand(1);
5533
5534     // Try to match the following pattern:
5535     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5536     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5537         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5538         Op0.getOperand(0) == Op1.getOperand(0) &&
5539         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5540         isa<ConstantSDNode>(Op1.getOperand(1)));
5541     if (!CanFold)
5542       break;
5543
5544     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5545     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5546
5547     if (i * 2 < NumElts) {
5548       if (V0.getOpcode() == ISD::UNDEF) {
5549         V0 = Op0.getOperand(0);
5550         if (V0.getValueType() != VT)
5551           return false;
5552       }
5553     } else {
5554       if (V1.getOpcode() == ISD::UNDEF) {
5555         V1 = Op0.getOperand(0);
5556         if (V1.getValueType() != VT)
5557           return false;
5558       }
5559       if (i * 2 == NumElts)
5560         ExpectedVExtractIdx = BaseIdx;
5561     }
5562
5563     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5564     if (I0 == ExpectedVExtractIdx)
5565       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5566     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5567       // Try to match the following dag sequence:
5568       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5569       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5570     } else
5571       CanFold = false;
5572
5573     ExpectedVExtractIdx += 2;
5574   }
5575
5576   return CanFold;
5577 }
5578
5579 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5580 /// a concat_vector.
5581 ///
5582 /// This is a helper function of LowerToHorizontalOp().
5583 /// This function expects two 256-bit vectors called V0 and V1.
5584 /// At first, each vector is split into two separate 128-bit vectors.
5585 /// Then, the resulting 128-bit vectors are used to implement two
5586 /// horizontal binary operations.
5587 ///
5588 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5589 ///
5590 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5591 /// the two new horizontal binop.
5592 /// When Mode is set, the first horizontal binop dag node would take as input
5593 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5594 /// horizontal binop dag node would take as input the lower 128-bit of V1
5595 /// and the upper 128-bit of V1.
5596 ///   Example:
5597 ///     HADD V0_LO, V0_HI
5598 ///     HADD V1_LO, V1_HI
5599 ///
5600 /// Otherwise, the first horizontal binop dag node takes as input the lower
5601 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5602 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5603 ///   Example:
5604 ///     HADD V0_LO, V1_LO
5605 ///     HADD V0_HI, V1_HI
5606 ///
5607 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5608 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5609 /// the upper 128-bits of the result.
5610 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5611                                      SDLoc DL, SelectionDAG &DAG,
5612                                      unsigned X86Opcode, bool Mode,
5613                                      bool isUndefLO, bool isUndefHI) {
5614   EVT VT = V0.getValueType();
5615   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5616          "Invalid nodes in input!");
5617
5618   unsigned NumElts = VT.getVectorNumElements();
5619   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5620   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5621   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5622   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5623   EVT NewVT = V0_LO.getValueType();
5624
5625   SDValue LO = DAG.getUNDEF(NewVT);
5626   SDValue HI = DAG.getUNDEF(NewVT);
5627
5628   if (Mode) {
5629     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5630     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5631       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5632     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5633       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5634   } else {
5635     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5636     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5637                        V1_LO->getOpcode() != ISD::UNDEF))
5638       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5639
5640     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5641                        V1_HI->getOpcode() != ISD::UNDEF))
5642       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5643   }
5644
5645   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5646 }
5647
5648 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5649 /// node.
5650 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5651                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5652   EVT VT = BV->getValueType(0);
5653   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5654       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5655     return SDValue();
5656
5657   SDLoc DL(BV);
5658   unsigned NumElts = VT.getVectorNumElements();
5659   SDValue InVec0 = DAG.getUNDEF(VT);
5660   SDValue InVec1 = DAG.getUNDEF(VT);
5661
5662   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5663           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5664
5665   // Odd-numbered elements in the input build vector are obtained from
5666   // adding two integer/float elements.
5667   // Even-numbered elements in the input build vector are obtained from
5668   // subtracting two integer/float elements.
5669   unsigned ExpectedOpcode = ISD::FSUB;
5670   unsigned NextExpectedOpcode = ISD::FADD;
5671   bool AddFound = false;
5672   bool SubFound = false;
5673
5674   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5675     SDValue Op = BV->getOperand(i);
5676
5677     // Skip 'undef' values.
5678     unsigned Opcode = Op.getOpcode();
5679     if (Opcode == ISD::UNDEF) {
5680       std::swap(ExpectedOpcode, NextExpectedOpcode);
5681       continue;
5682     }
5683
5684     // Early exit if we found an unexpected opcode.
5685     if (Opcode != ExpectedOpcode)
5686       return SDValue();
5687
5688     SDValue Op0 = Op.getOperand(0);
5689     SDValue Op1 = Op.getOperand(1);
5690
5691     // Try to match the following pattern:
5692     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5693     // Early exit if we cannot match that sequence.
5694     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5695         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5696         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5697         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5698         Op0.getOperand(1) != Op1.getOperand(1))
5699       return SDValue();
5700
5701     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5702     if (I0 != i)
5703       return SDValue();
5704
5705     // We found a valid add/sub node. Update the information accordingly.
5706     if (i & 1)
5707       AddFound = true;
5708     else
5709       SubFound = true;
5710
5711     // Update InVec0 and InVec1.
5712     if (InVec0.getOpcode() == ISD::UNDEF) {
5713       InVec0 = Op0.getOperand(0);
5714       if (InVec0.getValueType() != VT)
5715         return SDValue();
5716     }
5717     if (InVec1.getOpcode() == ISD::UNDEF) {
5718       InVec1 = Op1.getOperand(0);
5719       if (InVec1.getValueType() != VT)
5720         return SDValue();
5721     }
5722
5723     // Make sure that operands in input to each add/sub node always
5724     // come from a same pair of vectors.
5725     if (InVec0 != Op0.getOperand(0)) {
5726       if (ExpectedOpcode == ISD::FSUB)
5727         return SDValue();
5728
5729       // FADD is commutable. Try to commute the operands
5730       // and then test again.
5731       std::swap(Op0, Op1);
5732       if (InVec0 != Op0.getOperand(0))
5733         return SDValue();
5734     }
5735
5736     if (InVec1 != Op1.getOperand(0))
5737       return SDValue();
5738
5739     // Update the pair of expected opcodes.
5740     std::swap(ExpectedOpcode, NextExpectedOpcode);
5741   }
5742
5743   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5744   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5745       InVec1.getOpcode() != ISD::UNDEF)
5746     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5747
5748   return SDValue();
5749 }
5750
5751 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5752 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5753                                    const X86Subtarget *Subtarget,
5754                                    SelectionDAG &DAG) {
5755   EVT VT = BV->getValueType(0);
5756   unsigned NumElts = VT.getVectorNumElements();
5757   unsigned NumUndefsLO = 0;
5758   unsigned NumUndefsHI = 0;
5759   unsigned Half = NumElts/2;
5760
5761   // Count the number of UNDEF operands in the build_vector in input.
5762   for (unsigned i = 0, e = Half; i != e; ++i)
5763     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5764       NumUndefsLO++;
5765
5766   for (unsigned i = Half, e = NumElts; i != e; ++i)
5767     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5768       NumUndefsHI++;
5769
5770   // Early exit if this is either a build_vector of all UNDEFs or all the
5771   // operands but one are UNDEF.
5772   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5773     return SDValue();
5774
5775   SDLoc DL(BV);
5776   SDValue InVec0, InVec1;
5777   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5778     // Try to match an SSE3 float HADD/HSUB.
5779     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5780       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5781
5782     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5783       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5784   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5785     // Try to match an SSSE3 integer HADD/HSUB.
5786     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5787       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5788
5789     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5790       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5791   }
5792
5793   if (!Subtarget->hasAVX())
5794     return SDValue();
5795
5796   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5797     // Try to match an AVX horizontal add/sub of packed single/double
5798     // precision floating point values from 256-bit vectors.
5799     SDValue InVec2, InVec3;
5800     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5801         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5802         ((InVec0.getOpcode() == ISD::UNDEF ||
5803           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5804         ((InVec1.getOpcode() == ISD::UNDEF ||
5805           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5806       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5807
5808     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5809         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5810         ((InVec0.getOpcode() == ISD::UNDEF ||
5811           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5812         ((InVec1.getOpcode() == ISD::UNDEF ||
5813           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5814       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5815   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5816     // Try to match an AVX2 horizontal add/sub of signed integers.
5817     SDValue InVec2, InVec3;
5818     unsigned X86Opcode;
5819     bool CanFold = true;
5820
5821     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5822         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5823         ((InVec0.getOpcode() == ISD::UNDEF ||
5824           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5825         ((InVec1.getOpcode() == ISD::UNDEF ||
5826           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5827       X86Opcode = X86ISD::HADD;
5828     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5829         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5830         ((InVec0.getOpcode() == ISD::UNDEF ||
5831           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5832         ((InVec1.getOpcode() == ISD::UNDEF ||
5833           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5834       X86Opcode = X86ISD::HSUB;
5835     else
5836       CanFold = false;
5837
5838     if (CanFold) {
5839       // Fold this build_vector into a single horizontal add/sub.
5840       // Do this only if the target has AVX2.
5841       if (Subtarget->hasAVX2())
5842         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5843
5844       // Do not try to expand this build_vector into a pair of horizontal
5845       // add/sub if we can emit a pair of scalar add/sub.
5846       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5847         return SDValue();
5848
5849       // Convert this build_vector into a pair of horizontal binop followed by
5850       // a concat vector.
5851       bool isUndefLO = NumUndefsLO == Half;
5852       bool isUndefHI = NumUndefsHI == Half;
5853       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5854                                    isUndefLO, isUndefHI);
5855     }
5856   }
5857
5858   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5859        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5860     unsigned X86Opcode;
5861     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5862       X86Opcode = X86ISD::HADD;
5863     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5864       X86Opcode = X86ISD::HSUB;
5865     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5866       X86Opcode = X86ISD::FHADD;
5867     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5868       X86Opcode = X86ISD::FHSUB;
5869     else
5870       return SDValue();
5871
5872     // Don't try to expand this build_vector into a pair of horizontal add/sub
5873     // if we can simply emit a pair of scalar add/sub.
5874     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5875       return SDValue();
5876
5877     // Convert this build_vector into two horizontal add/sub followed by
5878     // a concat vector.
5879     bool isUndefLO = NumUndefsLO == Half;
5880     bool isUndefHI = NumUndefsHI == Half;
5881     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5882                                  isUndefLO, isUndefHI);
5883   }
5884
5885   return SDValue();
5886 }
5887
5888 SDValue
5889 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5890   SDLoc dl(Op);
5891
5892   MVT VT = Op.getSimpleValueType();
5893   MVT ExtVT = VT.getVectorElementType();
5894   unsigned NumElems = Op.getNumOperands();
5895
5896   // Generate vectors for predicate vectors.
5897   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5898     return LowerBUILD_VECTORvXi1(Op, DAG);
5899
5900   // Vectors containing all zeros can be matched by pxor and xorps later
5901   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5902     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5903     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5904     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5905       return Op;
5906
5907     return getZeroVector(VT, Subtarget, DAG, dl);
5908   }
5909
5910   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5911   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5912   // vpcmpeqd on 256-bit vectors.
5913   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5914     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5915       return Op;
5916
5917     if (!VT.is512BitVector())
5918       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5919   }
5920
5921   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5922   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5923     return AddSub;
5924   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5925     return HorizontalOp;
5926   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5927     return Broadcast;
5928
5929   unsigned EVTBits = ExtVT.getSizeInBits();
5930
5931   unsigned NumZero  = 0;
5932   unsigned NumNonZero = 0;
5933   unsigned NonZeros = 0;
5934   bool IsAllConstants = true;
5935   SmallSet<SDValue, 8> Values;
5936   for (unsigned i = 0; i < NumElems; ++i) {
5937     SDValue Elt = Op.getOperand(i);
5938     if (Elt.getOpcode() == ISD::UNDEF)
5939       continue;
5940     Values.insert(Elt);
5941     if (Elt.getOpcode() != ISD::Constant &&
5942         Elt.getOpcode() != ISD::ConstantFP)
5943       IsAllConstants = false;
5944     if (X86::isZeroNode(Elt))
5945       NumZero++;
5946     else {
5947       NonZeros |= (1 << i);
5948       NumNonZero++;
5949     }
5950   }
5951
5952   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5953   if (NumNonZero == 0)
5954     return DAG.getUNDEF(VT);
5955
5956   // Special case for single non-zero, non-undef, element.
5957   if (NumNonZero == 1) {
5958     unsigned Idx = countTrailingZeros(NonZeros);
5959     SDValue Item = Op.getOperand(Idx);
5960
5961     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5962     // the value are obviously zero, truncate the value to i32 and do the
5963     // insertion that way.  Only do this if the value is non-constant or if the
5964     // value is a constant being inserted into element 0.  It is cheaper to do
5965     // a constant pool load than it is to do a movd + shuffle.
5966     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5967         (!IsAllConstants || Idx == 0)) {
5968       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5969         // Handle SSE only.
5970         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5971         EVT VecVT = MVT::v4i32;
5972
5973         // Truncate the value (which may itself be a constant) to i32, and
5974         // convert it to a vector with movd (S2V+shuffle to zero extend).
5975         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5976         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5977         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5978                                       Item, Idx * 2, true, Subtarget, DAG));
5979       }
5980     }
5981
5982     // If we have a constant or non-constant insertion into the low element of
5983     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5984     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5985     // depending on what the source datatype is.
5986     if (Idx == 0) {
5987       if (NumZero == 0)
5988         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5989
5990       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5991           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5992         if (VT.is512BitVector()) {
5993           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5994           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5995                              Item, DAG.getIntPtrConstant(0, dl));
5996         }
5997         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5998                "Expected an SSE value type!");
5999         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
6001         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6002       }
6003
6004       // We can't directly insert an i8 or i16 into a vector, so zero extend
6005       // it to i32 first.
6006       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
6007         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
6008         if (VT.is256BitVector()) {
6009           if (Subtarget->hasAVX()) {
6010             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
6011             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6012           } else {
6013             // Without AVX, we need to extend to a 128-bit vector and then
6014             // insert into the 256-bit vector.
6015             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6016             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
6017             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
6018           }
6019         } else {
6020           assert(VT.is128BitVector() && "Expected an SSE value type!");
6021           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
6022           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
6023         }
6024         return DAG.getBitcast(VT, Item);
6025       }
6026     }
6027
6028     // Is it a vector logical left shift?
6029     if (NumElems == 2 && Idx == 1 &&
6030         X86::isZeroNode(Op.getOperand(0)) &&
6031         !X86::isZeroNode(Op.getOperand(1))) {
6032       unsigned NumBits = VT.getSizeInBits();
6033       return getVShift(true, VT,
6034                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6035                                    VT, Op.getOperand(1)),
6036                        NumBits/2, DAG, *this, dl);
6037     }
6038
6039     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6040       return SDValue();
6041
6042     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6043     // is a non-constant being inserted into an element other than the low one,
6044     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6045     // movd/movss) to move this into the low element, then shuffle it into
6046     // place.
6047     if (EVTBits == 32) {
6048       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6049       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6050     }
6051   }
6052
6053   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6054   if (Values.size() == 1) {
6055     if (EVTBits == 32) {
6056       // Instead of a shuffle like this:
6057       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6058       // Check if it's possible to issue this instead.
6059       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6060       unsigned Idx = countTrailingZeros(NonZeros);
6061       SDValue Item = Op.getOperand(Idx);
6062       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6063         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6064     }
6065     return SDValue();
6066   }
6067
6068   // A vector full of immediates; various special cases are already
6069   // handled, so this is best done with a single constant-pool load.
6070   if (IsAllConstants)
6071     return SDValue();
6072
6073   // For AVX-length vectors, see if we can use a vector load to get all of the
6074   // elements, otherwise build the individual 128-bit pieces and use
6075   // shuffles to put them in place.
6076   if (VT.is256BitVector() || VT.is512BitVector()) {
6077     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6078
6079     // Check for a build vector of consecutive loads.
6080     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6081       return LD;
6082
6083     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6084
6085     // Build both the lower and upper subvector.
6086     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6087                                 makeArrayRef(&V[0], NumElems/2));
6088     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6089                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6090
6091     // Recreate the wider vector with the lower and upper part.
6092     if (VT.is256BitVector())
6093       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6094     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6095   }
6096
6097   // Let legalizer expand 2-wide build_vectors.
6098   if (EVTBits == 64) {
6099     if (NumNonZero == 1) {
6100       // One half is zero or undef.
6101       unsigned Idx = countTrailingZeros(NonZeros);
6102       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6103                                  Op.getOperand(Idx));
6104       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6105     }
6106     return SDValue();
6107   }
6108
6109   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6110   if (EVTBits == 8 && NumElems == 16)
6111     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6112                                         Subtarget, *this))
6113       return V;
6114
6115   if (EVTBits == 16 && NumElems == 8)
6116     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6117                                       Subtarget, *this))
6118       return V;
6119
6120   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6121   if (EVTBits == 32 && NumElems == 4)
6122     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6123       return V;
6124
6125   // If element VT is == 32 bits, turn it into a number of shuffles.
6126   SmallVector<SDValue, 8> V(NumElems);
6127   if (NumElems == 4 && NumZero > 0) {
6128     for (unsigned i = 0; i < 4; ++i) {
6129       bool isZero = !(NonZeros & (1 << i));
6130       if (isZero)
6131         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6132       else
6133         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6134     }
6135
6136     for (unsigned i = 0; i < 2; ++i) {
6137       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6138         default: break;
6139         case 0:
6140           V[i] = V[i*2];  // Must be a zero vector.
6141           break;
6142         case 1:
6143           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6144           break;
6145         case 2:
6146           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6147           break;
6148         case 3:
6149           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6150           break;
6151       }
6152     }
6153
6154     bool Reverse1 = (NonZeros & 0x3) == 2;
6155     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6156     int MaskVec[] = {
6157       Reverse1 ? 1 : 0,
6158       Reverse1 ? 0 : 1,
6159       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6160       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6161     };
6162     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6163   }
6164
6165   if (Values.size() > 1 && VT.is128BitVector()) {
6166     // Check for a build vector of consecutive loads.
6167     for (unsigned i = 0; i < NumElems; ++i)
6168       V[i] = Op.getOperand(i);
6169
6170     // Check for elements which are consecutive loads.
6171     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6172       return LD;
6173
6174     // Check for a build vector from mostly shuffle plus few inserting.
6175     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6176       return Sh;
6177
6178     // For SSE 4.1, use insertps to put the high elements into the low element.
6179     if (Subtarget->hasSSE41()) {
6180       SDValue Result;
6181       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6182         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6183       else
6184         Result = DAG.getUNDEF(VT);
6185
6186       for (unsigned i = 1; i < NumElems; ++i) {
6187         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6188         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6189                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6190       }
6191       return Result;
6192     }
6193
6194     // Otherwise, expand into a number of unpckl*, start by extending each of
6195     // our (non-undef) elements to the full vector width with the element in the
6196     // bottom slot of the vector (which generates no code for SSE).
6197     for (unsigned i = 0; i < NumElems; ++i) {
6198       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6199         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6200       else
6201         V[i] = DAG.getUNDEF(VT);
6202     }
6203
6204     // Next, we iteratively mix elements, e.g. for v4f32:
6205     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6206     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6207     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6208     unsigned EltStride = NumElems >> 1;
6209     while (EltStride != 0) {
6210       for (unsigned i = 0; i < EltStride; ++i) {
6211         // If V[i+EltStride] is undef and this is the first round of mixing,
6212         // then it is safe to just drop this shuffle: V[i] is already in the
6213         // right place, the one element (since it's the first round) being
6214         // inserted as undef can be dropped.  This isn't safe for successive
6215         // rounds because they will permute elements within both vectors.
6216         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6217             EltStride == NumElems/2)
6218           continue;
6219
6220         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6221       }
6222       EltStride >>= 1;
6223     }
6224     return V[0];
6225   }
6226   return SDValue();
6227 }
6228
6229 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6230 // to create 256-bit vectors from two other 128-bit ones.
6231 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6232   SDLoc dl(Op);
6233   MVT ResVT = Op.getSimpleValueType();
6234
6235   assert((ResVT.is256BitVector() ||
6236           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6237
6238   SDValue V1 = Op.getOperand(0);
6239   SDValue V2 = Op.getOperand(1);
6240   unsigned NumElems = ResVT.getVectorNumElements();
6241   if (ResVT.is256BitVector())
6242     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6243
6244   if (Op.getNumOperands() == 4) {
6245     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6246                                 ResVT.getVectorNumElements()/2);
6247     SDValue V3 = Op.getOperand(2);
6248     SDValue V4 = Op.getOperand(3);
6249     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6250       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6251   }
6252   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6253 }
6254
6255 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6256                                        const X86Subtarget *Subtarget,
6257                                        SelectionDAG & DAG) {
6258   SDLoc dl(Op);
6259   MVT ResVT = Op.getSimpleValueType();
6260   unsigned NumOfOperands = Op.getNumOperands();
6261
6262   assert(isPowerOf2_32(NumOfOperands) &&
6263          "Unexpected number of operands in CONCAT_VECTORS");
6264
6265   if (NumOfOperands > 2) {
6266     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6267                                   ResVT.getVectorNumElements()/2);
6268     SmallVector<SDValue, 2> Ops;
6269     for (unsigned i = 0; i < NumOfOperands/2; i++)
6270       Ops.push_back(Op.getOperand(i));
6271     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6272     Ops.clear();
6273     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6274       Ops.push_back(Op.getOperand(i));
6275     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6276     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6277   }
6278
6279   SDValue V1 = Op.getOperand(0);
6280   SDValue V2 = Op.getOperand(1);
6281   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6282   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6283
6284   if (IsZeroV1 && IsZeroV2)
6285     return getZeroVector(ResVT, Subtarget, DAG, dl);
6286
6287   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6288   SDValue Undef = DAG.getUNDEF(ResVT);
6289   unsigned NumElems = ResVT.getVectorNumElements();
6290   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6291
6292   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6293   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6294   if (IsZeroV1)
6295     return V2;
6296
6297   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6298   // Zero the upper bits of V1
6299   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6300   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6301   if (IsZeroV2)
6302     return V1;
6303   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6304 }
6305
6306 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6307                                    const X86Subtarget *Subtarget,
6308                                    SelectionDAG &DAG) {
6309   MVT VT = Op.getSimpleValueType();
6310   if (VT.getVectorElementType() == MVT::i1)
6311     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6312
6313   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6314          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6315           Op.getNumOperands() == 4)));
6316
6317   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6318   // from two other 128-bit ones.
6319
6320   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6321   return LowerAVXCONCAT_VECTORS(Op, DAG);
6322 }
6323
6324
6325 //===----------------------------------------------------------------------===//
6326 // Vector shuffle lowering
6327 //
6328 // This is an experimental code path for lowering vector shuffles on x86. It is
6329 // designed to handle arbitrary vector shuffles and blends, gracefully
6330 // degrading performance as necessary. It works hard to recognize idiomatic
6331 // shuffles and lower them to optimal instruction patterns without leaving
6332 // a framework that allows reasonably efficient handling of all vector shuffle
6333 // patterns.
6334 //===----------------------------------------------------------------------===//
6335
6336 /// \brief Tiny helper function to identify a no-op mask.
6337 ///
6338 /// This is a somewhat boring predicate function. It checks whether the mask
6339 /// array input, which is assumed to be a single-input shuffle mask of the kind
6340 /// used by the X86 shuffle instructions (not a fully general
6341 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6342 /// in-place shuffle are 'no-op's.
6343 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6344   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6345     if (Mask[i] != -1 && Mask[i] != i)
6346       return false;
6347   return true;
6348 }
6349
6350 /// \brief Helper function to classify a mask as a single-input mask.
6351 ///
6352 /// This isn't a generic single-input test because in the vector shuffle
6353 /// lowering we canonicalize single inputs to be the first input operand. This
6354 /// means we can more quickly test for a single input by only checking whether
6355 /// an input from the second operand exists. We also assume that the size of
6356 /// mask corresponds to the size of the input vectors which isn't true in the
6357 /// fully general case.
6358 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6359   for (int M : Mask)
6360     if (M >= (int)Mask.size())
6361       return false;
6362   return true;
6363 }
6364
6365 /// \brief Test whether there are elements crossing 128-bit lanes in this
6366 /// shuffle mask.
6367 ///
6368 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6369 /// and we routinely test for these.
6370 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6371   int LaneSize = 128 / VT.getScalarSizeInBits();
6372   int Size = Mask.size();
6373   for (int i = 0; i < Size; ++i)
6374     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6375       return true;
6376   return false;
6377 }
6378
6379 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6380 ///
6381 /// This checks a shuffle mask to see if it is performing the same
6382 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6383 /// that it is also not lane-crossing. It may however involve a blend from the
6384 /// same lane of a second vector.
6385 ///
6386 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6387 /// non-trivial to compute in the face of undef lanes. The representation is
6388 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6389 /// entries from both V1 and V2 inputs to the wider mask.
6390 static bool
6391 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6392                                 SmallVectorImpl<int> &RepeatedMask) {
6393   int LaneSize = 128 / VT.getScalarSizeInBits();
6394   RepeatedMask.resize(LaneSize, -1);
6395   int Size = Mask.size();
6396   for (int i = 0; i < Size; ++i) {
6397     if (Mask[i] < 0)
6398       continue;
6399     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6400       // This entry crosses lanes, so there is no way to model this shuffle.
6401       return false;
6402
6403     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6404     if (RepeatedMask[i % LaneSize] == -1)
6405       // This is the first non-undef entry in this slot of a 128-bit lane.
6406       RepeatedMask[i % LaneSize] =
6407           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6408     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6409       // Found a mismatch with the repeated mask.
6410       return false;
6411   }
6412   return true;
6413 }
6414
6415 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6416 /// arguments.
6417 ///
6418 /// This is a fast way to test a shuffle mask against a fixed pattern:
6419 ///
6420 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6421 ///
6422 /// It returns true if the mask is exactly as wide as the argument list, and
6423 /// each element of the mask is either -1 (signifying undef) or the value given
6424 /// in the argument.
6425 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6426                                 ArrayRef<int> ExpectedMask) {
6427   if (Mask.size() != ExpectedMask.size())
6428     return false;
6429
6430   int Size = Mask.size();
6431
6432   // If the values are build vectors, we can look through them to find
6433   // equivalent inputs that make the shuffles equivalent.
6434   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6435   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6436
6437   for (int i = 0; i < Size; ++i)
6438     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6439       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6440       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6441       if (!MaskBV || !ExpectedBV ||
6442           MaskBV->getOperand(Mask[i] % Size) !=
6443               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6444         return false;
6445     }
6446
6447   return true;
6448 }
6449
6450 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6451 ///
6452 /// This helper function produces an 8-bit shuffle immediate corresponding to
6453 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6454 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6455 /// example.
6456 ///
6457 /// NB: We rely heavily on "undef" masks preserving the input lane.
6458 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6459                                           SelectionDAG &DAG) {
6460   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6461   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6462   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6463   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6464   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6465
6466   unsigned Imm = 0;
6467   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6468   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6469   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6470   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6471   return DAG.getConstant(Imm, DL, MVT::i8);
6472 }
6473
6474 /// \brief Compute whether each element of a shuffle is zeroable.
6475 ///
6476 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6477 /// Either it is an undef element in the shuffle mask, the element of the input
6478 /// referenced is undef, or the element of the input referenced is known to be
6479 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6480 /// as many lanes with this technique as possible to simplify the remaining
6481 /// shuffle.
6482 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6483                                                      SDValue V1, SDValue V2) {
6484   SmallBitVector Zeroable(Mask.size(), false);
6485
6486   while (V1.getOpcode() == ISD::BITCAST)
6487     V1 = V1->getOperand(0);
6488   while (V2.getOpcode() == ISD::BITCAST)
6489     V2 = V2->getOperand(0);
6490
6491   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6492   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6493
6494   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6495     int M = Mask[i];
6496     // Handle the easy cases.
6497     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6498       Zeroable[i] = true;
6499       continue;
6500     }
6501
6502     // If this is an index into a build_vector node (which has the same number
6503     // of elements), dig out the input value and use it.
6504     SDValue V = M < Size ? V1 : V2;
6505     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6506       continue;
6507
6508     SDValue Input = V.getOperand(M % Size);
6509     // The UNDEF opcode check really should be dead code here, but not quite
6510     // worth asserting on (it isn't invalid, just unexpected).
6511     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6512       Zeroable[i] = true;
6513   }
6514
6515   return Zeroable;
6516 }
6517
6518 /// \brief Try to emit a bitmask instruction for a shuffle.
6519 ///
6520 /// This handles cases where we can model a blend exactly as a bitmask due to
6521 /// one of the inputs being zeroable.
6522 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6523                                            SDValue V2, ArrayRef<int> Mask,
6524                                            SelectionDAG &DAG) {
6525   MVT EltVT = VT.getScalarType();
6526   int NumEltBits = EltVT.getSizeInBits();
6527   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6528   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6529   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6530                                     IntEltVT);
6531   if (EltVT.isFloatingPoint()) {
6532     Zero = DAG.getBitcast(EltVT, Zero);
6533     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6534   }
6535   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6536   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6537   SDValue V;
6538   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6539     if (Zeroable[i])
6540       continue;
6541     if (Mask[i] % Size != i)
6542       return SDValue(); // Not a blend.
6543     if (!V)
6544       V = Mask[i] < Size ? V1 : V2;
6545     else if (V != (Mask[i] < Size ? V1 : V2))
6546       return SDValue(); // Can only let one input through the mask.
6547
6548     VMaskOps[i] = AllOnes;
6549   }
6550   if (!V)
6551     return SDValue(); // No non-zeroable elements!
6552
6553   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6554   V = DAG.getNode(VT.isFloatingPoint()
6555                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6556                   DL, VT, V, VMask);
6557   return V;
6558 }
6559
6560 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6561 ///
6562 /// This is used as a fallback approach when first class blend instructions are
6563 /// unavailable. Currently it is only suitable for integer vectors, but could
6564 /// be generalized for floating point vectors if desirable.
6565 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6566                                             SDValue V2, ArrayRef<int> Mask,
6567                                             SelectionDAG &DAG) {
6568   assert(VT.isInteger() && "Only supports integer vector types!");
6569   MVT EltVT = VT.getScalarType();
6570   int NumEltBits = EltVT.getSizeInBits();
6571   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6572   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6573                                     EltVT);
6574   SmallVector<SDValue, 16> MaskOps;
6575   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6576     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6577       return SDValue(); // Shuffled input!
6578     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6579   }
6580
6581   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6582   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6583   // We have to cast V2 around.
6584   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6585   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6586                                       DAG.getBitcast(MaskVT, V1Mask),
6587                                       DAG.getBitcast(MaskVT, V2)));
6588   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6589 }
6590
6591 /// \brief Try to emit a blend instruction for a shuffle.
6592 ///
6593 /// This doesn't do any checks for the availability of instructions for blending
6594 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6595 /// be matched in the backend with the type given. What it does check for is
6596 /// that the shuffle mask is in fact a blend.
6597 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6598                                          SDValue V2, ArrayRef<int> Mask,
6599                                          const X86Subtarget *Subtarget,
6600                                          SelectionDAG &DAG) {
6601   unsigned BlendMask = 0;
6602   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6603     if (Mask[i] >= Size) {
6604       if (Mask[i] != i + Size)
6605         return SDValue(); // Shuffled V2 input!
6606       BlendMask |= 1u << i;
6607       continue;
6608     }
6609     if (Mask[i] >= 0 && Mask[i] != i)
6610       return SDValue(); // Shuffled V1 input!
6611   }
6612   switch (VT.SimpleTy) {
6613   case MVT::v2f64:
6614   case MVT::v4f32:
6615   case MVT::v4f64:
6616   case MVT::v8f32:
6617     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6618                        DAG.getConstant(BlendMask, DL, MVT::i8));
6619
6620   case MVT::v4i64:
6621   case MVT::v8i32:
6622     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6623     // FALLTHROUGH
6624   case MVT::v2i64:
6625   case MVT::v4i32:
6626     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6627     // that instruction.
6628     if (Subtarget->hasAVX2()) {
6629       // Scale the blend by the number of 32-bit dwords per element.
6630       int Scale =  VT.getScalarSizeInBits() / 32;
6631       BlendMask = 0;
6632       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6633         if (Mask[i] >= Size)
6634           for (int j = 0; j < Scale; ++j)
6635             BlendMask |= 1u << (i * Scale + j);
6636
6637       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6638       V1 = DAG.getBitcast(BlendVT, V1);
6639       V2 = DAG.getBitcast(BlendVT, V2);
6640       return DAG.getBitcast(
6641           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6642                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6643     }
6644     // FALLTHROUGH
6645   case MVT::v8i16: {
6646     // For integer shuffles we need to expand the mask and cast the inputs to
6647     // v8i16s prior to blending.
6648     int Scale = 8 / VT.getVectorNumElements();
6649     BlendMask = 0;
6650     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6651       if (Mask[i] >= Size)
6652         for (int j = 0; j < Scale; ++j)
6653           BlendMask |= 1u << (i * Scale + j);
6654
6655     V1 = DAG.getBitcast(MVT::v8i16, V1);
6656     V2 = DAG.getBitcast(MVT::v8i16, V2);
6657     return DAG.getBitcast(VT,
6658                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6659                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6660   }
6661
6662   case MVT::v16i16: {
6663     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6664     SmallVector<int, 8> RepeatedMask;
6665     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6666       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6667       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6668       BlendMask = 0;
6669       for (int i = 0; i < 8; ++i)
6670         if (RepeatedMask[i] >= 16)
6671           BlendMask |= 1u << i;
6672       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6673                          DAG.getConstant(BlendMask, DL, MVT::i8));
6674     }
6675   }
6676     // FALLTHROUGH
6677   case MVT::v16i8:
6678   case MVT::v32i8: {
6679     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6680            "256-bit byte-blends require AVX2 support!");
6681
6682     // Scale the blend by the number of bytes per element.
6683     int Scale = VT.getScalarSizeInBits() / 8;
6684
6685     // This form of blend is always done on bytes. Compute the byte vector
6686     // type.
6687     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6688
6689     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6690     // mix of LLVM's code generator and the x86 backend. We tell the code
6691     // generator that boolean values in the elements of an x86 vector register
6692     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6693     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6694     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6695     // of the element (the remaining are ignored) and 0 in that high bit would
6696     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6697     // the LLVM model for boolean values in vector elements gets the relevant
6698     // bit set, it is set backwards and over constrained relative to x86's
6699     // actual model.
6700     SmallVector<SDValue, 32> VSELECTMask;
6701     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6702       for (int j = 0; j < Scale; ++j)
6703         VSELECTMask.push_back(
6704             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6705                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6706                                           MVT::i8));
6707
6708     V1 = DAG.getBitcast(BlendVT, V1);
6709     V2 = DAG.getBitcast(BlendVT, V2);
6710     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6711                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6712                                                       BlendVT, VSELECTMask),
6713                                           V1, V2));
6714   }
6715
6716   default:
6717     llvm_unreachable("Not a supported integer vector type!");
6718   }
6719 }
6720
6721 /// \brief Try to lower as a blend of elements from two inputs followed by
6722 /// a single-input permutation.
6723 ///
6724 /// This matches the pattern where we can blend elements from two inputs and
6725 /// then reduce the shuffle to a single-input permutation.
6726 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6727                                                    SDValue V2,
6728                                                    ArrayRef<int> Mask,
6729                                                    SelectionDAG &DAG) {
6730   // We build up the blend mask while checking whether a blend is a viable way
6731   // to reduce the shuffle.
6732   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6733   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6734
6735   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6736     if (Mask[i] < 0)
6737       continue;
6738
6739     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6740
6741     if (BlendMask[Mask[i] % Size] == -1)
6742       BlendMask[Mask[i] % Size] = Mask[i];
6743     else if (BlendMask[Mask[i] % Size] != Mask[i])
6744       return SDValue(); // Can't blend in the needed input!
6745
6746     PermuteMask[i] = Mask[i] % Size;
6747   }
6748
6749   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6750   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6751 }
6752
6753 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6754 /// blends and permutes.
6755 ///
6756 /// This matches the extremely common pattern for handling combined
6757 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6758 /// operations. It will try to pick the best arrangement of shuffles and
6759 /// blends.
6760 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6761                                                           SDValue V1,
6762                                                           SDValue V2,
6763                                                           ArrayRef<int> Mask,
6764                                                           SelectionDAG &DAG) {
6765   // Shuffle the input elements into the desired positions in V1 and V2 and
6766   // blend them together.
6767   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6768   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6769   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6770   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6771     if (Mask[i] >= 0 && Mask[i] < Size) {
6772       V1Mask[i] = Mask[i];
6773       BlendMask[i] = i;
6774     } else if (Mask[i] >= Size) {
6775       V2Mask[i] = Mask[i] - Size;
6776       BlendMask[i] = i + Size;
6777     }
6778
6779   // Try to lower with the simpler initial blend strategy unless one of the
6780   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6781   // shuffle may be able to fold with a load or other benefit. However, when
6782   // we'll have to do 2x as many shuffles in order to achieve this, blending
6783   // first is a better strategy.
6784   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6785     if (SDValue BlendPerm =
6786             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6787       return BlendPerm;
6788
6789   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6790   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6791   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6792 }
6793
6794 /// \brief Try to lower a vector shuffle as a byte rotation.
6795 ///
6796 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6797 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6798 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6799 /// try to generically lower a vector shuffle through such an pattern. It
6800 /// does not check for the profitability of lowering either as PALIGNR or
6801 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6802 /// This matches shuffle vectors that look like:
6803 ///
6804 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6805 ///
6806 /// Essentially it concatenates V1 and V2, shifts right by some number of
6807 /// elements, and takes the low elements as the result. Note that while this is
6808 /// specified as a *right shift* because x86 is little-endian, it is a *left
6809 /// rotate* of the vector lanes.
6810 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6811                                               SDValue V2,
6812                                               ArrayRef<int> Mask,
6813                                               const X86Subtarget *Subtarget,
6814                                               SelectionDAG &DAG) {
6815   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6816
6817   int NumElts = Mask.size();
6818   int NumLanes = VT.getSizeInBits() / 128;
6819   int NumLaneElts = NumElts / NumLanes;
6820
6821   // We need to detect various ways of spelling a rotation:
6822   //   [11, 12, 13, 14, 15,  0,  1,  2]
6823   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6824   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6825   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6826   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6827   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6828   int Rotation = 0;
6829   SDValue Lo, Hi;
6830   for (int l = 0; l < NumElts; l += NumLaneElts) {
6831     for (int i = 0; i < NumLaneElts; ++i) {
6832       if (Mask[l + i] == -1)
6833         continue;
6834       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6835
6836       // Get the mod-Size index and lane correct it.
6837       int LaneIdx = (Mask[l + i] % NumElts) - l;
6838       // Make sure it was in this lane.
6839       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6840         return SDValue();
6841
6842       // Determine where a rotated vector would have started.
6843       int StartIdx = i - LaneIdx;
6844       if (StartIdx == 0)
6845         // The identity rotation isn't interesting, stop.
6846         return SDValue();
6847
6848       // If we found the tail of a vector the rotation must be the missing
6849       // front. If we found the head of a vector, it must be how much of the
6850       // head.
6851       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6852
6853       if (Rotation == 0)
6854         Rotation = CandidateRotation;
6855       else if (Rotation != CandidateRotation)
6856         // The rotations don't match, so we can't match this mask.
6857         return SDValue();
6858
6859       // Compute which value this mask is pointing at.
6860       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6861
6862       // Compute which of the two target values this index should be assigned
6863       // to. This reflects whether the high elements are remaining or the low
6864       // elements are remaining.
6865       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6866
6867       // Either set up this value if we've not encountered it before, or check
6868       // that it remains consistent.
6869       if (!TargetV)
6870         TargetV = MaskV;
6871       else if (TargetV != MaskV)
6872         // This may be a rotation, but it pulls from the inputs in some
6873         // unsupported interleaving.
6874         return SDValue();
6875     }
6876   }
6877
6878   // Check that we successfully analyzed the mask, and normalize the results.
6879   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6880   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6881   if (!Lo)
6882     Lo = Hi;
6883   else if (!Hi)
6884     Hi = Lo;
6885
6886   // The actual rotate instruction rotates bytes, so we need to scale the
6887   // rotation based on how many bytes are in the vector lane.
6888   int Scale = 16 / NumLaneElts;
6889
6890   // SSSE3 targets can use the palignr instruction.
6891   if (Subtarget->hasSSSE3()) {
6892     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6893     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6894     Lo = DAG.getBitcast(AlignVT, Lo);
6895     Hi = DAG.getBitcast(AlignVT, Hi);
6896
6897     return DAG.getBitcast(
6898         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6899                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6900   }
6901
6902   assert(VT.getSizeInBits() == 128 &&
6903          "Rotate-based lowering only supports 128-bit lowering!");
6904   assert(Mask.size() <= 16 &&
6905          "Can shuffle at most 16 bytes in a 128-bit vector!");
6906
6907   // Default SSE2 implementation
6908   int LoByteShift = 16 - Rotation * Scale;
6909   int HiByteShift = Rotation * Scale;
6910
6911   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6912   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6913   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6914
6915   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6916                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6917   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6918                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6919   return DAG.getBitcast(VT,
6920                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6921 }
6922
6923 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6924 ///
6925 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6926 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6927 /// matches elements from one of the input vectors shuffled to the left or
6928 /// right with zeroable elements 'shifted in'. It handles both the strictly
6929 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6930 /// quad word lane.
6931 ///
6932 /// PSHL : (little-endian) left bit shift.
6933 /// [ zz, 0, zz,  2 ]
6934 /// [ -1, 4, zz, -1 ]
6935 /// PSRL : (little-endian) right bit shift.
6936 /// [  1, zz,  3, zz]
6937 /// [ -1, -1,  7, zz]
6938 /// PSLLDQ : (little-endian) left byte shift
6939 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6940 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6941 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6942 /// PSRLDQ : (little-endian) right byte shift
6943 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6944 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6945 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6946 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6947                                          SDValue V2, ArrayRef<int> Mask,
6948                                          SelectionDAG &DAG) {
6949   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6950
6951   int Size = Mask.size();
6952   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6953
6954   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6955     for (int i = 0; i < Size; i += Scale)
6956       for (int j = 0; j < Shift; ++j)
6957         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6958           return false;
6959
6960     return true;
6961   };
6962
6963   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6964     for (int i = 0; i != Size; i += Scale) {
6965       unsigned Pos = Left ? i + Shift : i;
6966       unsigned Low = Left ? i : i + Shift;
6967       unsigned Len = Scale - Shift;
6968       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6969                                       Low + (V == V1 ? 0 : Size)))
6970         return SDValue();
6971     }
6972
6973     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6974     bool ByteShift = ShiftEltBits > 64;
6975     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6976                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6977     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6978
6979     // Normalize the scale for byte shifts to still produce an i64 element
6980     // type.
6981     Scale = ByteShift ? Scale / 2 : Scale;
6982
6983     // We need to round trip through the appropriate type for the shift.
6984     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6985     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6986     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6987            "Illegal integer vector type");
6988     V = DAG.getBitcast(ShiftVT, V);
6989
6990     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6991                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6992     return DAG.getBitcast(VT, V);
6993   };
6994
6995   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6996   // keep doubling the size of the integer elements up to that. We can
6997   // then shift the elements of the integer vector by whole multiples of
6998   // their width within the elements of the larger integer vector. Test each
6999   // multiple to see if we can find a match with the moved element indices
7000   // and that the shifted in elements are all zeroable.
7001   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
7002     for (int Shift = 1; Shift != Scale; ++Shift)
7003       for (bool Left : {true, false})
7004         if (CheckZeros(Shift, Scale, Left))
7005           for (SDValue V : {V1, V2})
7006             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
7007               return Match;
7008
7009   // no match
7010   return SDValue();
7011 }
7012
7013 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
7014 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
7015                                            SDValue V2, ArrayRef<int> Mask,
7016                                            SelectionDAG &DAG) {
7017   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7018   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
7019
7020   int Size = Mask.size();
7021   int HalfSize = Size / 2;
7022   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
7023
7024   // Upper half must be undefined.
7025   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7026     return SDValue();
7027
7028   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7029   // Remainder of lower half result is zero and upper half is all undef.
7030   auto LowerAsEXTRQ = [&]() {
7031     // Determine the extraction length from the part of the
7032     // lower half that isn't zeroable.
7033     int Len = HalfSize;
7034     for (; Len >= 0; --Len)
7035       if (!Zeroable[Len - 1])
7036         break;
7037     assert(Len > 0 && "Zeroable shuffle mask");
7038
7039     // Attempt to match first Len sequential elements from the lower half.
7040     SDValue Src;
7041     int Idx = -1;
7042     for (int i = 0; i != Len; ++i) {
7043       int M = Mask[i];
7044       if (M < 0)
7045         continue;
7046       SDValue &V = (M < Size ? V1 : V2);
7047       M = M % Size;
7048
7049       // All mask elements must be in the lower half.
7050       if (M > HalfSize)
7051         return SDValue();
7052
7053       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7054         Src = V;
7055         Idx = M - i;
7056         continue;
7057       }
7058       return SDValue();
7059     }
7060
7061     if (Idx < 0)
7062       return SDValue();
7063
7064     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7065     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7066     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7067     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7068                        DAG.getConstant(BitLen, DL, MVT::i8),
7069                        DAG.getConstant(BitIdx, DL, MVT::i8));
7070   };
7071
7072   if (SDValue ExtrQ = LowerAsEXTRQ())
7073     return ExtrQ;
7074
7075   // INSERTQ: Extract lowest Len elements from lower half of second source and
7076   // insert over first source, starting at Idx.
7077   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7078   auto LowerAsInsertQ = [&]() {
7079     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7080       SDValue Base;
7081
7082       // Attempt to match first source from mask before insertion point.
7083       if (isUndefInRange(Mask, 0, Idx)) {
7084         /* EMPTY */
7085       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7086         Base = V1;
7087       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7088         Base = V2;
7089       } else {
7090         continue;
7091       }
7092
7093       // Extend the extraction length looking to match both the insertion of
7094       // the second source and the remaining elements of the first.
7095       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7096         SDValue Insert;
7097         int Len = Hi - Idx;
7098
7099         // Match insertion.
7100         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7101           Insert = V1;
7102         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7103           Insert = V2;
7104         } else {
7105           continue;
7106         }
7107
7108         // Match the remaining elements of the lower half.
7109         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7110           /* EMPTY */
7111         } else if ((!Base || (Base == V1)) &&
7112                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7113           Base = V1;
7114         } else if ((!Base || (Base == V2)) &&
7115                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7116                                               Size + Hi)) {
7117           Base = V2;
7118         } else {
7119           continue;
7120         }
7121
7122         // We may not have a base (first source) - this can safely be undefined.
7123         if (!Base)
7124           Base = DAG.getUNDEF(VT);
7125
7126         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7127         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7128         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7129                            DAG.getConstant(BitLen, DL, MVT::i8),
7130                            DAG.getConstant(BitIdx, DL, MVT::i8));
7131       }
7132     }
7133
7134     return SDValue();
7135   };
7136
7137   if (SDValue InsertQ = LowerAsInsertQ())
7138     return InsertQ;
7139
7140   return SDValue();
7141 }
7142
7143 /// \brief Lower a vector shuffle as a zero or any extension.
7144 ///
7145 /// Given a specific number of elements, element bit width, and extension
7146 /// stride, produce either a zero or any extension based on the available
7147 /// features of the subtarget.
7148 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7149     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7150     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7151   assert(Scale > 1 && "Need a scale to extend.");
7152   int NumElements = VT.getVectorNumElements();
7153   int EltBits = VT.getScalarSizeInBits();
7154   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7155          "Only 8, 16, and 32 bit elements can be extended.");
7156   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7157
7158   // Found a valid zext mask! Try various lowering strategies based on the
7159   // input type and available ISA extensions.
7160   if (Subtarget->hasSSE41()) {
7161     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7162                                  NumElements / Scale);
7163     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7164   }
7165
7166   // For any extends we can cheat for larger element sizes and use shuffle
7167   // instructions that can fold with a load and/or copy.
7168   if (AnyExt && EltBits == 32) {
7169     int PSHUFDMask[4] = {0, -1, 1, -1};
7170     return DAG.getBitcast(
7171         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7172                         DAG.getBitcast(MVT::v4i32, InputV),
7173                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7174   }
7175   if (AnyExt && EltBits == 16 && Scale > 2) {
7176     int PSHUFDMask[4] = {0, -1, 0, -1};
7177     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7178                          DAG.getBitcast(MVT::v4i32, InputV),
7179                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7180     int PSHUFHWMask[4] = {1, -1, -1, -1};
7181     return DAG.getBitcast(
7182         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7183                         DAG.getBitcast(MVT::v8i16, InputV),
7184                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7185   }
7186
7187   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7188   // to 64-bits.
7189   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7190     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7191     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7192
7193     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7194                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7195                                          DAG.getConstant(EltBits, DL, MVT::i8),
7196                                          DAG.getConstant(0, DL, MVT::i8)));
7197     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7198       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7199
7200     SDValue Hi =
7201         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7202                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7203                                 DAG.getConstant(EltBits, DL, MVT::i8),
7204                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7205     return DAG.getNode(ISD::BITCAST, DL, VT,
7206                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7207   }
7208
7209   // If this would require more than 2 unpack instructions to expand, use
7210   // pshufb when available. We can only use more than 2 unpack instructions
7211   // when zero extending i8 elements which also makes it easier to use pshufb.
7212   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7213     assert(NumElements == 16 && "Unexpected byte vector width!");
7214     SDValue PSHUFBMask[16];
7215     for (int i = 0; i < 16; ++i)
7216       PSHUFBMask[i] =
7217           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7218     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7219     return DAG.getBitcast(VT,
7220                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7221                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7222                                                   MVT::v16i8, PSHUFBMask)));
7223   }
7224
7225   // Otherwise emit a sequence of unpacks.
7226   do {
7227     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7228     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7229                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7230     InputV = DAG.getBitcast(InputVT, InputV);
7231     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7232     Scale /= 2;
7233     EltBits *= 2;
7234     NumElements /= 2;
7235   } while (Scale > 1);
7236   return DAG.getBitcast(VT, InputV);
7237 }
7238
7239 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7240 ///
7241 /// This routine will try to do everything in its power to cleverly lower
7242 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7243 /// check for the profitability of this lowering,  it tries to aggressively
7244 /// match this pattern. It will use all of the micro-architectural details it
7245 /// can to emit an efficient lowering. It handles both blends with all-zero
7246 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7247 /// masking out later).
7248 ///
7249 /// The reason we have dedicated lowering for zext-style shuffles is that they
7250 /// are both incredibly common and often quite performance sensitive.
7251 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7252     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7253     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7254   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7255
7256   int Bits = VT.getSizeInBits();
7257   int NumElements = VT.getVectorNumElements();
7258   assert(VT.getScalarSizeInBits() <= 32 &&
7259          "Exceeds 32-bit integer zero extension limit");
7260   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7261
7262   // Define a helper function to check a particular ext-scale and lower to it if
7263   // valid.
7264   auto Lower = [&](int Scale) -> SDValue {
7265     SDValue InputV;
7266     bool AnyExt = true;
7267     for (int i = 0; i < NumElements; ++i) {
7268       if (Mask[i] == -1)
7269         continue; // Valid anywhere but doesn't tell us anything.
7270       if (i % Scale != 0) {
7271         // Each of the extended elements need to be zeroable.
7272         if (!Zeroable[i])
7273           return SDValue();
7274
7275         // We no longer are in the anyext case.
7276         AnyExt = false;
7277         continue;
7278       }
7279
7280       // Each of the base elements needs to be consecutive indices into the
7281       // same input vector.
7282       SDValue V = Mask[i] < NumElements ? V1 : V2;
7283       if (!InputV)
7284         InputV = V;
7285       else if (InputV != V)
7286         return SDValue(); // Flip-flopping inputs.
7287
7288       if (Mask[i] % NumElements != i / Scale)
7289         return SDValue(); // Non-consecutive strided elements.
7290     }
7291
7292     // If we fail to find an input, we have a zero-shuffle which should always
7293     // have already been handled.
7294     // FIXME: Maybe handle this here in case during blending we end up with one?
7295     if (!InputV)
7296       return SDValue();
7297
7298     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7299         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7300   };
7301
7302   // The widest scale possible for extending is to a 64-bit integer.
7303   assert(Bits % 64 == 0 &&
7304          "The number of bits in a vector must be divisible by 64 on x86!");
7305   int NumExtElements = Bits / 64;
7306
7307   // Each iteration, try extending the elements half as much, but into twice as
7308   // many elements.
7309   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7310     assert(NumElements % NumExtElements == 0 &&
7311            "The input vector size must be divisible by the extended size.");
7312     if (SDValue V = Lower(NumElements / NumExtElements))
7313       return V;
7314   }
7315
7316   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7317   if (Bits != 128)
7318     return SDValue();
7319
7320   // Returns one of the source operands if the shuffle can be reduced to a
7321   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7322   auto CanZExtLowHalf = [&]() {
7323     for (int i = NumElements / 2; i != NumElements; ++i)
7324       if (!Zeroable[i])
7325         return SDValue();
7326     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7327       return V1;
7328     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7329       return V2;
7330     return SDValue();
7331   };
7332
7333   if (SDValue V = CanZExtLowHalf()) {
7334     V = DAG.getBitcast(MVT::v2i64, V);
7335     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7336     return DAG.getBitcast(VT, V);
7337   }
7338
7339   // No viable ext lowering found.
7340   return SDValue();
7341 }
7342
7343 /// \brief Try to get a scalar value for a specific element of a vector.
7344 ///
7345 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7346 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7347                                               SelectionDAG &DAG) {
7348   MVT VT = V.getSimpleValueType();
7349   MVT EltVT = VT.getVectorElementType();
7350   while (V.getOpcode() == ISD::BITCAST)
7351     V = V.getOperand(0);
7352   // If the bitcasts shift the element size, we can't extract an equivalent
7353   // element from it.
7354   MVT NewVT = V.getSimpleValueType();
7355   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7356     return SDValue();
7357
7358   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7359       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7360     // Ensure the scalar operand is the same size as the destination.
7361     // FIXME: Add support for scalar truncation where possible.
7362     SDValue S = V.getOperand(Idx);
7363     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7364       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7365   }
7366
7367   return SDValue();
7368 }
7369
7370 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7371 ///
7372 /// This is particularly important because the set of instructions varies
7373 /// significantly based on whether the operand is a load or not.
7374 static bool isShuffleFoldableLoad(SDValue V) {
7375   while (V.getOpcode() == ISD::BITCAST)
7376     V = V.getOperand(0);
7377
7378   return ISD::isNON_EXTLoad(V.getNode());
7379 }
7380
7381 /// \brief Try to lower insertion of a single element into a zero vector.
7382 ///
7383 /// This is a common pattern that we have especially efficient patterns to lower
7384 /// across all subtarget feature sets.
7385 static SDValue lowerVectorShuffleAsElementInsertion(
7386     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7387     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7388   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7389   MVT ExtVT = VT;
7390   MVT EltVT = VT.getVectorElementType();
7391
7392   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7393                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7394                 Mask.begin();
7395   bool IsV1Zeroable = true;
7396   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7397     if (i != V2Index && !Zeroable[i]) {
7398       IsV1Zeroable = false;
7399       break;
7400     }
7401
7402   // Check for a single input from a SCALAR_TO_VECTOR node.
7403   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7404   // all the smarts here sunk into that routine. However, the current
7405   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7406   // vector shuffle lowering is dead.
7407   SDValue V2S = getScalarValueForVectorElement(V2, Mask[V2Index] - Mask.size(),
7408                                                DAG);
7409   if (V2S && DAG.getTargetLoweringInfo().isTypeLegal(V2S.getValueType())) {
7410     // We need to zext the scalar if it is smaller than an i32.
7411     V2S = DAG.getBitcast(EltVT, V2S);
7412     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7413       // Using zext to expand a narrow element won't work for non-zero
7414       // insertions.
7415       if (!IsV1Zeroable)
7416         return SDValue();
7417
7418       // Zero-extend directly to i32.
7419       ExtVT = MVT::v4i32;
7420       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7421     }
7422     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7423   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7424              EltVT == MVT::i16) {
7425     // Either not inserting from the low element of the input or the input
7426     // element size is too small to use VZEXT_MOVL to clear the high bits.
7427     return SDValue();
7428   }
7429
7430   if (!IsV1Zeroable) {
7431     // If V1 can't be treated as a zero vector we have fewer options to lower
7432     // this. We can't support integer vectors or non-zero targets cheaply, and
7433     // the V1 elements can't be permuted in any way.
7434     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7435     if (!VT.isFloatingPoint() || V2Index != 0)
7436       return SDValue();
7437     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7438     V1Mask[V2Index] = -1;
7439     if (!isNoopShuffleMask(V1Mask))
7440       return SDValue();
7441     // This is essentially a special case blend operation, but if we have
7442     // general purpose blend operations, they are always faster. Bail and let
7443     // the rest of the lowering handle these as blends.
7444     if (Subtarget->hasSSE41())
7445       return SDValue();
7446
7447     // Otherwise, use MOVSD or MOVSS.
7448     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7449            "Only two types of floating point element types to handle!");
7450     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7451                        ExtVT, V1, V2);
7452   }
7453
7454   // This lowering only works for the low element with floating point vectors.
7455   if (VT.isFloatingPoint() && V2Index != 0)
7456     return SDValue();
7457
7458   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7459   if (ExtVT != VT)
7460     V2 = DAG.getBitcast(VT, V2);
7461
7462   if (V2Index != 0) {
7463     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7464     // the desired position. Otherwise it is more efficient to do a vector
7465     // shift left. We know that we can do a vector shift left because all
7466     // the inputs are zero.
7467     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7468       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7469       V2Shuffle[V2Index] = 0;
7470       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7471     } else {
7472       V2 = DAG.getBitcast(MVT::v2i64, V2);
7473       V2 = DAG.getNode(
7474           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7475           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7476                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7477                               DAG.getDataLayout(), VT)));
7478       V2 = DAG.getBitcast(VT, V2);
7479     }
7480   }
7481   return V2;
7482 }
7483
7484 /// \brief Try to lower broadcast of a single element.
7485 ///
7486 /// For convenience, this code also bundles all of the subtarget feature set
7487 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7488 /// a convenient way to factor it out.
7489 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7490                                              ArrayRef<int> Mask,
7491                                              const X86Subtarget *Subtarget,
7492                                              SelectionDAG &DAG) {
7493   if (!Subtarget->hasAVX())
7494     return SDValue();
7495   if (VT.isInteger() && !Subtarget->hasAVX2())
7496     return SDValue();
7497
7498   // Check that the mask is a broadcast.
7499   int BroadcastIdx = -1;
7500   for (int M : Mask)
7501     if (M >= 0 && BroadcastIdx == -1)
7502       BroadcastIdx = M;
7503     else if (M >= 0 && M != BroadcastIdx)
7504       return SDValue();
7505
7506   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7507                                             "a sorted mask where the broadcast "
7508                                             "comes from V1.");
7509
7510   // Go up the chain of (vector) values to find a scalar load that we can
7511   // combine with the broadcast.
7512   for (;;) {
7513     switch (V.getOpcode()) {
7514     case ISD::CONCAT_VECTORS: {
7515       int OperandSize = Mask.size() / V.getNumOperands();
7516       V = V.getOperand(BroadcastIdx / OperandSize);
7517       BroadcastIdx %= OperandSize;
7518       continue;
7519     }
7520
7521     case ISD::INSERT_SUBVECTOR: {
7522       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7523       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7524       if (!ConstantIdx)
7525         break;
7526
7527       int BeginIdx = (int)ConstantIdx->getZExtValue();
7528       int EndIdx =
7529           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7530       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7531         BroadcastIdx -= BeginIdx;
7532         V = VInner;
7533       } else {
7534         V = VOuter;
7535       }
7536       continue;
7537     }
7538     }
7539     break;
7540   }
7541
7542   // Check if this is a broadcast of a scalar. We special case lowering
7543   // for scalars so that we can more effectively fold with loads.
7544   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7545       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7546     V = V.getOperand(BroadcastIdx);
7547
7548     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7549     // Only AVX2 has register broadcasts.
7550     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7551       return SDValue();
7552   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7553     // We can't broadcast from a vector register without AVX2, and we can only
7554     // broadcast from the zero-element of a vector register.
7555     return SDValue();
7556   }
7557
7558   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7559 }
7560
7561 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7562 // INSERTPS when the V1 elements are already in the correct locations
7563 // because otherwise we can just always use two SHUFPS instructions which
7564 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7565 // perform INSERTPS if a single V1 element is out of place and all V2
7566 // elements are zeroable.
7567 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7568                                             ArrayRef<int> Mask,
7569                                             SelectionDAG &DAG) {
7570   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7571   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7572   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7573   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7574
7575   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7576
7577   unsigned ZMask = 0;
7578   int V1DstIndex = -1;
7579   int V2DstIndex = -1;
7580   bool V1UsedInPlace = false;
7581
7582   for (int i = 0; i < 4; ++i) {
7583     // Synthesize a zero mask from the zeroable elements (includes undefs).
7584     if (Zeroable[i]) {
7585       ZMask |= 1 << i;
7586       continue;
7587     }
7588
7589     // Flag if we use any V1 inputs in place.
7590     if (i == Mask[i]) {
7591       V1UsedInPlace = true;
7592       continue;
7593     }
7594
7595     // We can only insert a single non-zeroable element.
7596     if (V1DstIndex != -1 || V2DstIndex != -1)
7597       return SDValue();
7598
7599     if (Mask[i] < 4) {
7600       // V1 input out of place for insertion.
7601       V1DstIndex = i;
7602     } else {
7603       // V2 input for insertion.
7604       V2DstIndex = i;
7605     }
7606   }
7607
7608   // Don't bother if we have no (non-zeroable) element for insertion.
7609   if (V1DstIndex == -1 && V2DstIndex == -1)
7610     return SDValue();
7611
7612   // Determine element insertion src/dst indices. The src index is from the
7613   // start of the inserted vector, not the start of the concatenated vector.
7614   unsigned V2SrcIndex = 0;
7615   if (V1DstIndex != -1) {
7616     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7617     // and don't use the original V2 at all.
7618     V2SrcIndex = Mask[V1DstIndex];
7619     V2DstIndex = V1DstIndex;
7620     V2 = V1;
7621   } else {
7622     V2SrcIndex = Mask[V2DstIndex] - 4;
7623   }
7624
7625   // If no V1 inputs are used in place, then the result is created only from
7626   // the zero mask and the V2 insertion - so remove V1 dependency.
7627   if (!V1UsedInPlace)
7628     V1 = DAG.getUNDEF(MVT::v4f32);
7629
7630   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7631   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7632
7633   // Insert the V2 element into the desired position.
7634   SDLoc DL(Op);
7635   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7636                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7637 }
7638
7639 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7640 /// UNPCK instruction.
7641 ///
7642 /// This specifically targets cases where we end up with alternating between
7643 /// the two inputs, and so can permute them into something that feeds a single
7644 /// UNPCK instruction. Note that this routine only targets integer vectors
7645 /// because for floating point vectors we have a generalized SHUFPS lowering
7646 /// strategy that handles everything that doesn't *exactly* match an unpack,
7647 /// making this clever lowering unnecessary.
7648 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7649                                           SDValue V2, ArrayRef<int> Mask,
7650                                           SelectionDAG &DAG) {
7651   assert(!VT.isFloatingPoint() &&
7652          "This routine only supports integer vectors.");
7653   assert(!isSingleInputShuffleMask(Mask) &&
7654          "This routine should only be used when blending two inputs.");
7655   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7656
7657   int Size = Mask.size();
7658
7659   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7660     return M >= 0 && M % Size < Size / 2;
7661   });
7662   int NumHiInputs = std::count_if(
7663       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7664
7665   bool UnpackLo = NumLoInputs >= NumHiInputs;
7666
7667   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7668     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7669     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7670
7671     for (int i = 0; i < Size; ++i) {
7672       if (Mask[i] < 0)
7673         continue;
7674
7675       // Each element of the unpack contains Scale elements from this mask.
7676       int UnpackIdx = i / Scale;
7677
7678       // We only handle the case where V1 feeds the first slots of the unpack.
7679       // We rely on canonicalization to ensure this is the case.
7680       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7681         return SDValue();
7682
7683       // Setup the mask for this input. The indexing is tricky as we have to
7684       // handle the unpack stride.
7685       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7686       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7687           Mask[i] % Size;
7688     }
7689
7690     // If we will have to shuffle both inputs to use the unpack, check whether
7691     // we can just unpack first and shuffle the result. If so, skip this unpack.
7692     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7693         !isNoopShuffleMask(V2Mask))
7694       return SDValue();
7695
7696     // Shuffle the inputs into place.
7697     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7698     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7699
7700     // Cast the inputs to the type we will use to unpack them.
7701     V1 = DAG.getBitcast(UnpackVT, V1);
7702     V2 = DAG.getBitcast(UnpackVT, V2);
7703
7704     // Unpack the inputs and cast the result back to the desired type.
7705     return DAG.getBitcast(
7706         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7707                         UnpackVT, V1, V2));
7708   };
7709
7710   // We try each unpack from the largest to the smallest to try and find one
7711   // that fits this mask.
7712   int OrigNumElements = VT.getVectorNumElements();
7713   int OrigScalarSize = VT.getScalarSizeInBits();
7714   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7715     int Scale = ScalarSize / OrigScalarSize;
7716     int NumElements = OrigNumElements / Scale;
7717     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7718     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7719       return Unpack;
7720   }
7721
7722   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7723   // initial unpack.
7724   if (NumLoInputs == 0 || NumHiInputs == 0) {
7725     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7726            "We have to have *some* inputs!");
7727     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7728
7729     // FIXME: We could consider the total complexity of the permute of each
7730     // possible unpacking. Or at the least we should consider how many
7731     // half-crossings are created.
7732     // FIXME: We could consider commuting the unpacks.
7733
7734     SmallVector<int, 32> PermMask;
7735     PermMask.assign(Size, -1);
7736     for (int i = 0; i < Size; ++i) {
7737       if (Mask[i] < 0)
7738         continue;
7739
7740       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7741
7742       PermMask[i] =
7743           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7744     }
7745     return DAG.getVectorShuffle(
7746         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7747                             DL, VT, V1, V2),
7748         DAG.getUNDEF(VT), PermMask);
7749   }
7750
7751   return SDValue();
7752 }
7753
7754 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7755 ///
7756 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7757 /// support for floating point shuffles but not integer shuffles. These
7758 /// instructions will incur a domain crossing penalty on some chips though so
7759 /// it is better to avoid lowering through this for integer vectors where
7760 /// possible.
7761 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7762                                        const X86Subtarget *Subtarget,
7763                                        SelectionDAG &DAG) {
7764   SDLoc DL(Op);
7765   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7766   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7767   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7768   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7769   ArrayRef<int> Mask = SVOp->getMask();
7770   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7771
7772   if (isSingleInputShuffleMask(Mask)) {
7773     // Use low duplicate instructions for masks that match their pattern.
7774     if (Subtarget->hasSSE3())
7775       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7776         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7777
7778     // Straight shuffle of a single input vector. Simulate this by using the
7779     // single input as both of the "inputs" to this instruction..
7780     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7781
7782     if (Subtarget->hasAVX()) {
7783       // If we have AVX, we can use VPERMILPS which will allow folding a load
7784       // into the shuffle.
7785       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7786                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7787     }
7788
7789     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7790                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7791   }
7792   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7793   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7794
7795   // If we have a single input, insert that into V1 if we can do so cheaply.
7796   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7797     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7798             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7799       return Insertion;
7800     // Try inverting the insertion since for v2 masks it is easy to do and we
7801     // can't reliably sort the mask one way or the other.
7802     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7803                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7804     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7805             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7806       return Insertion;
7807   }
7808
7809   // Try to use one of the special instruction patterns to handle two common
7810   // blend patterns if a zero-blend above didn't work.
7811   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7812       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7813     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7814       // We can either use a special instruction to load over the low double or
7815       // to move just the low double.
7816       return DAG.getNode(
7817           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7818           DL, MVT::v2f64, V2,
7819           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7820
7821   if (Subtarget->hasSSE41())
7822     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7823                                                   Subtarget, DAG))
7824       return Blend;
7825
7826   // Use dedicated unpack instructions for masks that match their pattern.
7827   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7828     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7829   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7830     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7831
7832   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7833   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7834                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7835 }
7836
7837 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7838 ///
7839 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7840 /// the integer unit to minimize domain crossing penalties. However, for blends
7841 /// it falls back to the floating point shuffle operation with appropriate bit
7842 /// casting.
7843 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7844                                        const X86Subtarget *Subtarget,
7845                                        SelectionDAG &DAG) {
7846   SDLoc DL(Op);
7847   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7848   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7849   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7850   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7851   ArrayRef<int> Mask = SVOp->getMask();
7852   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7853
7854   if (isSingleInputShuffleMask(Mask)) {
7855     // Check for being able to broadcast a single element.
7856     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7857                                                           Mask, Subtarget, DAG))
7858       return Broadcast;
7859
7860     // Straight shuffle of a single input vector. For everything from SSE2
7861     // onward this has a single fast instruction with no scary immediates.
7862     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7863     V1 = DAG.getBitcast(MVT::v4i32, V1);
7864     int WidenedMask[4] = {
7865         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7866         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7867     return DAG.getBitcast(
7868         MVT::v2i64,
7869         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7870                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7871   }
7872   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7873   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7874   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7875   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7876
7877   // If we have a blend of two PACKUS operations an the blend aligns with the
7878   // low and half halves, we can just merge the PACKUS operations. This is
7879   // particularly important as it lets us merge shuffles that this routine itself
7880   // creates.
7881   auto GetPackNode = [](SDValue V) {
7882     while (V.getOpcode() == ISD::BITCAST)
7883       V = V.getOperand(0);
7884
7885     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7886   };
7887   if (SDValue V1Pack = GetPackNode(V1))
7888     if (SDValue V2Pack = GetPackNode(V2))
7889       return DAG.getBitcast(MVT::v2i64,
7890                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7891                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7892                                                      : V1Pack.getOperand(1),
7893                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7894                                                      : V2Pack.getOperand(1)));
7895
7896   // Try to use shift instructions.
7897   if (SDValue Shift =
7898           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7899     return Shift;
7900
7901   // When loading a scalar and then shuffling it into a vector we can often do
7902   // the insertion cheaply.
7903   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7904           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7905     return Insertion;
7906   // Try inverting the insertion since for v2 masks it is easy to do and we
7907   // can't reliably sort the mask one way or the other.
7908   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7909   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7910           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7911     return Insertion;
7912
7913   // We have different paths for blend lowering, but they all must use the
7914   // *exact* same predicate.
7915   bool IsBlendSupported = Subtarget->hasSSE41();
7916   if (IsBlendSupported)
7917     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7918                                                   Subtarget, DAG))
7919       return Blend;
7920
7921   // Use dedicated unpack instructions for masks that match their pattern.
7922   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7923     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7924   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7925     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7926
7927   // Try to use byte rotation instructions.
7928   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7929   if (Subtarget->hasSSSE3())
7930     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7931             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7932       return Rotate;
7933
7934   // If we have direct support for blends, we should lower by decomposing into
7935   // a permute. That will be faster than the domain cross.
7936   if (IsBlendSupported)
7937     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7938                                                       Mask, DAG);
7939
7940   // We implement this with SHUFPD which is pretty lame because it will likely
7941   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7942   // However, all the alternatives are still more cycles and newer chips don't
7943   // have this problem. It would be really nice if x86 had better shuffles here.
7944   V1 = DAG.getBitcast(MVT::v2f64, V1);
7945   V2 = DAG.getBitcast(MVT::v2f64, V2);
7946   return DAG.getBitcast(MVT::v2i64,
7947                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7948 }
7949
7950 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7951 ///
7952 /// This is used to disable more specialized lowerings when the shufps lowering
7953 /// will happen to be efficient.
7954 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7955   // This routine only handles 128-bit shufps.
7956   assert(Mask.size() == 4 && "Unsupported mask size!");
7957
7958   // To lower with a single SHUFPS we need to have the low half and high half
7959   // each requiring a single input.
7960   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7961     return false;
7962   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7963     return false;
7964
7965   return true;
7966 }
7967
7968 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7969 ///
7970 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7971 /// It makes no assumptions about whether this is the *best* lowering, it simply
7972 /// uses it.
7973 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7974                                             ArrayRef<int> Mask, SDValue V1,
7975                                             SDValue V2, SelectionDAG &DAG) {
7976   SDValue LowV = V1, HighV = V2;
7977   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7978
7979   int NumV2Elements =
7980       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7981
7982   if (NumV2Elements == 1) {
7983     int V2Index =
7984         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7985         Mask.begin();
7986
7987     // Compute the index adjacent to V2Index and in the same half by toggling
7988     // the low bit.
7989     int V2AdjIndex = V2Index ^ 1;
7990
7991     if (Mask[V2AdjIndex] == -1) {
7992       // Handles all the cases where we have a single V2 element and an undef.
7993       // This will only ever happen in the high lanes because we commute the
7994       // vector otherwise.
7995       if (V2Index < 2)
7996         std::swap(LowV, HighV);
7997       NewMask[V2Index] -= 4;
7998     } else {
7999       // Handle the case where the V2 element ends up adjacent to a V1 element.
8000       // To make this work, blend them together as the first step.
8001       int V1Index = V2AdjIndex;
8002       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
8003       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
8004                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8005
8006       // Now proceed to reconstruct the final blend as we have the necessary
8007       // high or low half formed.
8008       if (V2Index < 2) {
8009         LowV = V2;
8010         HighV = V1;
8011       } else {
8012         HighV = V2;
8013       }
8014       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
8015       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
8016     }
8017   } else if (NumV2Elements == 2) {
8018     if (Mask[0] < 4 && Mask[1] < 4) {
8019       // Handle the easy case where we have V1 in the low lanes and V2 in the
8020       // high lanes.
8021       NewMask[2] -= 4;
8022       NewMask[3] -= 4;
8023     } else if (Mask[2] < 4 && Mask[3] < 4) {
8024       // We also handle the reversed case because this utility may get called
8025       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8026       // arrange things in the right direction.
8027       NewMask[0] -= 4;
8028       NewMask[1] -= 4;
8029       HighV = V1;
8030       LowV = V2;
8031     } else {
8032       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8033       // trying to place elements directly, just blend them and set up the final
8034       // shuffle to place them.
8035
8036       // The first two blend mask elements are for V1, the second two are for
8037       // V2.
8038       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8039                           Mask[2] < 4 ? Mask[2] : Mask[3],
8040                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8041                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8042       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8043                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8044
8045       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8046       // a blend.
8047       LowV = HighV = V1;
8048       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8049       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8050       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8051       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8052     }
8053   }
8054   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8055                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8056 }
8057
8058 /// \brief Lower 4-lane 32-bit floating point shuffles.
8059 ///
8060 /// Uses instructions exclusively from the floating point unit to minimize
8061 /// domain crossing penalties, as these are sufficient to implement all v4f32
8062 /// shuffles.
8063 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8064                                        const X86Subtarget *Subtarget,
8065                                        SelectionDAG &DAG) {
8066   SDLoc DL(Op);
8067   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8068   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8069   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8070   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8071   ArrayRef<int> Mask = SVOp->getMask();
8072   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8073
8074   int NumV2Elements =
8075       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8076
8077   if (NumV2Elements == 0) {
8078     // Check for being able to broadcast a single element.
8079     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8080                                                           Mask, Subtarget, DAG))
8081       return Broadcast;
8082
8083     // Use even/odd duplicate instructions for masks that match their pattern.
8084     if (Subtarget->hasSSE3()) {
8085       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8086         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8087       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8088         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8089     }
8090
8091     if (Subtarget->hasAVX()) {
8092       // If we have AVX, we can use VPERMILPS which will allow folding a load
8093       // into the shuffle.
8094       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8095                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8096     }
8097
8098     // Otherwise, use a straight shuffle of a single input vector. We pass the
8099     // input vector to both operands to simulate this with a SHUFPS.
8100     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8101                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8102   }
8103
8104   // There are special ways we can lower some single-element blends. However, we
8105   // have custom ways we can lower more complex single-element blends below that
8106   // we defer to if both this and BLENDPS fail to match, so restrict this to
8107   // when the V2 input is targeting element 0 of the mask -- that is the fast
8108   // case here.
8109   if (NumV2Elements == 1 && Mask[0] >= 4)
8110     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8111                                                          Mask, Subtarget, DAG))
8112       return V;
8113
8114   if (Subtarget->hasSSE41()) {
8115     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8116                                                   Subtarget, DAG))
8117       return Blend;
8118
8119     // Use INSERTPS if we can complete the shuffle efficiently.
8120     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8121       return V;
8122
8123     if (!isSingleSHUFPSMask(Mask))
8124       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8125               DL, MVT::v4f32, V1, V2, Mask, DAG))
8126         return BlendPerm;
8127   }
8128
8129   // Use dedicated unpack instructions for masks that match their pattern.
8130   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8131     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8132   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8133     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8134   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8135     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8136   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8137     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8138
8139   // Otherwise fall back to a SHUFPS lowering strategy.
8140   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8141 }
8142
8143 /// \brief Lower 4-lane i32 vector shuffles.
8144 ///
8145 /// We try to handle these with integer-domain shuffles where we can, but for
8146 /// blends we use the floating point domain blend instructions.
8147 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8148                                        const X86Subtarget *Subtarget,
8149                                        SelectionDAG &DAG) {
8150   SDLoc DL(Op);
8151   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8152   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8153   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8154   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8155   ArrayRef<int> Mask = SVOp->getMask();
8156   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8157
8158   // Whenever we can lower this as a zext, that instruction is strictly faster
8159   // than any alternative. It also allows us to fold memory operands into the
8160   // shuffle in many cases.
8161   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8162                                                          Mask, Subtarget, DAG))
8163     return ZExt;
8164
8165   int NumV2Elements =
8166       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8167
8168   if (NumV2Elements == 0) {
8169     // Check for being able to broadcast a single element.
8170     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8171                                                           Mask, Subtarget, DAG))
8172       return Broadcast;
8173
8174     // Straight shuffle of a single input vector. For everything from SSE2
8175     // onward this has a single fast instruction with no scary immediates.
8176     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8177     // but we aren't actually going to use the UNPCK instruction because doing
8178     // so prevents folding a load into this instruction or making a copy.
8179     const int UnpackLoMask[] = {0, 0, 1, 1};
8180     const int UnpackHiMask[] = {2, 2, 3, 3};
8181     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8182       Mask = UnpackLoMask;
8183     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8184       Mask = UnpackHiMask;
8185
8186     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8187                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8188   }
8189
8190   // Try to use shift instructions.
8191   if (SDValue Shift =
8192           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8193     return Shift;
8194
8195   // There are special ways we can lower some single-element blends.
8196   if (NumV2Elements == 1)
8197     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8198                                                          Mask, Subtarget, DAG))
8199       return V;
8200
8201   // We have different paths for blend lowering, but they all must use the
8202   // *exact* same predicate.
8203   bool IsBlendSupported = Subtarget->hasSSE41();
8204   if (IsBlendSupported)
8205     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8206                                                   Subtarget, DAG))
8207       return Blend;
8208
8209   if (SDValue Masked =
8210           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8211     return Masked;
8212
8213   // Use dedicated unpack instructions for masks that match their pattern.
8214   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8215     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8216   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8217     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8218   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8219     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8220   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8221     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8222
8223   // Try to use byte rotation instructions.
8224   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8225   if (Subtarget->hasSSSE3())
8226     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8227             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8228       return Rotate;
8229
8230   // If we have direct support for blends, we should lower by decomposing into
8231   // a permute. That will be faster than the domain cross.
8232   if (IsBlendSupported)
8233     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8234                                                       Mask, DAG);
8235
8236   // Try to lower by permuting the inputs into an unpack instruction.
8237   if (SDValue Unpack =
8238           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8239     return Unpack;
8240
8241   // We implement this with SHUFPS because it can blend from two vectors.
8242   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8243   // up the inputs, bypassing domain shift penalties that we would encur if we
8244   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8245   // relevant.
8246   return DAG.getBitcast(
8247       MVT::v4i32,
8248       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8249                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8250 }
8251
8252 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8253 /// shuffle lowering, and the most complex part.
8254 ///
8255 /// The lowering strategy is to try to form pairs of input lanes which are
8256 /// targeted at the same half of the final vector, and then use a dword shuffle
8257 /// to place them onto the right half, and finally unpack the paired lanes into
8258 /// their final position.
8259 ///
8260 /// The exact breakdown of how to form these dword pairs and align them on the
8261 /// correct sides is really tricky. See the comments within the function for
8262 /// more of the details.
8263 ///
8264 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8265 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8266 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8267 /// vector, form the analogous 128-bit 8-element Mask.
8268 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8269     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8270     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8271   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8272   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8273
8274   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8275   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8276   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8277
8278   SmallVector<int, 4> LoInputs;
8279   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8280                [](int M) { return M >= 0; });
8281   std::sort(LoInputs.begin(), LoInputs.end());
8282   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8283   SmallVector<int, 4> HiInputs;
8284   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8285                [](int M) { return M >= 0; });
8286   std::sort(HiInputs.begin(), HiInputs.end());
8287   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8288   int NumLToL =
8289       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8290   int NumHToL = LoInputs.size() - NumLToL;
8291   int NumLToH =
8292       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8293   int NumHToH = HiInputs.size() - NumLToH;
8294   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8295   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8296   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8297   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8298
8299   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8300   // such inputs we can swap two of the dwords across the half mark and end up
8301   // with <=2 inputs to each half in each half. Once there, we can fall through
8302   // to the generic code below. For example:
8303   //
8304   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8305   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8306   //
8307   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8308   // and an existing 2-into-2 on the other half. In this case we may have to
8309   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8310   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8311   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8312   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8313   // half than the one we target for fixing) will be fixed when we re-enter this
8314   // path. We will also combine away any sequence of PSHUFD instructions that
8315   // result into a single instruction. Here is an example of the tricky case:
8316   //
8317   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8318   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8319   //
8320   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8321   //
8322   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8323   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8324   //
8325   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8326   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8327   //
8328   // The result is fine to be handled by the generic logic.
8329   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8330                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8331                           int AOffset, int BOffset) {
8332     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8333            "Must call this with A having 3 or 1 inputs from the A half.");
8334     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8335            "Must call this with B having 1 or 3 inputs from the B half.");
8336     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8337            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8338
8339     // Compute the index of dword with only one word among the three inputs in
8340     // a half by taking the sum of the half with three inputs and subtracting
8341     // the sum of the actual three inputs. The difference is the remaining
8342     // slot.
8343     int ADWord, BDWord;
8344     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8345     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8346     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8347     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8348     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8349     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8350     int TripleNonInputIdx =
8351         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8352     TripleDWord = TripleNonInputIdx / 2;
8353
8354     // We use xor with one to compute the adjacent DWord to whichever one the
8355     // OneInput is in.
8356     OneInputDWord = (OneInput / 2) ^ 1;
8357
8358     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8359     // and BToA inputs. If there is also such a problem with the BToB and AToB
8360     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8361     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8362     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8363     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8364       // Compute how many inputs will be flipped by swapping these DWords. We
8365       // need
8366       // to balance this to ensure we don't form a 3-1 shuffle in the other
8367       // half.
8368       int NumFlippedAToBInputs =
8369           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8370           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8371       int NumFlippedBToBInputs =
8372           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8373           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8374       if ((NumFlippedAToBInputs == 1 &&
8375            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8376           (NumFlippedBToBInputs == 1 &&
8377            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8378         // We choose whether to fix the A half or B half based on whether that
8379         // half has zero flipped inputs. At zero, we may not be able to fix it
8380         // with that half. We also bias towards fixing the B half because that
8381         // will more commonly be the high half, and we have to bias one way.
8382         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8383                                                        ArrayRef<int> Inputs) {
8384           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8385           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8386                                          PinnedIdx ^ 1) != Inputs.end();
8387           // Determine whether the free index is in the flipped dword or the
8388           // unflipped dword based on where the pinned index is. We use this bit
8389           // in an xor to conditionally select the adjacent dword.
8390           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8391           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8392                                              FixFreeIdx) != Inputs.end();
8393           if (IsFixIdxInput == IsFixFreeIdxInput)
8394             FixFreeIdx += 1;
8395           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8396                                         FixFreeIdx) != Inputs.end();
8397           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8398                  "We need to be changing the number of flipped inputs!");
8399           int PSHUFHalfMask[] = {0, 1, 2, 3};
8400           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8401           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8402                           MVT::v8i16, V,
8403                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8404
8405           for (int &M : Mask)
8406             if (M != -1 && M == FixIdx)
8407               M = FixFreeIdx;
8408             else if (M != -1 && M == FixFreeIdx)
8409               M = FixIdx;
8410         };
8411         if (NumFlippedBToBInputs != 0) {
8412           int BPinnedIdx =
8413               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8414           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8415         } else {
8416           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8417           int APinnedIdx =
8418               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8419           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8420         }
8421       }
8422     }
8423
8424     int PSHUFDMask[] = {0, 1, 2, 3};
8425     PSHUFDMask[ADWord] = BDWord;
8426     PSHUFDMask[BDWord] = ADWord;
8427     V = DAG.getBitcast(
8428         VT,
8429         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8430                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8431
8432     // Adjust the mask to match the new locations of A and B.
8433     for (int &M : Mask)
8434       if (M != -1 && M/2 == ADWord)
8435         M = 2 * BDWord + M % 2;
8436       else if (M != -1 && M/2 == BDWord)
8437         M = 2 * ADWord + M % 2;
8438
8439     // Recurse back into this routine to re-compute state now that this isn't
8440     // a 3 and 1 problem.
8441     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8442                                                      DAG);
8443   };
8444   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8445     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8446   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8447     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8448
8449   // At this point there are at most two inputs to the low and high halves from
8450   // each half. That means the inputs can always be grouped into dwords and
8451   // those dwords can then be moved to the correct half with a dword shuffle.
8452   // We use at most one low and one high word shuffle to collect these paired
8453   // inputs into dwords, and finally a dword shuffle to place them.
8454   int PSHUFLMask[4] = {-1, -1, -1, -1};
8455   int PSHUFHMask[4] = {-1, -1, -1, -1};
8456   int PSHUFDMask[4] = {-1, -1, -1, -1};
8457
8458   // First fix the masks for all the inputs that are staying in their
8459   // original halves. This will then dictate the targets of the cross-half
8460   // shuffles.
8461   auto fixInPlaceInputs =
8462       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8463                     MutableArrayRef<int> SourceHalfMask,
8464                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8465     if (InPlaceInputs.empty())
8466       return;
8467     if (InPlaceInputs.size() == 1) {
8468       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8469           InPlaceInputs[0] - HalfOffset;
8470       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8471       return;
8472     }
8473     if (IncomingInputs.empty()) {
8474       // Just fix all of the in place inputs.
8475       for (int Input : InPlaceInputs) {
8476         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8477         PSHUFDMask[Input / 2] = Input / 2;
8478       }
8479       return;
8480     }
8481
8482     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8483     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8484         InPlaceInputs[0] - HalfOffset;
8485     // Put the second input next to the first so that they are packed into
8486     // a dword. We find the adjacent index by toggling the low bit.
8487     int AdjIndex = InPlaceInputs[0] ^ 1;
8488     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8489     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8490     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8491   };
8492   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8493   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8494
8495   // Now gather the cross-half inputs and place them into a free dword of
8496   // their target half.
8497   // FIXME: This operation could almost certainly be simplified dramatically to
8498   // look more like the 3-1 fixing operation.
8499   auto moveInputsToRightHalf = [&PSHUFDMask](
8500       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8501       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8502       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8503       int DestOffset) {
8504     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8505       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8506     };
8507     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8508                                                int Word) {
8509       int LowWord = Word & ~1;
8510       int HighWord = Word | 1;
8511       return isWordClobbered(SourceHalfMask, LowWord) ||
8512              isWordClobbered(SourceHalfMask, HighWord);
8513     };
8514
8515     if (IncomingInputs.empty())
8516       return;
8517
8518     if (ExistingInputs.empty()) {
8519       // Map any dwords with inputs from them into the right half.
8520       for (int Input : IncomingInputs) {
8521         // If the source half mask maps over the inputs, turn those into
8522         // swaps and use the swapped lane.
8523         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8524           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8525             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8526                 Input - SourceOffset;
8527             // We have to swap the uses in our half mask in one sweep.
8528             for (int &M : HalfMask)
8529               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8530                 M = Input;
8531               else if (M == Input)
8532                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8533           } else {
8534             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8535                        Input - SourceOffset &&
8536                    "Previous placement doesn't match!");
8537           }
8538           // Note that this correctly re-maps both when we do a swap and when
8539           // we observe the other side of the swap above. We rely on that to
8540           // avoid swapping the members of the input list directly.
8541           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8542         }
8543
8544         // Map the input's dword into the correct half.
8545         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8546           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8547         else
8548           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8549                      Input / 2 &&
8550                  "Previous placement doesn't match!");
8551       }
8552
8553       // And just directly shift any other-half mask elements to be same-half
8554       // as we will have mirrored the dword containing the element into the
8555       // same position within that half.
8556       for (int &M : HalfMask)
8557         if (M >= SourceOffset && M < SourceOffset + 4) {
8558           M = M - SourceOffset + DestOffset;
8559           assert(M >= 0 && "This should never wrap below zero!");
8560         }
8561       return;
8562     }
8563
8564     // Ensure we have the input in a viable dword of its current half. This
8565     // is particularly tricky because the original position may be clobbered
8566     // by inputs being moved and *staying* in that half.
8567     if (IncomingInputs.size() == 1) {
8568       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8569         int InputFixed = std::find(std::begin(SourceHalfMask),
8570                                    std::end(SourceHalfMask), -1) -
8571                          std::begin(SourceHalfMask) + SourceOffset;
8572         SourceHalfMask[InputFixed - SourceOffset] =
8573             IncomingInputs[0] - SourceOffset;
8574         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8575                      InputFixed);
8576         IncomingInputs[0] = InputFixed;
8577       }
8578     } else if (IncomingInputs.size() == 2) {
8579       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8580           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8581         // We have two non-adjacent or clobbered inputs we need to extract from
8582         // the source half. To do this, we need to map them into some adjacent
8583         // dword slot in the source mask.
8584         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8585                               IncomingInputs[1] - SourceOffset};
8586
8587         // If there is a free slot in the source half mask adjacent to one of
8588         // the inputs, place the other input in it. We use (Index XOR 1) to
8589         // compute an adjacent index.
8590         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8591             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8592           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8593           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8594           InputsFixed[1] = InputsFixed[0] ^ 1;
8595         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8596                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8597           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8598           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8599           InputsFixed[0] = InputsFixed[1] ^ 1;
8600         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8601                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8602           // The two inputs are in the same DWord but it is clobbered and the
8603           // adjacent DWord isn't used at all. Move both inputs to the free
8604           // slot.
8605           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8606           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8607           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8608           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8609         } else {
8610           // The only way we hit this point is if there is no clobbering
8611           // (because there are no off-half inputs to this half) and there is no
8612           // free slot adjacent to one of the inputs. In this case, we have to
8613           // swap an input with a non-input.
8614           for (int i = 0; i < 4; ++i)
8615             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8616                    "We can't handle any clobbers here!");
8617           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8618                  "Cannot have adjacent inputs here!");
8619
8620           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8621           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8622
8623           // We also have to update the final source mask in this case because
8624           // it may need to undo the above swap.
8625           for (int &M : FinalSourceHalfMask)
8626             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8627               M = InputsFixed[1] + SourceOffset;
8628             else if (M == InputsFixed[1] + SourceOffset)
8629               M = (InputsFixed[0] ^ 1) + SourceOffset;
8630
8631           InputsFixed[1] = InputsFixed[0] ^ 1;
8632         }
8633
8634         // Point everything at the fixed inputs.
8635         for (int &M : HalfMask)
8636           if (M == IncomingInputs[0])
8637             M = InputsFixed[0] + SourceOffset;
8638           else if (M == IncomingInputs[1])
8639             M = InputsFixed[1] + SourceOffset;
8640
8641         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8642         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8643       }
8644     } else {
8645       llvm_unreachable("Unhandled input size!");
8646     }
8647
8648     // Now hoist the DWord down to the right half.
8649     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8650     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8651     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8652     for (int &M : HalfMask)
8653       for (int Input : IncomingInputs)
8654         if (M == Input)
8655           M = FreeDWord * 2 + Input % 2;
8656   };
8657   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8658                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8659   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8660                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8661
8662   // Now enact all the shuffles we've computed to move the inputs into their
8663   // target half.
8664   if (!isNoopShuffleMask(PSHUFLMask))
8665     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8666                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8667   if (!isNoopShuffleMask(PSHUFHMask))
8668     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8669                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8670   if (!isNoopShuffleMask(PSHUFDMask))
8671     V = DAG.getBitcast(
8672         VT,
8673         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8674                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8675
8676   // At this point, each half should contain all its inputs, and we can then
8677   // just shuffle them into their final position.
8678   assert(std::count_if(LoMask.begin(), LoMask.end(),
8679                        [](int M) { return M >= 4; }) == 0 &&
8680          "Failed to lift all the high half inputs to the low mask!");
8681   assert(std::count_if(HiMask.begin(), HiMask.end(),
8682                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8683          "Failed to lift all the low half inputs to the high mask!");
8684
8685   // Do a half shuffle for the low mask.
8686   if (!isNoopShuffleMask(LoMask))
8687     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8688                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8689
8690   // Do a half shuffle with the high mask after shifting its values down.
8691   for (int &M : HiMask)
8692     if (M >= 0)
8693       M -= 4;
8694   if (!isNoopShuffleMask(HiMask))
8695     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8696                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8697
8698   return V;
8699 }
8700
8701 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8702 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8703                                           SDValue V2, ArrayRef<int> Mask,
8704                                           SelectionDAG &DAG, bool &V1InUse,
8705                                           bool &V2InUse) {
8706   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8707   SDValue V1Mask[16];
8708   SDValue V2Mask[16];
8709   V1InUse = false;
8710   V2InUse = false;
8711
8712   int Size = Mask.size();
8713   int Scale = 16 / Size;
8714   for (int i = 0; i < 16; ++i) {
8715     if (Mask[i / Scale] == -1) {
8716       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8717     } else {
8718       const int ZeroMask = 0x80;
8719       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8720                                           : ZeroMask;
8721       int V2Idx = Mask[i / Scale] < Size
8722                       ? ZeroMask
8723                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8724       if (Zeroable[i / Scale])
8725         V1Idx = V2Idx = ZeroMask;
8726       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8727       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8728       V1InUse |= (ZeroMask != V1Idx);
8729       V2InUse |= (ZeroMask != V2Idx);
8730     }
8731   }
8732
8733   if (V1InUse)
8734     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8735                      DAG.getBitcast(MVT::v16i8, V1),
8736                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8737   if (V2InUse)
8738     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8739                      DAG.getBitcast(MVT::v16i8, V2),
8740                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8741
8742   // If we need shuffled inputs from both, blend the two.
8743   SDValue V;
8744   if (V1InUse && V2InUse)
8745     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8746   else
8747     V = V1InUse ? V1 : V2;
8748
8749   // Cast the result back to the correct type.
8750   return DAG.getBitcast(VT, V);
8751 }
8752
8753 /// \brief Generic lowering of 8-lane i16 shuffles.
8754 ///
8755 /// This handles both single-input shuffles and combined shuffle/blends with
8756 /// two inputs. The single input shuffles are immediately delegated to
8757 /// a dedicated lowering routine.
8758 ///
8759 /// The blends are lowered in one of three fundamental ways. If there are few
8760 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8761 /// of the input is significantly cheaper when lowered as an interleaving of
8762 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8763 /// halves of the inputs separately (making them have relatively few inputs)
8764 /// and then concatenate them.
8765 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8766                                        const X86Subtarget *Subtarget,
8767                                        SelectionDAG &DAG) {
8768   SDLoc DL(Op);
8769   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8770   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8771   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8772   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8773   ArrayRef<int> OrigMask = SVOp->getMask();
8774   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8775                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8776   MutableArrayRef<int> Mask(MaskStorage);
8777
8778   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8779
8780   // Whenever we can lower this as a zext, that instruction is strictly faster
8781   // than any alternative.
8782   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8783           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8784     return ZExt;
8785
8786   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8787   (void)isV1;
8788   auto isV2 = [](int M) { return M >= 8; };
8789
8790   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8791
8792   if (NumV2Inputs == 0) {
8793     // Check for being able to broadcast a single element.
8794     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8795                                                           Mask, Subtarget, DAG))
8796       return Broadcast;
8797
8798     // Try to use shift instructions.
8799     if (SDValue Shift =
8800             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8801       return Shift;
8802
8803     // Use dedicated unpack instructions for masks that match their pattern.
8804     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8805       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8806     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8807       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8808
8809     // Try to use byte rotation instructions.
8810     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8811                                                         Mask, Subtarget, DAG))
8812       return Rotate;
8813
8814     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8815                                                      Subtarget, DAG);
8816   }
8817
8818   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8819          "All single-input shuffles should be canonicalized to be V1-input "
8820          "shuffles.");
8821
8822   // Try to use shift instructions.
8823   if (SDValue Shift =
8824           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8825     return Shift;
8826
8827   // See if we can use SSE4A Extraction / Insertion.
8828   if (Subtarget->hasSSE4A())
8829     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8830       return V;
8831
8832   // There are special ways we can lower some single-element blends.
8833   if (NumV2Inputs == 1)
8834     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8835                                                          Mask, Subtarget, DAG))
8836       return V;
8837
8838   // We have different paths for blend lowering, but they all must use the
8839   // *exact* same predicate.
8840   bool IsBlendSupported = Subtarget->hasSSE41();
8841   if (IsBlendSupported)
8842     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8843                                                   Subtarget, DAG))
8844       return Blend;
8845
8846   if (SDValue Masked =
8847           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8848     return Masked;
8849
8850   // Use dedicated unpack instructions for masks that match their pattern.
8851   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8852     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8853   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8854     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8855
8856   // Try to use byte rotation instructions.
8857   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8858           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8859     return Rotate;
8860
8861   if (SDValue BitBlend =
8862           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8863     return BitBlend;
8864
8865   if (SDValue Unpack =
8866           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8867     return Unpack;
8868
8869   // If we can't directly blend but can use PSHUFB, that will be better as it
8870   // can both shuffle and set up the inefficient blend.
8871   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8872     bool V1InUse, V2InUse;
8873     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8874                                       V1InUse, V2InUse);
8875   }
8876
8877   // We can always bit-blend if we have to so the fallback strategy is to
8878   // decompose into single-input permutes and blends.
8879   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8880                                                       Mask, DAG);
8881 }
8882
8883 /// \brief Check whether a compaction lowering can be done by dropping even
8884 /// elements and compute how many times even elements must be dropped.
8885 ///
8886 /// This handles shuffles which take every Nth element where N is a power of
8887 /// two. Example shuffle masks:
8888 ///
8889 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8890 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8891 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8892 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8893 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8894 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8895 ///
8896 /// Any of these lanes can of course be undef.
8897 ///
8898 /// This routine only supports N <= 3.
8899 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8900 /// for larger N.
8901 ///
8902 /// \returns N above, or the number of times even elements must be dropped if
8903 /// there is such a number. Otherwise returns zero.
8904 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8905   // Figure out whether we're looping over two inputs or just one.
8906   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8907
8908   // The modulus for the shuffle vector entries is based on whether this is
8909   // a single input or not.
8910   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8911   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8912          "We should only be called with masks with a power-of-2 size!");
8913
8914   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8915
8916   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8917   // and 2^3 simultaneously. This is because we may have ambiguity with
8918   // partially undef inputs.
8919   bool ViableForN[3] = {true, true, true};
8920
8921   for (int i = 0, e = Mask.size(); i < e; ++i) {
8922     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8923     // want.
8924     if (Mask[i] == -1)
8925       continue;
8926
8927     bool IsAnyViable = false;
8928     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8929       if (ViableForN[j]) {
8930         uint64_t N = j + 1;
8931
8932         // The shuffle mask must be equal to (i * 2^N) % M.
8933         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8934           IsAnyViable = true;
8935         else
8936           ViableForN[j] = false;
8937       }
8938     // Early exit if we exhaust the possible powers of two.
8939     if (!IsAnyViable)
8940       break;
8941   }
8942
8943   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8944     if (ViableForN[j])
8945       return j + 1;
8946
8947   // Return 0 as there is no viable power of two.
8948   return 0;
8949 }
8950
8951 /// \brief Generic lowering of v16i8 shuffles.
8952 ///
8953 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8954 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8955 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8956 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8957 /// back together.
8958 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8959                                        const X86Subtarget *Subtarget,
8960                                        SelectionDAG &DAG) {
8961   SDLoc DL(Op);
8962   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8963   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8964   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8965   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8966   ArrayRef<int> Mask = SVOp->getMask();
8967   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8968
8969   // Try to use shift instructions.
8970   if (SDValue Shift =
8971           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8972     return Shift;
8973
8974   // Try to use byte rotation instructions.
8975   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8976           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8977     return Rotate;
8978
8979   // Try to use a zext lowering.
8980   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8981           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8982     return ZExt;
8983
8984   // See if we can use SSE4A Extraction / Insertion.
8985   if (Subtarget->hasSSE4A())
8986     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8987       return V;
8988
8989   int NumV2Elements =
8990       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8991
8992   // For single-input shuffles, there are some nicer lowering tricks we can use.
8993   if (NumV2Elements == 0) {
8994     // Check for being able to broadcast a single element.
8995     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8996                                                           Mask, Subtarget, DAG))
8997       return Broadcast;
8998
8999     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
9000     // Notably, this handles splat and partial-splat shuffles more efficiently.
9001     // However, it only makes sense if the pre-duplication shuffle simplifies
9002     // things significantly. Currently, this means we need to be able to
9003     // express the pre-duplication shuffle as an i16 shuffle.
9004     //
9005     // FIXME: We should check for other patterns which can be widened into an
9006     // i16 shuffle as well.
9007     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
9008       for (int i = 0; i < 16; i += 2)
9009         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
9010           return false;
9011
9012       return true;
9013     };
9014     auto tryToWidenViaDuplication = [&]() -> SDValue {
9015       if (!canWidenViaDuplication(Mask))
9016         return SDValue();
9017       SmallVector<int, 4> LoInputs;
9018       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
9019                    [](int M) { return M >= 0 && M < 8; });
9020       std::sort(LoInputs.begin(), LoInputs.end());
9021       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
9022                      LoInputs.end());
9023       SmallVector<int, 4> HiInputs;
9024       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9025                    [](int M) { return M >= 8; });
9026       std::sort(HiInputs.begin(), HiInputs.end());
9027       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9028                      HiInputs.end());
9029
9030       bool TargetLo = LoInputs.size() >= HiInputs.size();
9031       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9032       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9033
9034       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9035       SmallDenseMap<int, int, 8> LaneMap;
9036       for (int I : InPlaceInputs) {
9037         PreDupI16Shuffle[I/2] = I/2;
9038         LaneMap[I] = I;
9039       }
9040       int j = TargetLo ? 0 : 4, je = j + 4;
9041       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9042         // Check if j is already a shuffle of this input. This happens when
9043         // there are two adjacent bytes after we move the low one.
9044         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9045           // If we haven't yet mapped the input, search for a slot into which
9046           // we can map it.
9047           while (j < je && PreDupI16Shuffle[j] != -1)
9048             ++j;
9049
9050           if (j == je)
9051             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9052             return SDValue();
9053
9054           // Map this input with the i16 shuffle.
9055           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9056         }
9057
9058         // Update the lane map based on the mapping we ended up with.
9059         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9060       }
9061       V1 = DAG.getBitcast(
9062           MVT::v16i8,
9063           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9064                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9065
9066       // Unpack the bytes to form the i16s that will be shuffled into place.
9067       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9068                        MVT::v16i8, V1, V1);
9069
9070       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9071       for (int i = 0; i < 16; ++i)
9072         if (Mask[i] != -1) {
9073           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9074           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9075           if (PostDupI16Shuffle[i / 2] == -1)
9076             PostDupI16Shuffle[i / 2] = MappedMask;
9077           else
9078             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9079                    "Conflicting entrties in the original shuffle!");
9080         }
9081       return DAG.getBitcast(
9082           MVT::v16i8,
9083           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9084                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9085     };
9086     if (SDValue V = tryToWidenViaDuplication())
9087       return V;
9088   }
9089
9090   // Use dedicated unpack instructions for masks that match their pattern.
9091   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9092                                          0, 16, 1, 17, 2, 18, 3, 19,
9093                                          // High half.
9094                                          4, 20, 5, 21, 6, 22, 7, 23}))
9095     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9096   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9097                                          8, 24, 9, 25, 10, 26, 11, 27,
9098                                          // High half.
9099                                          12, 28, 13, 29, 14, 30, 15, 31}))
9100     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9101
9102   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9103   // with PSHUFB. It is important to do this before we attempt to generate any
9104   // blends but after all of the single-input lowerings. If the single input
9105   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9106   // want to preserve that and we can DAG combine any longer sequences into
9107   // a PSHUFB in the end. But once we start blending from multiple inputs,
9108   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9109   // and there are *very* few patterns that would actually be faster than the
9110   // PSHUFB approach because of its ability to zero lanes.
9111   //
9112   // FIXME: The only exceptions to the above are blends which are exact
9113   // interleavings with direct instructions supporting them. We currently don't
9114   // handle those well here.
9115   if (Subtarget->hasSSSE3()) {
9116     bool V1InUse = false;
9117     bool V2InUse = false;
9118
9119     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9120                                                 DAG, V1InUse, V2InUse);
9121
9122     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9123     // do so. This avoids using them to handle blends-with-zero which is
9124     // important as a single pshufb is significantly faster for that.
9125     if (V1InUse && V2InUse) {
9126       if (Subtarget->hasSSE41())
9127         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9128                                                       Mask, Subtarget, DAG))
9129           return Blend;
9130
9131       // We can use an unpack to do the blending rather than an or in some
9132       // cases. Even though the or may be (very minorly) more efficient, we
9133       // preference this lowering because there are common cases where part of
9134       // the complexity of the shuffles goes away when we do the final blend as
9135       // an unpack.
9136       // FIXME: It might be worth trying to detect if the unpack-feeding
9137       // shuffles will both be pshufb, in which case we shouldn't bother with
9138       // this.
9139       if (SDValue Unpack =
9140               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9141         return Unpack;
9142     }
9143
9144     return PSHUFB;
9145   }
9146
9147   // There are special ways we can lower some single-element blends.
9148   if (NumV2Elements == 1)
9149     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9150                                                          Mask, Subtarget, DAG))
9151       return V;
9152
9153   if (SDValue BitBlend =
9154           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9155     return BitBlend;
9156
9157   // Check whether a compaction lowering can be done. This handles shuffles
9158   // which take every Nth element for some even N. See the helper function for
9159   // details.
9160   //
9161   // We special case these as they can be particularly efficiently handled with
9162   // the PACKUSB instruction on x86 and they show up in common patterns of
9163   // rearranging bytes to truncate wide elements.
9164   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9165     // NumEvenDrops is the power of two stride of the elements. Another way of
9166     // thinking about it is that we need to drop the even elements this many
9167     // times to get the original input.
9168     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9169
9170     // First we need to zero all the dropped bytes.
9171     assert(NumEvenDrops <= 3 &&
9172            "No support for dropping even elements more than 3 times.");
9173     // We use the mask type to pick which bytes are preserved based on how many
9174     // elements are dropped.
9175     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9176     SDValue ByteClearMask = DAG.getBitcast(
9177         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9178     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9179     if (!IsSingleInput)
9180       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9181
9182     // Now pack things back together.
9183     V1 = DAG.getBitcast(MVT::v8i16, V1);
9184     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9185     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9186     for (int i = 1; i < NumEvenDrops; ++i) {
9187       Result = DAG.getBitcast(MVT::v8i16, Result);
9188       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9189     }
9190
9191     return Result;
9192   }
9193
9194   // Handle multi-input cases by blending single-input shuffles.
9195   if (NumV2Elements > 0)
9196     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9197                                                       Mask, DAG);
9198
9199   // The fallback path for single-input shuffles widens this into two v8i16
9200   // vectors with unpacks, shuffles those, and then pulls them back together
9201   // with a pack.
9202   SDValue V = V1;
9203
9204   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9205   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9206   for (int i = 0; i < 16; ++i)
9207     if (Mask[i] >= 0)
9208       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9209
9210   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9211
9212   SDValue VLoHalf, VHiHalf;
9213   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9214   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9215   // i16s.
9216   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9217                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9218       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9219                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9220     // Use a mask to drop the high bytes.
9221     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9222     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9223                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9224
9225     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9226     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9227
9228     // Squash the masks to point directly into VLoHalf.
9229     for (int &M : LoBlendMask)
9230       if (M >= 0)
9231         M /= 2;
9232     for (int &M : HiBlendMask)
9233       if (M >= 0)
9234         M /= 2;
9235   } else {
9236     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9237     // VHiHalf so that we can blend them as i16s.
9238     VLoHalf = DAG.getBitcast(
9239         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9240     VHiHalf = DAG.getBitcast(
9241         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9242   }
9243
9244   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9245   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9246
9247   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9248 }
9249
9250 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9251 ///
9252 /// This routine breaks down the specific type of 128-bit shuffle and
9253 /// dispatches to the lowering routines accordingly.
9254 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9255                                         MVT VT, const X86Subtarget *Subtarget,
9256                                         SelectionDAG &DAG) {
9257   switch (VT.SimpleTy) {
9258   case MVT::v2i64:
9259     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9260   case MVT::v2f64:
9261     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9262   case MVT::v4i32:
9263     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9264   case MVT::v4f32:
9265     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9266   case MVT::v8i16:
9267     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9268   case MVT::v16i8:
9269     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9270
9271   default:
9272     llvm_unreachable("Unimplemented!");
9273   }
9274 }
9275
9276 /// \brief Helper function to test whether a shuffle mask could be
9277 /// simplified by widening the elements being shuffled.
9278 ///
9279 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9280 /// leaves it in an unspecified state.
9281 ///
9282 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9283 /// shuffle masks. The latter have the special property of a '-2' representing
9284 /// a zero-ed lane of a vector.
9285 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9286                                     SmallVectorImpl<int> &WidenedMask) {
9287   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9288     // If both elements are undef, its trivial.
9289     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9290       WidenedMask.push_back(SM_SentinelUndef);
9291       continue;
9292     }
9293
9294     // Check for an undef mask and a mask value properly aligned to fit with
9295     // a pair of values. If we find such a case, use the non-undef mask's value.
9296     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9297       WidenedMask.push_back(Mask[i + 1] / 2);
9298       continue;
9299     }
9300     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9301       WidenedMask.push_back(Mask[i] / 2);
9302       continue;
9303     }
9304
9305     // When zeroing, we need to spread the zeroing across both lanes to widen.
9306     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9307       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9308           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9309         WidenedMask.push_back(SM_SentinelZero);
9310         continue;
9311       }
9312       return false;
9313     }
9314
9315     // Finally check if the two mask values are adjacent and aligned with
9316     // a pair.
9317     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9318       WidenedMask.push_back(Mask[i] / 2);
9319       continue;
9320     }
9321
9322     // Otherwise we can't safely widen the elements used in this shuffle.
9323     return false;
9324   }
9325   assert(WidenedMask.size() == Mask.size() / 2 &&
9326          "Incorrect size of mask after widening the elements!");
9327
9328   return true;
9329 }
9330
9331 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9332 ///
9333 /// This routine just extracts two subvectors, shuffles them independently, and
9334 /// then concatenates them back together. This should work effectively with all
9335 /// AVX vector shuffle types.
9336 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9337                                           SDValue V2, ArrayRef<int> Mask,
9338                                           SelectionDAG &DAG) {
9339   assert(VT.getSizeInBits() >= 256 &&
9340          "Only for 256-bit or wider vector shuffles!");
9341   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9342   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9343
9344   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9345   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9346
9347   int NumElements = VT.getVectorNumElements();
9348   int SplitNumElements = NumElements / 2;
9349   MVT ScalarVT = VT.getScalarType();
9350   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9351
9352   // Rather than splitting build-vectors, just build two narrower build
9353   // vectors. This helps shuffling with splats and zeros.
9354   auto SplitVector = [&](SDValue V) {
9355     while (V.getOpcode() == ISD::BITCAST)
9356       V = V->getOperand(0);
9357
9358     MVT OrigVT = V.getSimpleValueType();
9359     int OrigNumElements = OrigVT.getVectorNumElements();
9360     int OrigSplitNumElements = OrigNumElements / 2;
9361     MVT OrigScalarVT = OrigVT.getScalarType();
9362     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9363
9364     SDValue LoV, HiV;
9365
9366     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9367     if (!BV) {
9368       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9369                         DAG.getIntPtrConstant(0, DL));
9370       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9371                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9372     } else {
9373
9374       SmallVector<SDValue, 16> LoOps, HiOps;
9375       for (int i = 0; i < OrigSplitNumElements; ++i) {
9376         LoOps.push_back(BV->getOperand(i));
9377         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9378       }
9379       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9380       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9381     }
9382     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9383                           DAG.getBitcast(SplitVT, HiV));
9384   };
9385
9386   SDValue LoV1, HiV1, LoV2, HiV2;
9387   std::tie(LoV1, HiV1) = SplitVector(V1);
9388   std::tie(LoV2, HiV2) = SplitVector(V2);
9389
9390   // Now create two 4-way blends of these half-width vectors.
9391   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9392     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9393     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9394     for (int i = 0; i < SplitNumElements; ++i) {
9395       int M = HalfMask[i];
9396       if (M >= NumElements) {
9397         if (M >= NumElements + SplitNumElements)
9398           UseHiV2 = true;
9399         else
9400           UseLoV2 = true;
9401         V2BlendMask.push_back(M - NumElements);
9402         V1BlendMask.push_back(-1);
9403         BlendMask.push_back(SplitNumElements + i);
9404       } else if (M >= 0) {
9405         if (M >= SplitNumElements)
9406           UseHiV1 = true;
9407         else
9408           UseLoV1 = true;
9409         V2BlendMask.push_back(-1);
9410         V1BlendMask.push_back(M);
9411         BlendMask.push_back(i);
9412       } else {
9413         V2BlendMask.push_back(-1);
9414         V1BlendMask.push_back(-1);
9415         BlendMask.push_back(-1);
9416       }
9417     }
9418
9419     // Because the lowering happens after all combining takes place, we need to
9420     // manually combine these blend masks as much as possible so that we create
9421     // a minimal number of high-level vector shuffle nodes.
9422
9423     // First try just blending the halves of V1 or V2.
9424     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9425       return DAG.getUNDEF(SplitVT);
9426     if (!UseLoV2 && !UseHiV2)
9427       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9428     if (!UseLoV1 && !UseHiV1)
9429       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9430
9431     SDValue V1Blend, V2Blend;
9432     if (UseLoV1 && UseHiV1) {
9433       V1Blend =
9434         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9435     } else {
9436       // We only use half of V1 so map the usage down into the final blend mask.
9437       V1Blend = UseLoV1 ? LoV1 : HiV1;
9438       for (int i = 0; i < SplitNumElements; ++i)
9439         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9440           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9441     }
9442     if (UseLoV2 && UseHiV2) {
9443       V2Blend =
9444         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9445     } else {
9446       // We only use half of V2 so map the usage down into the final blend mask.
9447       V2Blend = UseLoV2 ? LoV2 : HiV2;
9448       for (int i = 0; i < SplitNumElements; ++i)
9449         if (BlendMask[i] >= SplitNumElements)
9450           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9451     }
9452     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9453   };
9454   SDValue Lo = HalfBlend(LoMask);
9455   SDValue Hi = HalfBlend(HiMask);
9456   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9457 }
9458
9459 /// \brief Either split a vector in halves or decompose the shuffles and the
9460 /// blend.
9461 ///
9462 /// This is provided as a good fallback for many lowerings of non-single-input
9463 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9464 /// between splitting the shuffle into 128-bit components and stitching those
9465 /// back together vs. extracting the single-input shuffles and blending those
9466 /// results.
9467 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9468                                                 SDValue V2, ArrayRef<int> Mask,
9469                                                 SelectionDAG &DAG) {
9470   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9471                                             "lower single-input shuffles as it "
9472                                             "could then recurse on itself.");
9473   int Size = Mask.size();
9474
9475   // If this can be modeled as a broadcast of two elements followed by a blend,
9476   // prefer that lowering. This is especially important because broadcasts can
9477   // often fold with memory operands.
9478   auto DoBothBroadcast = [&] {
9479     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9480     for (int M : Mask)
9481       if (M >= Size) {
9482         if (V2BroadcastIdx == -1)
9483           V2BroadcastIdx = M - Size;
9484         else if (M - Size != V2BroadcastIdx)
9485           return false;
9486       } else if (M >= 0) {
9487         if (V1BroadcastIdx == -1)
9488           V1BroadcastIdx = M;
9489         else if (M != V1BroadcastIdx)
9490           return false;
9491       }
9492     return true;
9493   };
9494   if (DoBothBroadcast())
9495     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9496                                                       DAG);
9497
9498   // If the inputs all stem from a single 128-bit lane of each input, then we
9499   // split them rather than blending because the split will decompose to
9500   // unusually few instructions.
9501   int LaneCount = VT.getSizeInBits() / 128;
9502   int LaneSize = Size / LaneCount;
9503   SmallBitVector LaneInputs[2];
9504   LaneInputs[0].resize(LaneCount, false);
9505   LaneInputs[1].resize(LaneCount, false);
9506   for (int i = 0; i < Size; ++i)
9507     if (Mask[i] >= 0)
9508       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9509   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9510     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9511
9512   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9513   // that the decomposed single-input shuffles don't end up here.
9514   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9515 }
9516
9517 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9518 /// a permutation and blend of those lanes.
9519 ///
9520 /// This essentially blends the out-of-lane inputs to each lane into the lane
9521 /// from a permuted copy of the vector. This lowering strategy results in four
9522 /// instructions in the worst case for a single-input cross lane shuffle which
9523 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9524 /// of. Special cases for each particular shuffle pattern should be handled
9525 /// prior to trying this lowering.
9526 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9527                                                        SDValue V1, SDValue V2,
9528                                                        ArrayRef<int> Mask,
9529                                                        SelectionDAG &DAG) {
9530   // FIXME: This should probably be generalized for 512-bit vectors as well.
9531   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9532   int LaneSize = Mask.size() / 2;
9533
9534   // If there are only inputs from one 128-bit lane, splitting will in fact be
9535   // less expensive. The flags track whether the given lane contains an element
9536   // that crosses to another lane.
9537   bool LaneCrossing[2] = {false, false};
9538   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9539     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9540       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9541   if (!LaneCrossing[0] || !LaneCrossing[1])
9542     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9543
9544   if (isSingleInputShuffleMask(Mask)) {
9545     SmallVector<int, 32> FlippedBlendMask;
9546     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9547       FlippedBlendMask.push_back(
9548           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9549                                   ? Mask[i]
9550                                   : Mask[i] % LaneSize +
9551                                         (i / LaneSize) * LaneSize + Size));
9552
9553     // Flip the vector, and blend the results which should now be in-lane. The
9554     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9555     // 5 for the high source. The value 3 selects the high half of source 2 and
9556     // the value 2 selects the low half of source 2. We only use source 2 to
9557     // allow folding it into a memory operand.
9558     unsigned PERMMask = 3 | 2 << 4;
9559     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9560                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9561     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9562   }
9563
9564   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9565   // will be handled by the above logic and a blend of the results, much like
9566   // other patterns in AVX.
9567   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9568 }
9569
9570 /// \brief Handle lowering 2-lane 128-bit shuffles.
9571 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9572                                         SDValue V2, ArrayRef<int> Mask,
9573                                         const X86Subtarget *Subtarget,
9574                                         SelectionDAG &DAG) {
9575   // TODO: If minimizing size and one of the inputs is a zero vector and the
9576   // the zero vector has only one use, we could use a VPERM2X128 to save the
9577   // instruction bytes needed to explicitly generate the zero vector.
9578
9579   // Blends are faster and handle all the non-lane-crossing cases.
9580   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9581                                                 Subtarget, DAG))
9582     return Blend;
9583
9584   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9585   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9586
9587   // If either input operand is a zero vector, use VPERM2X128 because its mask
9588   // allows us to replace the zero input with an implicit zero.
9589   if (!IsV1Zero && !IsV2Zero) {
9590     // Check for patterns which can be matched with a single insert of a 128-bit
9591     // subvector.
9592     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9593     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9594       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9595                                    VT.getVectorNumElements() / 2);
9596       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9597                                 DAG.getIntPtrConstant(0, DL));
9598       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9599                                 OnlyUsesV1 ? V1 : V2,
9600                                 DAG.getIntPtrConstant(0, DL));
9601       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9602     }
9603   }
9604
9605   // Otherwise form a 128-bit permutation. After accounting for undefs,
9606   // convert the 64-bit shuffle mask selection values into 128-bit
9607   // selection bits by dividing the indexes by 2 and shifting into positions
9608   // defined by a vperm2*128 instruction's immediate control byte.
9609
9610   // The immediate permute control byte looks like this:
9611   //    [1:0] - select 128 bits from sources for low half of destination
9612   //    [2]   - ignore
9613   //    [3]   - zero low half of destination
9614   //    [5:4] - select 128 bits from sources for high half of destination
9615   //    [6]   - ignore
9616   //    [7]   - zero high half of destination
9617
9618   int MaskLO = Mask[0];
9619   if (MaskLO == SM_SentinelUndef)
9620     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9621
9622   int MaskHI = Mask[2];
9623   if (MaskHI == SM_SentinelUndef)
9624     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9625
9626   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9627
9628   // If either input is a zero vector, replace it with an undef input.
9629   // Shuffle mask values <  4 are selecting elements of V1.
9630   // Shuffle mask values >= 4 are selecting elements of V2.
9631   // Adjust each half of the permute mask by clearing the half that was
9632   // selecting the zero vector and setting the zero mask bit.
9633   if (IsV1Zero) {
9634     V1 = DAG.getUNDEF(VT);
9635     if (MaskLO < 4)
9636       PermMask = (PermMask & 0xf0) | 0x08;
9637     if (MaskHI < 4)
9638       PermMask = (PermMask & 0x0f) | 0x80;
9639   }
9640   if (IsV2Zero) {
9641     V2 = DAG.getUNDEF(VT);
9642     if (MaskLO >= 4)
9643       PermMask = (PermMask & 0xf0) | 0x08;
9644     if (MaskHI >= 4)
9645       PermMask = (PermMask & 0x0f) | 0x80;
9646   }
9647
9648   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9649                      DAG.getConstant(PermMask, DL, MVT::i8));
9650 }
9651
9652 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9653 /// shuffling each lane.
9654 ///
9655 /// This will only succeed when the result of fixing the 128-bit lanes results
9656 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9657 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9658 /// the lane crosses early and then use simpler shuffles within each lane.
9659 ///
9660 /// FIXME: It might be worthwhile at some point to support this without
9661 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9662 /// in x86 only floating point has interesting non-repeating shuffles, and even
9663 /// those are still *marginally* more expensive.
9664 static SDValue lowerVectorShuffleByMerging128BitLanes(
9665     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9666     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9667   assert(!isSingleInputShuffleMask(Mask) &&
9668          "This is only useful with multiple inputs.");
9669
9670   int Size = Mask.size();
9671   int LaneSize = 128 / VT.getScalarSizeInBits();
9672   int NumLanes = Size / LaneSize;
9673   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9674
9675   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9676   // check whether the in-128-bit lane shuffles share a repeating pattern.
9677   SmallVector<int, 4> Lanes;
9678   Lanes.resize(NumLanes, -1);
9679   SmallVector<int, 4> InLaneMask;
9680   InLaneMask.resize(LaneSize, -1);
9681   for (int i = 0; i < Size; ++i) {
9682     if (Mask[i] < 0)
9683       continue;
9684
9685     int j = i / LaneSize;
9686
9687     if (Lanes[j] < 0) {
9688       // First entry we've seen for this lane.
9689       Lanes[j] = Mask[i] / LaneSize;
9690     } else if (Lanes[j] != Mask[i] / LaneSize) {
9691       // This doesn't match the lane selected previously!
9692       return SDValue();
9693     }
9694
9695     // Check that within each lane we have a consistent shuffle mask.
9696     int k = i % LaneSize;
9697     if (InLaneMask[k] < 0) {
9698       InLaneMask[k] = Mask[i] % LaneSize;
9699     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9700       // This doesn't fit a repeating in-lane mask.
9701       return SDValue();
9702     }
9703   }
9704
9705   // First shuffle the lanes into place.
9706   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9707                                 VT.getSizeInBits() / 64);
9708   SmallVector<int, 8> LaneMask;
9709   LaneMask.resize(NumLanes * 2, -1);
9710   for (int i = 0; i < NumLanes; ++i)
9711     if (Lanes[i] >= 0) {
9712       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9713       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9714     }
9715
9716   V1 = DAG.getBitcast(LaneVT, V1);
9717   V2 = DAG.getBitcast(LaneVT, V2);
9718   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9719
9720   // Cast it back to the type we actually want.
9721   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9722
9723   // Now do a simple shuffle that isn't lane crossing.
9724   SmallVector<int, 8> NewMask;
9725   NewMask.resize(Size, -1);
9726   for (int i = 0; i < Size; ++i)
9727     if (Mask[i] >= 0)
9728       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9729   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9730          "Must not introduce lane crosses at this point!");
9731
9732   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9733 }
9734
9735 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9736 /// given mask.
9737 ///
9738 /// This returns true if the elements from a particular input are already in the
9739 /// slot required by the given mask and require no permutation.
9740 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9741   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9742   int Size = Mask.size();
9743   for (int i = 0; i < Size; ++i)
9744     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9745       return false;
9746
9747   return true;
9748 }
9749
9750 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9751                                             ArrayRef<int> Mask, SDValue V1,
9752                                             SDValue V2, SelectionDAG &DAG) {
9753
9754   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9755   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9756   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9757   int NumElts = VT.getVectorNumElements();
9758   bool ShufpdMask = true;
9759   bool CommutableMask = true;
9760   unsigned Immediate = 0;
9761   for (int i = 0; i < NumElts; ++i) {
9762     if (Mask[i] < 0)
9763       continue;
9764     int Val = (i & 6) + NumElts * (i & 1);
9765     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9766     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9767       ShufpdMask = false;
9768     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9769       CommutableMask = false;
9770     Immediate |= (Mask[i] % 2) << i;
9771   }
9772   if (ShufpdMask)
9773     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9774                        DAG.getConstant(Immediate, DL, MVT::i8));
9775   if (CommutableMask)
9776     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9777                        DAG.getConstant(Immediate, DL, MVT::i8));
9778   return SDValue();
9779 }
9780
9781 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9782 ///
9783 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9784 /// isn't available.
9785 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9786                                        const X86Subtarget *Subtarget,
9787                                        SelectionDAG &DAG) {
9788   SDLoc DL(Op);
9789   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9790   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9791   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9792   ArrayRef<int> Mask = SVOp->getMask();
9793   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9794
9795   SmallVector<int, 4> WidenedMask;
9796   if (canWidenShuffleElements(Mask, WidenedMask))
9797     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9798                                     DAG);
9799
9800   if (isSingleInputShuffleMask(Mask)) {
9801     // Check for being able to broadcast a single element.
9802     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9803                                                           Mask, Subtarget, DAG))
9804       return Broadcast;
9805
9806     // Use low duplicate instructions for masks that match their pattern.
9807     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9808       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9809
9810     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9811       // Non-half-crossing single input shuffles can be lowerid with an
9812       // interleaved permutation.
9813       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9814                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9815       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9816                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9817     }
9818
9819     // With AVX2 we have direct support for this permutation.
9820     if (Subtarget->hasAVX2())
9821       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9822                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9823
9824     // Otherwise, fall back.
9825     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9826                                                    DAG);
9827   }
9828
9829   // X86 has dedicated unpack instructions that can handle specific blend
9830   // operations: UNPCKH and UNPCKL.
9831   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9832     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9833   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9834     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9835   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9836     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9837   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9838     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9839
9840   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9841                                                 Subtarget, DAG))
9842     return Blend;
9843
9844   // Check if the blend happens to exactly fit that of SHUFPD.
9845   if (SDValue Op =
9846       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9847     return Op;
9848
9849   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9850   // shuffle. However, if we have AVX2 and either inputs are already in place,
9851   // we will be able to shuffle even across lanes the other input in a single
9852   // instruction so skip this pattern.
9853   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9854                                  isShuffleMaskInputInPlace(1, Mask))))
9855     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9856             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9857       return Result;
9858
9859   // If we have AVX2 then we always want to lower with a blend because an v4 we
9860   // can fully permute the elements.
9861   if (Subtarget->hasAVX2())
9862     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9863                                                       Mask, DAG);
9864
9865   // Otherwise fall back on generic lowering.
9866   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9867 }
9868
9869 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9870 ///
9871 /// This routine is only called when we have AVX2 and thus a reasonable
9872 /// instruction set for v4i64 shuffling..
9873 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9874                                        const X86Subtarget *Subtarget,
9875                                        SelectionDAG &DAG) {
9876   SDLoc DL(Op);
9877   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9878   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9879   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9880   ArrayRef<int> Mask = SVOp->getMask();
9881   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9882   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9883
9884   SmallVector<int, 4> WidenedMask;
9885   if (canWidenShuffleElements(Mask, WidenedMask))
9886     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9887                                     DAG);
9888
9889   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9890                                                 Subtarget, DAG))
9891     return Blend;
9892
9893   // Check for being able to broadcast a single element.
9894   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9895                                                         Mask, Subtarget, DAG))
9896     return Broadcast;
9897
9898   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9899   // use lower latency instructions that will operate on both 128-bit lanes.
9900   SmallVector<int, 2> RepeatedMask;
9901   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9902     if (isSingleInputShuffleMask(Mask)) {
9903       int PSHUFDMask[] = {-1, -1, -1, -1};
9904       for (int i = 0; i < 2; ++i)
9905         if (RepeatedMask[i] >= 0) {
9906           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9907           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9908         }
9909       return DAG.getBitcast(
9910           MVT::v4i64,
9911           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9912                       DAG.getBitcast(MVT::v8i32, V1),
9913                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9914     }
9915   }
9916
9917   // AVX2 provides a direct instruction for permuting a single input across
9918   // lanes.
9919   if (isSingleInputShuffleMask(Mask))
9920     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9921                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9922
9923   // Try to use shift instructions.
9924   if (SDValue Shift =
9925           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9926     return Shift;
9927
9928   // Use dedicated unpack instructions for masks that match their pattern.
9929   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9930     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9931   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9932     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9933   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9934     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9935   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9936     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9937
9938   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9939   // shuffle. However, if we have AVX2 and either inputs are already in place,
9940   // we will be able to shuffle even across lanes the other input in a single
9941   // instruction so skip this pattern.
9942   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9943                                  isShuffleMaskInputInPlace(1, Mask))))
9944     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9945             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9946       return Result;
9947
9948   // Otherwise fall back on generic blend lowering.
9949   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9950                                                     Mask, DAG);
9951 }
9952
9953 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9954 ///
9955 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9956 /// isn't available.
9957 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9958                                        const X86Subtarget *Subtarget,
9959                                        SelectionDAG &DAG) {
9960   SDLoc DL(Op);
9961   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9962   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9963   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9964   ArrayRef<int> Mask = SVOp->getMask();
9965   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9966
9967   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9968                                                 Subtarget, DAG))
9969     return Blend;
9970
9971   // Check for being able to broadcast a single element.
9972   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9973                                                         Mask, Subtarget, DAG))
9974     return Broadcast;
9975
9976   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9977   // options to efficiently lower the shuffle.
9978   SmallVector<int, 4> RepeatedMask;
9979   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9980     assert(RepeatedMask.size() == 4 &&
9981            "Repeated masks must be half the mask width!");
9982
9983     // Use even/odd duplicate instructions for masks that match their pattern.
9984     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9985       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9986     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9987       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9988
9989     if (isSingleInputShuffleMask(Mask))
9990       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9991                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9992
9993     // Use dedicated unpack instructions for masks that match their pattern.
9994     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9995       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9996     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9997       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9998     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9999       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
10000     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10001       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
10002
10003     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
10004     // have already handled any direct blends. We also need to squash the
10005     // repeated mask into a simulated v4f32 mask.
10006     for (int i = 0; i < 4; ++i)
10007       if (RepeatedMask[i] >= 8)
10008         RepeatedMask[i] -= 4;
10009     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
10010   }
10011
10012   // If we have a single input shuffle with different shuffle patterns in the
10013   // two 128-bit lanes use the variable mask to VPERMILPS.
10014   if (isSingleInputShuffleMask(Mask)) {
10015     SDValue VPermMask[8];
10016     for (int i = 0; i < 8; ++i)
10017       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10018                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10019     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
10020       return DAG.getNode(
10021           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
10022           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
10023
10024     if (Subtarget->hasAVX2())
10025       return DAG.getNode(
10026           X86ISD::VPERMV, DL, MVT::v8f32,
10027           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10028                                                  MVT::v8i32, VPermMask)),
10029           V1);
10030
10031     // Otherwise, fall back.
10032     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10033                                                    DAG);
10034   }
10035
10036   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10037   // shuffle.
10038   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10039           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10040     return Result;
10041
10042   // If we have AVX2 then we always want to lower with a blend because at v8 we
10043   // can fully permute the elements.
10044   if (Subtarget->hasAVX2())
10045     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10046                                                       Mask, DAG);
10047
10048   // Otherwise fall back on generic lowering.
10049   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10050 }
10051
10052 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10053 ///
10054 /// This routine is only called when we have AVX2 and thus a reasonable
10055 /// instruction set for v8i32 shuffling..
10056 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10057                                        const X86Subtarget *Subtarget,
10058                                        SelectionDAG &DAG) {
10059   SDLoc DL(Op);
10060   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10061   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10062   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10063   ArrayRef<int> Mask = SVOp->getMask();
10064   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10065   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10066
10067   // Whenever we can lower this as a zext, that instruction is strictly faster
10068   // than any alternative. It also allows us to fold memory operands into the
10069   // shuffle in many cases.
10070   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10071                                                          Mask, Subtarget, DAG))
10072     return ZExt;
10073
10074   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10075                                                 Subtarget, DAG))
10076     return Blend;
10077
10078   // Check for being able to broadcast a single element.
10079   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10080                                                         Mask, Subtarget, DAG))
10081     return Broadcast;
10082
10083   // If the shuffle mask is repeated in each 128-bit lane we can use more
10084   // efficient instructions that mirror the shuffles across the two 128-bit
10085   // lanes.
10086   SmallVector<int, 4> RepeatedMask;
10087   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10088     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10089     if (isSingleInputShuffleMask(Mask))
10090       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10091                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10092
10093     // Use dedicated unpack instructions for masks that match their pattern.
10094     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10095       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10096     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10097       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10098     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10099       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10100     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10101       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10102   }
10103
10104   // Try to use shift instructions.
10105   if (SDValue Shift =
10106           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10107     return Shift;
10108
10109   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10110           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10111     return Rotate;
10112
10113   // If the shuffle patterns aren't repeated but it is a single input, directly
10114   // generate a cross-lane VPERMD instruction.
10115   if (isSingleInputShuffleMask(Mask)) {
10116     SDValue VPermMask[8];
10117     for (int i = 0; i < 8; ++i)
10118       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10119                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10120     return DAG.getNode(
10121         X86ISD::VPERMV, DL, MVT::v8i32,
10122         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10123   }
10124
10125   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10126   // shuffle.
10127   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10128           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10129     return Result;
10130
10131   // Otherwise fall back on generic blend lowering.
10132   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10133                                                     Mask, DAG);
10134 }
10135
10136 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10137 ///
10138 /// This routine is only called when we have AVX2 and thus a reasonable
10139 /// instruction set for v16i16 shuffling..
10140 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10141                                         const X86Subtarget *Subtarget,
10142                                         SelectionDAG &DAG) {
10143   SDLoc DL(Op);
10144   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10145   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10146   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10147   ArrayRef<int> Mask = SVOp->getMask();
10148   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10149   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10150
10151   // Whenever we can lower this as a zext, that instruction is strictly faster
10152   // than any alternative. It also allows us to fold memory operands into the
10153   // shuffle in many cases.
10154   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10155                                                          Mask, Subtarget, DAG))
10156     return ZExt;
10157
10158   // Check for being able to broadcast a single element.
10159   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10160                                                         Mask, Subtarget, DAG))
10161     return Broadcast;
10162
10163   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10164                                                 Subtarget, DAG))
10165     return Blend;
10166
10167   // Use dedicated unpack instructions for masks that match their pattern.
10168   if (isShuffleEquivalent(V1, V2, Mask,
10169                           {// First 128-bit lane:
10170                            0, 16, 1, 17, 2, 18, 3, 19,
10171                            // Second 128-bit lane:
10172                            8, 24, 9, 25, 10, 26, 11, 27}))
10173     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10174   if (isShuffleEquivalent(V1, V2, Mask,
10175                           {// First 128-bit lane:
10176                            4, 20, 5, 21, 6, 22, 7, 23,
10177                            // Second 128-bit lane:
10178                            12, 28, 13, 29, 14, 30, 15, 31}))
10179     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10180
10181   // Try to use shift instructions.
10182   if (SDValue Shift =
10183           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10184     return Shift;
10185
10186   // Try to use byte rotation instructions.
10187   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10188           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10189     return Rotate;
10190
10191   if (isSingleInputShuffleMask(Mask)) {
10192     // There are no generalized cross-lane shuffle operations available on i16
10193     // element types.
10194     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10195       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10196                                                      Mask, DAG);
10197
10198     SmallVector<int, 8> RepeatedMask;
10199     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10200       // As this is a single-input shuffle, the repeated mask should be
10201       // a strictly valid v8i16 mask that we can pass through to the v8i16
10202       // lowering to handle even the v16 case.
10203       return lowerV8I16GeneralSingleInputVectorShuffle(
10204           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10205     }
10206
10207     SDValue PSHUFBMask[32];
10208     for (int i = 0; i < 16; ++i) {
10209       if (Mask[i] == -1) {
10210         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10211         continue;
10212       }
10213
10214       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10215       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10216       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10217       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10218     }
10219     return DAG.getBitcast(MVT::v16i16,
10220                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10221                                       DAG.getBitcast(MVT::v32i8, V1),
10222                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10223                                                   MVT::v32i8, PSHUFBMask)));
10224   }
10225
10226   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10227   // shuffle.
10228   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10229           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10230     return Result;
10231
10232   // Otherwise fall back on generic lowering.
10233   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10234 }
10235
10236 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10237 ///
10238 /// This routine is only called when we have AVX2 and thus a reasonable
10239 /// instruction set for v32i8 shuffling..
10240 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10241                                        const X86Subtarget *Subtarget,
10242                                        SelectionDAG &DAG) {
10243   SDLoc DL(Op);
10244   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10245   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10247   ArrayRef<int> Mask = SVOp->getMask();
10248   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10249   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10250
10251   // Whenever we can lower this as a zext, that instruction is strictly faster
10252   // than any alternative. It also allows us to fold memory operands into the
10253   // shuffle in many cases.
10254   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10255                                                          Mask, Subtarget, DAG))
10256     return ZExt;
10257
10258   // Check for being able to broadcast a single element.
10259   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10260                                                         Mask, Subtarget, DAG))
10261     return Broadcast;
10262
10263   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10264                                                 Subtarget, DAG))
10265     return Blend;
10266
10267   // Use dedicated unpack instructions for masks that match their pattern.
10268   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10269   // 256-bit lanes.
10270   if (isShuffleEquivalent(
10271           V1, V2, Mask,
10272           {// First 128-bit lane:
10273            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10274            // Second 128-bit lane:
10275            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10276     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10277   if (isShuffleEquivalent(
10278           V1, V2, Mask,
10279           {// First 128-bit lane:
10280            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10281            // Second 128-bit lane:
10282            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10283     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10284
10285   // Try to use shift instructions.
10286   if (SDValue Shift =
10287           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10288     return Shift;
10289
10290   // Try to use byte rotation instructions.
10291   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10292           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10293     return Rotate;
10294
10295   if (isSingleInputShuffleMask(Mask)) {
10296     // There are no generalized cross-lane shuffle operations available on i8
10297     // element types.
10298     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10299       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10300                                                      Mask, DAG);
10301
10302     SDValue PSHUFBMask[32];
10303     for (int i = 0; i < 32; ++i)
10304       PSHUFBMask[i] =
10305           Mask[i] < 0
10306               ? DAG.getUNDEF(MVT::i8)
10307               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10308                                 MVT::i8);
10309
10310     return DAG.getNode(
10311         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10312         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10313   }
10314
10315   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10316   // shuffle.
10317   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10318           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10319     return Result;
10320
10321   // Otherwise fall back on generic lowering.
10322   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10323 }
10324
10325 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10326 ///
10327 /// This routine either breaks down the specific type of a 256-bit x86 vector
10328 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10329 /// together based on the available instructions.
10330 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10331                                         MVT VT, const X86Subtarget *Subtarget,
10332                                         SelectionDAG &DAG) {
10333   SDLoc DL(Op);
10334   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10335   ArrayRef<int> Mask = SVOp->getMask();
10336
10337   // If we have a single input to the zero element, insert that into V1 if we
10338   // can do so cheaply.
10339   int NumElts = VT.getVectorNumElements();
10340   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10341     return M >= NumElts;
10342   });
10343
10344   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10345     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10346                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10347       return Insertion;
10348
10349   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10350   // check for those subtargets here and avoid much of the subtarget querying in
10351   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10352   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10353   // floating point types there eventually, just immediately cast everything to
10354   // a float and operate entirely in that domain.
10355   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10356     int ElementBits = VT.getScalarSizeInBits();
10357     if (ElementBits < 32)
10358       // No floating point type available, decompose into 128-bit vectors.
10359       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10360
10361     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10362                                 VT.getVectorNumElements());
10363     V1 = DAG.getBitcast(FpVT, V1);
10364     V2 = DAG.getBitcast(FpVT, V2);
10365     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10366   }
10367
10368   switch (VT.SimpleTy) {
10369   case MVT::v4f64:
10370     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10371   case MVT::v4i64:
10372     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10373   case MVT::v8f32:
10374     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10375   case MVT::v8i32:
10376     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10377   case MVT::v16i16:
10378     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10379   case MVT::v32i8:
10380     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10381
10382   default:
10383     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10384   }
10385 }
10386
10387 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10388 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10389                                        const X86Subtarget *Subtarget,
10390                                        SelectionDAG &DAG) {
10391   SDLoc DL(Op);
10392   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10393   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10394   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10395   ArrayRef<int> Mask = SVOp->getMask();
10396   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10397
10398   // X86 has dedicated unpack instructions that can handle specific blend
10399   // operations: UNPCKH and UNPCKL.
10400   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10401     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10402   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10403     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10404
10405   // FIXME: Implement direct support for this type!
10406   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10407 }
10408
10409 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10410 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10411                                        const X86Subtarget *Subtarget,
10412                                        SelectionDAG &DAG) {
10413   SDLoc DL(Op);
10414   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10415   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10416   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10417   ArrayRef<int> Mask = SVOp->getMask();
10418   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10419
10420   // Use dedicated unpack instructions for masks that match their pattern.
10421   if (isShuffleEquivalent(V1, V2, Mask,
10422                           {// First 128-bit lane.
10423                            0, 16, 1, 17, 4, 20, 5, 21,
10424                            // Second 128-bit lane.
10425                            8, 24, 9, 25, 12, 28, 13, 29}))
10426     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10427   if (isShuffleEquivalent(V1, V2, Mask,
10428                           {// First 128-bit lane.
10429                            2, 18, 3, 19, 6, 22, 7, 23,
10430                            // Second 128-bit lane.
10431                            10, 26, 11, 27, 14, 30, 15, 31}))
10432     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10433
10434   // FIXME: Implement direct support for this type!
10435   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10436 }
10437
10438 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10439 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10440                                        const X86Subtarget *Subtarget,
10441                                        SelectionDAG &DAG) {
10442   SDLoc DL(Op);
10443   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10444   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10445   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10446   ArrayRef<int> Mask = SVOp->getMask();
10447   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10448
10449   // X86 has dedicated unpack instructions that can handle specific blend
10450   // operations: UNPCKH and UNPCKL.
10451   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10452     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10453   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10454     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10455
10456   // FIXME: Implement direct support for this type!
10457   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10458 }
10459
10460 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10461 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10462                                        const X86Subtarget *Subtarget,
10463                                        SelectionDAG &DAG) {
10464   SDLoc DL(Op);
10465   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10466   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10467   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10468   ArrayRef<int> Mask = SVOp->getMask();
10469   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10470
10471   // Use dedicated unpack instructions for masks that match their pattern.
10472   if (isShuffleEquivalent(V1, V2, Mask,
10473                           {// First 128-bit lane.
10474                            0, 16, 1, 17, 4, 20, 5, 21,
10475                            // Second 128-bit lane.
10476                            8, 24, 9, 25, 12, 28, 13, 29}))
10477     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10478   if (isShuffleEquivalent(V1, V2, Mask,
10479                           {// First 128-bit lane.
10480                            2, 18, 3, 19, 6, 22, 7, 23,
10481                            // Second 128-bit lane.
10482                            10, 26, 11, 27, 14, 30, 15, 31}))
10483     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10484
10485   // FIXME: Implement direct support for this type!
10486   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10487 }
10488
10489 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10490 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10491                                         const X86Subtarget *Subtarget,
10492                                         SelectionDAG &DAG) {
10493   SDLoc DL(Op);
10494   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10495   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10496   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10497   ArrayRef<int> Mask = SVOp->getMask();
10498   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10499   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10500
10501   // FIXME: Implement direct support for this type!
10502   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10503 }
10504
10505 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10506 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10507                                        const X86Subtarget *Subtarget,
10508                                        SelectionDAG &DAG) {
10509   SDLoc DL(Op);
10510   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10511   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10512   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10513   ArrayRef<int> Mask = SVOp->getMask();
10514   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10515   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10516
10517   // FIXME: Implement direct support for this type!
10518   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10519 }
10520
10521 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10522 ///
10523 /// This routine either breaks down the specific type of a 512-bit x86 vector
10524 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10525 /// together based on the available instructions.
10526 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10527                                         MVT VT, const X86Subtarget *Subtarget,
10528                                         SelectionDAG &DAG) {
10529   SDLoc DL(Op);
10530   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10531   ArrayRef<int> Mask = SVOp->getMask();
10532   assert(Subtarget->hasAVX512() &&
10533          "Cannot lower 512-bit vectors w/ basic ISA!");
10534
10535   // Check for being able to broadcast a single element.
10536   if (SDValue Broadcast =
10537           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10538     return Broadcast;
10539
10540   // Dispatch to each element type for lowering. If we don't have supprot for
10541   // specific element type shuffles at 512 bits, immediately split them and
10542   // lower them. Each lowering routine of a given type is allowed to assume that
10543   // the requisite ISA extensions for that element type are available.
10544   switch (VT.SimpleTy) {
10545   case MVT::v8f64:
10546     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10547   case MVT::v16f32:
10548     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10549   case MVT::v8i64:
10550     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10551   case MVT::v16i32:
10552     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10553   case MVT::v32i16:
10554     if (Subtarget->hasBWI())
10555       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10556     break;
10557   case MVT::v64i8:
10558     if (Subtarget->hasBWI())
10559       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10560     break;
10561
10562   default:
10563     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10564   }
10565
10566   // Otherwise fall back on splitting.
10567   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10568 }
10569
10570 /// \brief Top-level lowering for x86 vector shuffles.
10571 ///
10572 /// This handles decomposition, canonicalization, and lowering of all x86
10573 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10574 /// above in helper routines. The canonicalization attempts to widen shuffles
10575 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10576 /// s.t. only one of the two inputs needs to be tested, etc.
10577 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10578                                   SelectionDAG &DAG) {
10579   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10580   ArrayRef<int> Mask = SVOp->getMask();
10581   SDValue V1 = Op.getOperand(0);
10582   SDValue V2 = Op.getOperand(1);
10583   MVT VT = Op.getSimpleValueType();
10584   int NumElements = VT.getVectorNumElements();
10585   SDLoc dl(Op);
10586
10587   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10588
10589   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10590   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10591   if (V1IsUndef && V2IsUndef)
10592     return DAG.getUNDEF(VT);
10593
10594   // When we create a shuffle node we put the UNDEF node to second operand,
10595   // but in some cases the first operand may be transformed to UNDEF.
10596   // In this case we should just commute the node.
10597   if (V1IsUndef)
10598     return DAG.getCommutedVectorShuffle(*SVOp);
10599
10600   // Check for non-undef masks pointing at an undef vector and make the masks
10601   // undef as well. This makes it easier to match the shuffle based solely on
10602   // the mask.
10603   if (V2IsUndef)
10604     for (int M : Mask)
10605       if (M >= NumElements) {
10606         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10607         for (int &M : NewMask)
10608           if (M >= NumElements)
10609             M = -1;
10610         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10611       }
10612
10613   // We actually see shuffles that are entirely re-arrangements of a set of
10614   // zero inputs. This mostly happens while decomposing complex shuffles into
10615   // simple ones. Directly lower these as a buildvector of zeros.
10616   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10617   if (Zeroable.all())
10618     return getZeroVector(VT, Subtarget, DAG, dl);
10619
10620   // Try to collapse shuffles into using a vector type with fewer elements but
10621   // wider element types. We cap this to not form integers or floating point
10622   // elements wider than 64 bits, but it might be interesting to form i128
10623   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10624   SmallVector<int, 16> WidenedMask;
10625   if (VT.getScalarSizeInBits() < 64 &&
10626       canWidenShuffleElements(Mask, WidenedMask)) {
10627     MVT NewEltVT = VT.isFloatingPoint()
10628                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10629                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10630     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10631     // Make sure that the new vector type is legal. For example, v2f64 isn't
10632     // legal on SSE1.
10633     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10634       V1 = DAG.getBitcast(NewVT, V1);
10635       V2 = DAG.getBitcast(NewVT, V2);
10636       return DAG.getBitcast(
10637           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10638     }
10639   }
10640
10641   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10642   for (int M : SVOp->getMask())
10643     if (M < 0)
10644       ++NumUndefElements;
10645     else if (M < NumElements)
10646       ++NumV1Elements;
10647     else
10648       ++NumV2Elements;
10649
10650   // Commute the shuffle as needed such that more elements come from V1 than
10651   // V2. This allows us to match the shuffle pattern strictly on how many
10652   // elements come from V1 without handling the symmetric cases.
10653   if (NumV2Elements > NumV1Elements)
10654     return DAG.getCommutedVectorShuffle(*SVOp);
10655
10656   // When the number of V1 and V2 elements are the same, try to minimize the
10657   // number of uses of V2 in the low half of the vector. When that is tied,
10658   // ensure that the sum of indices for V1 is equal to or lower than the sum
10659   // indices for V2. When those are equal, try to ensure that the number of odd
10660   // indices for V1 is lower than the number of odd indices for V2.
10661   if (NumV1Elements == NumV2Elements) {
10662     int LowV1Elements = 0, LowV2Elements = 0;
10663     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10664       if (M >= NumElements)
10665         ++LowV2Elements;
10666       else if (M >= 0)
10667         ++LowV1Elements;
10668     if (LowV2Elements > LowV1Elements) {
10669       return DAG.getCommutedVectorShuffle(*SVOp);
10670     } else if (LowV2Elements == LowV1Elements) {
10671       int SumV1Indices = 0, SumV2Indices = 0;
10672       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10673         if (SVOp->getMask()[i] >= NumElements)
10674           SumV2Indices += i;
10675         else if (SVOp->getMask()[i] >= 0)
10676           SumV1Indices += i;
10677       if (SumV2Indices < SumV1Indices) {
10678         return DAG.getCommutedVectorShuffle(*SVOp);
10679       } else if (SumV2Indices == SumV1Indices) {
10680         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10681         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10682           if (SVOp->getMask()[i] >= NumElements)
10683             NumV2OddIndices += i % 2;
10684           else if (SVOp->getMask()[i] >= 0)
10685             NumV1OddIndices += i % 2;
10686         if (NumV2OddIndices < NumV1OddIndices)
10687           return DAG.getCommutedVectorShuffle(*SVOp);
10688       }
10689     }
10690   }
10691
10692   // For each vector width, delegate to a specialized lowering routine.
10693   if (VT.getSizeInBits() == 128)
10694     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10695
10696   if (VT.getSizeInBits() == 256)
10697     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10698
10699   // Force AVX-512 vectors to be scalarized for now.
10700   // FIXME: Implement AVX-512 support!
10701   if (VT.getSizeInBits() == 512)
10702     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10703
10704   llvm_unreachable("Unimplemented!");
10705 }
10706
10707 // This function assumes its argument is a BUILD_VECTOR of constants or
10708 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10709 // true.
10710 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10711                                     unsigned &MaskValue) {
10712   MaskValue = 0;
10713   unsigned NumElems = BuildVector->getNumOperands();
10714   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10715   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10716   unsigned NumElemsInLane = NumElems / NumLanes;
10717
10718   // Blend for v16i16 should be symetric for the both lanes.
10719   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10720     SDValue EltCond = BuildVector->getOperand(i);
10721     SDValue SndLaneEltCond =
10722         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10723
10724     int Lane1Cond = -1, Lane2Cond = -1;
10725     if (isa<ConstantSDNode>(EltCond))
10726       Lane1Cond = !isZero(EltCond);
10727     if (isa<ConstantSDNode>(SndLaneEltCond))
10728       Lane2Cond = !isZero(SndLaneEltCond);
10729
10730     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10731       // Lane1Cond != 0, means we want the first argument.
10732       // Lane1Cond == 0, means we want the second argument.
10733       // The encoding of this argument is 0 for the first argument, 1
10734       // for the second. Therefore, invert the condition.
10735       MaskValue |= !Lane1Cond << i;
10736     else if (Lane1Cond < 0)
10737       MaskValue |= !Lane2Cond << i;
10738     else
10739       return false;
10740   }
10741   return true;
10742 }
10743
10744 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10745 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10746                                            const X86Subtarget *Subtarget,
10747                                            SelectionDAG &DAG) {
10748   SDValue Cond = Op.getOperand(0);
10749   SDValue LHS = Op.getOperand(1);
10750   SDValue RHS = Op.getOperand(2);
10751   SDLoc dl(Op);
10752   MVT VT = Op.getSimpleValueType();
10753
10754   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10755     return SDValue();
10756   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10757
10758   // Only non-legal VSELECTs reach this lowering, convert those into generic
10759   // shuffles and re-use the shuffle lowering path for blends.
10760   SmallVector<int, 32> Mask;
10761   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10762     SDValue CondElt = CondBV->getOperand(i);
10763     Mask.push_back(
10764         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10765   }
10766   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10767 }
10768
10769 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10770   // A vselect where all conditions and data are constants can be optimized into
10771   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10772   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10773       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10774       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10775     return SDValue();
10776
10777   // Try to lower this to a blend-style vector shuffle. This can handle all
10778   // constant condition cases.
10779   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10780     return BlendOp;
10781
10782   // Variable blends are only legal from SSE4.1 onward.
10783   if (!Subtarget->hasSSE41())
10784     return SDValue();
10785
10786   // Only some types will be legal on some subtargets. If we can emit a legal
10787   // VSELECT-matching blend, return Op, and but if we need to expand, return
10788   // a null value.
10789   switch (Op.getSimpleValueType().SimpleTy) {
10790   default:
10791     // Most of the vector types have blends past SSE4.1.
10792     return Op;
10793
10794   case MVT::v32i8:
10795     // The byte blends for AVX vectors were introduced only in AVX2.
10796     if (Subtarget->hasAVX2())
10797       return Op;
10798
10799     return SDValue();
10800
10801   case MVT::v8i16:
10802   case MVT::v16i16:
10803     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10804     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10805       return Op;
10806
10807     // FIXME: We should custom lower this by fixing the condition and using i8
10808     // blends.
10809     return SDValue();
10810   }
10811 }
10812
10813 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10814   MVT VT = Op.getSimpleValueType();
10815   SDLoc dl(Op);
10816
10817   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10818     return SDValue();
10819
10820   if (VT.getSizeInBits() == 8) {
10821     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10822                                   Op.getOperand(0), Op.getOperand(1));
10823     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10824                                   DAG.getValueType(VT));
10825     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10826   }
10827
10828   if (VT.getSizeInBits() == 16) {
10829     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10830     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10831     if (Idx == 0)
10832       return DAG.getNode(
10833           ISD::TRUNCATE, dl, MVT::i16,
10834           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10835                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10836                       Op.getOperand(1)));
10837     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10838                                   Op.getOperand(0), Op.getOperand(1));
10839     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10840                                   DAG.getValueType(VT));
10841     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10842   }
10843
10844   if (VT == MVT::f32) {
10845     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10846     // the result back to FR32 register. It's only worth matching if the
10847     // result has a single use which is a store or a bitcast to i32.  And in
10848     // the case of a store, it's not worth it if the index is a constant 0,
10849     // because a MOVSSmr can be used instead, which is smaller and faster.
10850     if (!Op.hasOneUse())
10851       return SDValue();
10852     SDNode *User = *Op.getNode()->use_begin();
10853     if ((User->getOpcode() != ISD::STORE ||
10854          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10855           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10856         (User->getOpcode() != ISD::BITCAST ||
10857          User->getValueType(0) != MVT::i32))
10858       return SDValue();
10859     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10860                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10861                                   Op.getOperand(1));
10862     return DAG.getBitcast(MVT::f32, Extract);
10863   }
10864
10865   if (VT == MVT::i32 || VT == MVT::i64) {
10866     // ExtractPS/pextrq works with constant index.
10867     if (isa<ConstantSDNode>(Op.getOperand(1)))
10868       return Op;
10869   }
10870   return SDValue();
10871 }
10872
10873 /// Extract one bit from mask vector, like v16i1 or v8i1.
10874 /// AVX-512 feature.
10875 SDValue
10876 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10877   SDValue Vec = Op.getOperand(0);
10878   SDLoc dl(Vec);
10879   MVT VecVT = Vec.getSimpleValueType();
10880   SDValue Idx = Op.getOperand(1);
10881   MVT EltVT = Op.getSimpleValueType();
10882
10883   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10884   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10885          "Unexpected vector type in ExtractBitFromMaskVector");
10886
10887   // variable index can't be handled in mask registers,
10888   // extend vector to VR512
10889   if (!isa<ConstantSDNode>(Idx)) {
10890     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10891     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10892     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10893                               ExtVT.getVectorElementType(), Ext, Idx);
10894     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10895   }
10896
10897   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10898   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10899   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10900     rc = getRegClassFor(MVT::v16i1);
10901   unsigned MaxSift = rc->getSize()*8 - 1;
10902   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10903                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10904   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10905                     DAG.getConstant(MaxSift, dl, MVT::i8));
10906   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10907                        DAG.getIntPtrConstant(0, dl));
10908 }
10909
10910 SDValue
10911 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10912                                            SelectionDAG &DAG) const {
10913   SDLoc dl(Op);
10914   SDValue Vec = Op.getOperand(0);
10915   MVT VecVT = Vec.getSimpleValueType();
10916   SDValue Idx = Op.getOperand(1);
10917
10918   if (Op.getSimpleValueType() == MVT::i1)
10919     return ExtractBitFromMaskVector(Op, DAG);
10920
10921   if (!isa<ConstantSDNode>(Idx)) {
10922     if (VecVT.is512BitVector() ||
10923         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10924          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10925
10926       MVT MaskEltVT =
10927         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10928       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10929                                     MaskEltVT.getSizeInBits());
10930
10931       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10932       auto PtrVT = getPointerTy(DAG.getDataLayout());
10933       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10934                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10935                                  DAG.getConstant(0, dl, PtrVT));
10936       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10937       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10938                          DAG.getConstant(0, dl, PtrVT));
10939     }
10940     return SDValue();
10941   }
10942
10943   // If this is a 256-bit vector result, first extract the 128-bit vector and
10944   // then extract the element from the 128-bit vector.
10945   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10946
10947     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10948     // Get the 128-bit vector.
10949     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10950     MVT EltVT = VecVT.getVectorElementType();
10951
10952     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10953
10954     //if (IdxVal >= NumElems/2)
10955     //  IdxVal -= NumElems/2;
10956     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10957     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10958                        DAG.getConstant(IdxVal, dl, MVT::i32));
10959   }
10960
10961   assert(VecVT.is128BitVector() && "Unexpected vector length");
10962
10963   if (Subtarget->hasSSE41())
10964     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10965       return Res;
10966
10967   MVT VT = Op.getSimpleValueType();
10968   // TODO: handle v16i8.
10969   if (VT.getSizeInBits() == 16) {
10970     SDValue Vec = Op.getOperand(0);
10971     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10972     if (Idx == 0)
10973       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10974                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10975                                      DAG.getBitcast(MVT::v4i32, Vec),
10976                                      Op.getOperand(1)));
10977     // Transform it so it match pextrw which produces a 32-bit result.
10978     MVT EltVT = MVT::i32;
10979     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10980                                   Op.getOperand(0), Op.getOperand(1));
10981     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10982                                   DAG.getValueType(VT));
10983     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10984   }
10985
10986   if (VT.getSizeInBits() == 32) {
10987     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10988     if (Idx == 0)
10989       return Op;
10990
10991     // SHUFPS the element to the lowest double word, then movss.
10992     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10993     MVT VVT = Op.getOperand(0).getSimpleValueType();
10994     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10995                                        DAG.getUNDEF(VVT), Mask);
10996     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10997                        DAG.getIntPtrConstant(0, dl));
10998   }
10999
11000   if (VT.getSizeInBits() == 64) {
11001     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
11002     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
11003     //        to match extract_elt for f64.
11004     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
11005     if (Idx == 0)
11006       return Op;
11007
11008     // UNPCKHPD the element to the lowest double word, then movsd.
11009     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
11010     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
11011     int Mask[2] = { 1, -1 };
11012     MVT VVT = Op.getOperand(0).getSimpleValueType();
11013     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
11014                                        DAG.getUNDEF(VVT), Mask);
11015     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
11016                        DAG.getIntPtrConstant(0, dl));
11017   }
11018
11019   return SDValue();
11020 }
11021
11022 /// Insert one bit to mask vector, like v16i1 or v8i1.
11023 /// AVX-512 feature.
11024 SDValue
11025 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11026   SDLoc dl(Op);
11027   SDValue Vec = Op.getOperand(0);
11028   SDValue Elt = Op.getOperand(1);
11029   SDValue Idx = Op.getOperand(2);
11030   MVT VecVT = Vec.getSimpleValueType();
11031
11032   if (!isa<ConstantSDNode>(Idx)) {
11033     // Non constant index. Extend source and destination,
11034     // insert element and then truncate the result.
11035     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11036     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11037     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11038       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11039       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11040     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11041   }
11042
11043   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11044   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11045   if (IdxVal)
11046     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11047                            DAG.getConstant(IdxVal, dl, MVT::i8));
11048   if (Vec.getOpcode() == ISD::UNDEF)
11049     return EltInVec;
11050   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11051 }
11052
11053 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11054                                                   SelectionDAG &DAG) const {
11055   MVT VT = Op.getSimpleValueType();
11056   MVT EltVT = VT.getVectorElementType();
11057
11058   if (EltVT == MVT::i1)
11059     return InsertBitToMaskVector(Op, DAG);
11060
11061   SDLoc dl(Op);
11062   SDValue N0 = Op.getOperand(0);
11063   SDValue N1 = Op.getOperand(1);
11064   SDValue N2 = Op.getOperand(2);
11065   if (!isa<ConstantSDNode>(N2))
11066     return SDValue();
11067   auto *N2C = cast<ConstantSDNode>(N2);
11068   unsigned IdxVal = N2C->getZExtValue();
11069
11070   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11071   // into that, and then insert the subvector back into the result.
11072   if (VT.is256BitVector() || VT.is512BitVector()) {
11073     // With a 256-bit vector, we can insert into the zero element efficiently
11074     // using a blend if we have AVX or AVX2 and the right data type.
11075     if (VT.is256BitVector() && IdxVal == 0) {
11076       // TODO: It is worthwhile to cast integer to floating point and back
11077       // and incur a domain crossing penalty if that's what we'll end up
11078       // doing anyway after extracting to a 128-bit vector.
11079       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11080           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11081         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11082         N2 = DAG.getIntPtrConstant(1, dl);
11083         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11084       }
11085     }
11086
11087     // Get the desired 128-bit vector chunk.
11088     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11089
11090     // Insert the element into the desired chunk.
11091     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11092     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11093
11094     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11095                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11096
11097     // Insert the changed part back into the bigger vector
11098     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11099   }
11100   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11101
11102   if (Subtarget->hasSSE41()) {
11103     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11104       unsigned Opc;
11105       if (VT == MVT::v8i16) {
11106         Opc = X86ISD::PINSRW;
11107       } else {
11108         assert(VT == MVT::v16i8);
11109         Opc = X86ISD::PINSRB;
11110       }
11111
11112       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11113       // argument.
11114       if (N1.getValueType() != MVT::i32)
11115         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11116       if (N2.getValueType() != MVT::i32)
11117         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11118       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11119     }
11120
11121     if (EltVT == MVT::f32) {
11122       // Bits [7:6] of the constant are the source select. This will always be
11123       //   zero here. The DAG Combiner may combine an extract_elt index into
11124       //   these bits. For example (insert (extract, 3), 2) could be matched by
11125       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11126       // Bits [5:4] of the constant are the destination select. This is the
11127       //   value of the incoming immediate.
11128       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11129       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11130
11131       const Function *F = DAG.getMachineFunction().getFunction();
11132       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11133       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11134         // If this is an insertion of 32-bits into the low 32-bits of
11135         // a vector, we prefer to generate a blend with immediate rather
11136         // than an insertps. Blends are simpler operations in hardware and so
11137         // will always have equal or better performance than insertps.
11138         // But if optimizing for size and there's a load folding opportunity,
11139         // generate insertps because blendps does not have a 32-bit memory
11140         // operand form.
11141         N2 = DAG.getIntPtrConstant(1, dl);
11142         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11143         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11144       }
11145       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11146       // Create this as a scalar to vector..
11147       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11148       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11149     }
11150
11151     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11152       // PINSR* works with constant index.
11153       return Op;
11154     }
11155   }
11156
11157   if (EltVT == MVT::i8)
11158     return SDValue();
11159
11160   if (EltVT.getSizeInBits() == 16) {
11161     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11162     // as its second argument.
11163     if (N1.getValueType() != MVT::i32)
11164       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11165     if (N2.getValueType() != MVT::i32)
11166       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11167     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11168   }
11169   return SDValue();
11170 }
11171
11172 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11173   SDLoc dl(Op);
11174   MVT OpVT = Op.getSimpleValueType();
11175
11176   // If this is a 256-bit vector result, first insert into a 128-bit
11177   // vector and then insert into the 256-bit vector.
11178   if (!OpVT.is128BitVector()) {
11179     // Insert into a 128-bit vector.
11180     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11181     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11182                                  OpVT.getVectorNumElements() / SizeFactor);
11183
11184     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11185
11186     // Insert the 128-bit vector.
11187     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11188   }
11189
11190   if (OpVT == MVT::v1i64 &&
11191       Op.getOperand(0).getValueType() == MVT::i64)
11192     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11193
11194   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11195   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11196   return DAG.getBitcast(
11197       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11198 }
11199
11200 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11201 // a simple subregister reference or explicit instructions to grab
11202 // upper bits of a vector.
11203 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11204                                       SelectionDAG &DAG) {
11205   SDLoc dl(Op);
11206   SDValue In =  Op.getOperand(0);
11207   SDValue Idx = Op.getOperand(1);
11208   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11209   MVT ResVT   = Op.getSimpleValueType();
11210   MVT InVT    = In.getSimpleValueType();
11211
11212   if (Subtarget->hasFp256()) {
11213     if (ResVT.is128BitVector() &&
11214         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11215         isa<ConstantSDNode>(Idx)) {
11216       return Extract128BitVector(In, IdxVal, DAG, dl);
11217     }
11218     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11219         isa<ConstantSDNode>(Idx)) {
11220       return Extract256BitVector(In, IdxVal, DAG, dl);
11221     }
11222   }
11223   return SDValue();
11224 }
11225
11226 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11227 // simple superregister reference or explicit instructions to insert
11228 // the upper bits of a vector.
11229 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11230                                      SelectionDAG &DAG) {
11231   if (!Subtarget->hasAVX())
11232     return SDValue();
11233
11234   SDLoc dl(Op);
11235   SDValue Vec = Op.getOperand(0);
11236   SDValue SubVec = Op.getOperand(1);
11237   SDValue Idx = Op.getOperand(2);
11238
11239   if (!isa<ConstantSDNode>(Idx))
11240     return SDValue();
11241
11242   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11243   MVT OpVT = Op.getSimpleValueType();
11244   MVT SubVecVT = SubVec.getSimpleValueType();
11245
11246   // Fold two 16-byte subvector loads into one 32-byte load:
11247   // (insert_subvector (insert_subvector undef, (load addr), 0),
11248   //                   (load addr + 16), Elts/2)
11249   // --> load32 addr
11250   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11251       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11252       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11253       !Subtarget->isUnalignedMem32Slow()) {
11254     SDValue SubVec2 = Vec.getOperand(1);
11255     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11256       if (Idx2->getZExtValue() == 0) {
11257         SDValue Ops[] = { SubVec2, SubVec };
11258         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11259           return Ld;
11260       }
11261     }
11262   }
11263
11264   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11265       SubVecVT.is128BitVector())
11266     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11267
11268   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11269     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11270
11271   if (OpVT.getVectorElementType() == MVT::i1) {
11272     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11273       return Op;
11274     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11275     SDValue Undef = DAG.getUNDEF(OpVT);
11276     unsigned NumElems = OpVT.getVectorNumElements();
11277     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11278
11279     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11280       // Zero upper bits of the Vec
11281       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11282       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11283
11284       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11285                                  SubVec, ZeroIdx);
11286       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11287       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11288     }
11289     if (IdxVal == 0) {
11290       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11291                                  SubVec, ZeroIdx);
11292       // Zero upper bits of the Vec2
11293       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11294       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11295       // Zero lower bits of the Vec
11296       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11297       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11298       // Merge them together
11299       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11300     }
11301   }
11302   return SDValue();
11303 }
11304
11305 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11306 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11307 // one of the above mentioned nodes. It has to be wrapped because otherwise
11308 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11309 // be used to form addressing mode. These wrapped nodes will be selected
11310 // into MOV32ri.
11311 SDValue
11312 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11313   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11314
11315   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11316   // global base reg.
11317   unsigned char OpFlag = 0;
11318   unsigned WrapperKind = X86ISD::Wrapper;
11319   CodeModel::Model M = DAG.getTarget().getCodeModel();
11320
11321   if (Subtarget->isPICStyleRIPRel() &&
11322       (M == CodeModel::Small || M == CodeModel::Kernel))
11323     WrapperKind = X86ISD::WrapperRIP;
11324   else if (Subtarget->isPICStyleGOT())
11325     OpFlag = X86II::MO_GOTOFF;
11326   else if (Subtarget->isPICStyleStubPIC())
11327     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11328
11329   auto PtrVT = getPointerTy(DAG.getDataLayout());
11330   SDValue Result = DAG.getTargetConstantPool(
11331       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11332   SDLoc DL(CP);
11333   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11334   // With PIC, the address is actually $g + Offset.
11335   if (OpFlag) {
11336     Result =
11337         DAG.getNode(ISD::ADD, DL, PtrVT,
11338                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11339   }
11340
11341   return Result;
11342 }
11343
11344 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11345   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11346
11347   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11348   // global base reg.
11349   unsigned char OpFlag = 0;
11350   unsigned WrapperKind = X86ISD::Wrapper;
11351   CodeModel::Model M = DAG.getTarget().getCodeModel();
11352
11353   if (Subtarget->isPICStyleRIPRel() &&
11354       (M == CodeModel::Small || M == CodeModel::Kernel))
11355     WrapperKind = X86ISD::WrapperRIP;
11356   else if (Subtarget->isPICStyleGOT())
11357     OpFlag = X86II::MO_GOTOFF;
11358   else if (Subtarget->isPICStyleStubPIC())
11359     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11360
11361   auto PtrVT = getPointerTy(DAG.getDataLayout());
11362   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11363   SDLoc DL(JT);
11364   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11365
11366   // With PIC, the address is actually $g + Offset.
11367   if (OpFlag)
11368     Result =
11369         DAG.getNode(ISD::ADD, DL, PtrVT,
11370                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11371
11372   return Result;
11373 }
11374
11375 SDValue
11376 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11377   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11378
11379   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11380   // global base reg.
11381   unsigned char OpFlag = 0;
11382   unsigned WrapperKind = X86ISD::Wrapper;
11383   CodeModel::Model M = DAG.getTarget().getCodeModel();
11384
11385   if (Subtarget->isPICStyleRIPRel() &&
11386       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11387     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11388       OpFlag = X86II::MO_GOTPCREL;
11389     WrapperKind = X86ISD::WrapperRIP;
11390   } else if (Subtarget->isPICStyleGOT()) {
11391     OpFlag = X86II::MO_GOT;
11392   } else if (Subtarget->isPICStyleStubPIC()) {
11393     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11394   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11395     OpFlag = X86II::MO_DARWIN_NONLAZY;
11396   }
11397
11398   auto PtrVT = getPointerTy(DAG.getDataLayout());
11399   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11400
11401   SDLoc DL(Op);
11402   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11403
11404   // With PIC, the address is actually $g + Offset.
11405   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11406       !Subtarget->is64Bit()) {
11407     Result =
11408         DAG.getNode(ISD::ADD, DL, PtrVT,
11409                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11410   }
11411
11412   // For symbols that require a load from a stub to get the address, emit the
11413   // load.
11414   if (isGlobalStubReference(OpFlag))
11415     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11416                          MachinePointerInfo::getGOT(), false, false, false, 0);
11417
11418   return Result;
11419 }
11420
11421 SDValue
11422 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11423   // Create the TargetBlockAddressAddress node.
11424   unsigned char OpFlags =
11425     Subtarget->ClassifyBlockAddressReference();
11426   CodeModel::Model M = DAG.getTarget().getCodeModel();
11427   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11428   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11429   SDLoc dl(Op);
11430   auto PtrVT = getPointerTy(DAG.getDataLayout());
11431   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11432
11433   if (Subtarget->isPICStyleRIPRel() &&
11434       (M == CodeModel::Small || M == CodeModel::Kernel))
11435     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11436   else
11437     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11438
11439   // With PIC, the address is actually $g + Offset.
11440   if (isGlobalRelativeToPICBase(OpFlags)) {
11441     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11442                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11443   }
11444
11445   return Result;
11446 }
11447
11448 SDValue
11449 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11450                                       int64_t Offset, SelectionDAG &DAG) const {
11451   // Create the TargetGlobalAddress node, folding in the constant
11452   // offset if it is legal.
11453   unsigned char OpFlags =
11454       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11455   CodeModel::Model M = DAG.getTarget().getCodeModel();
11456   auto PtrVT = getPointerTy(DAG.getDataLayout());
11457   SDValue Result;
11458   if (OpFlags == X86II::MO_NO_FLAG &&
11459       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11460     // A direct static reference to a global.
11461     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11462     Offset = 0;
11463   } else {
11464     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11465   }
11466
11467   if (Subtarget->isPICStyleRIPRel() &&
11468       (M == CodeModel::Small || M == CodeModel::Kernel))
11469     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11470   else
11471     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11472
11473   // With PIC, the address is actually $g + Offset.
11474   if (isGlobalRelativeToPICBase(OpFlags)) {
11475     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11476                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11477   }
11478
11479   // For globals that require a load from a stub to get the address, emit the
11480   // load.
11481   if (isGlobalStubReference(OpFlags))
11482     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11483                          MachinePointerInfo::getGOT(), false, false, false, 0);
11484
11485   // If there was a non-zero offset that we didn't fold, create an explicit
11486   // addition for it.
11487   if (Offset != 0)
11488     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11489                          DAG.getConstant(Offset, dl, PtrVT));
11490
11491   return Result;
11492 }
11493
11494 SDValue
11495 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11496   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11497   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11498   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11499 }
11500
11501 static SDValue
11502 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11503            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11504            unsigned char OperandFlags, bool LocalDynamic = false) {
11505   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11506   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11507   SDLoc dl(GA);
11508   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11509                                            GA->getValueType(0),
11510                                            GA->getOffset(),
11511                                            OperandFlags);
11512
11513   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11514                                            : X86ISD::TLSADDR;
11515
11516   if (InFlag) {
11517     SDValue Ops[] = { Chain,  TGA, *InFlag };
11518     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11519   } else {
11520     SDValue Ops[]  = { Chain, TGA };
11521     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11522   }
11523
11524   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11525   MFI->setAdjustsStack(true);
11526   MFI->setHasCalls(true);
11527
11528   SDValue Flag = Chain.getValue(1);
11529   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11530 }
11531
11532 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11533 static SDValue
11534 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11535                                 const EVT PtrVT) {
11536   SDValue InFlag;
11537   SDLoc dl(GA);  // ? function entry point might be better
11538   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11539                                    DAG.getNode(X86ISD::GlobalBaseReg,
11540                                                SDLoc(), PtrVT), InFlag);
11541   InFlag = Chain.getValue(1);
11542
11543   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11544 }
11545
11546 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11547 static SDValue
11548 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11549                                 const EVT PtrVT) {
11550   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11551                     X86::RAX, X86II::MO_TLSGD);
11552 }
11553
11554 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11555                                            SelectionDAG &DAG,
11556                                            const EVT PtrVT,
11557                                            bool is64Bit) {
11558   SDLoc dl(GA);
11559
11560   // Get the start address of the TLS block for this module.
11561   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11562       .getInfo<X86MachineFunctionInfo>();
11563   MFI->incNumLocalDynamicTLSAccesses();
11564
11565   SDValue Base;
11566   if (is64Bit) {
11567     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11568                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11569   } else {
11570     SDValue InFlag;
11571     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11572         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11573     InFlag = Chain.getValue(1);
11574     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11575                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11576   }
11577
11578   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11579   // of Base.
11580
11581   // Build x@dtpoff.
11582   unsigned char OperandFlags = X86II::MO_DTPOFF;
11583   unsigned WrapperKind = X86ISD::Wrapper;
11584   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11585                                            GA->getValueType(0),
11586                                            GA->getOffset(), OperandFlags);
11587   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11588
11589   // Add x@dtpoff with the base.
11590   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11591 }
11592
11593 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11594 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11595                                    const EVT PtrVT, TLSModel::Model model,
11596                                    bool is64Bit, bool isPIC) {
11597   SDLoc dl(GA);
11598
11599   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11600   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11601                                                          is64Bit ? 257 : 256));
11602
11603   SDValue ThreadPointer =
11604       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11605                   MachinePointerInfo(Ptr), false, false, false, 0);
11606
11607   unsigned char OperandFlags = 0;
11608   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11609   // initialexec.
11610   unsigned WrapperKind = X86ISD::Wrapper;
11611   if (model == TLSModel::LocalExec) {
11612     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11613   } else if (model == TLSModel::InitialExec) {
11614     if (is64Bit) {
11615       OperandFlags = X86II::MO_GOTTPOFF;
11616       WrapperKind = X86ISD::WrapperRIP;
11617     } else {
11618       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11619     }
11620   } else {
11621     llvm_unreachable("Unexpected model");
11622   }
11623
11624   // emit "addl x@ntpoff,%eax" (local exec)
11625   // or "addl x@indntpoff,%eax" (initial exec)
11626   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11627   SDValue TGA =
11628       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11629                                  GA->getOffset(), OperandFlags);
11630   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11631
11632   if (model == TLSModel::InitialExec) {
11633     if (isPIC && !is64Bit) {
11634       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11635                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11636                            Offset);
11637     }
11638
11639     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11640                          MachinePointerInfo::getGOT(), false, false, false, 0);
11641   }
11642
11643   // The address of the thread local variable is the add of the thread
11644   // pointer with the offset of the variable.
11645   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11646 }
11647
11648 SDValue
11649 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11650
11651   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11652   const GlobalValue *GV = GA->getGlobal();
11653   auto PtrVT = getPointerTy(DAG.getDataLayout());
11654
11655   if (Subtarget->isTargetELF()) {
11656     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11657     switch (model) {
11658       case TLSModel::GeneralDynamic:
11659         if (Subtarget->is64Bit())
11660           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11661         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11662       case TLSModel::LocalDynamic:
11663         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11664                                            Subtarget->is64Bit());
11665       case TLSModel::InitialExec:
11666       case TLSModel::LocalExec:
11667         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11668                                    DAG.getTarget().getRelocationModel() ==
11669                                        Reloc::PIC_);
11670     }
11671     llvm_unreachable("Unknown TLS model.");
11672   }
11673
11674   if (Subtarget->isTargetDarwin()) {
11675     // Darwin only has one model of TLS.  Lower to that.
11676     unsigned char OpFlag = 0;
11677     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11678                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11679
11680     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11681     // global base reg.
11682     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11683                  !Subtarget->is64Bit();
11684     if (PIC32)
11685       OpFlag = X86II::MO_TLVP_PIC_BASE;
11686     else
11687       OpFlag = X86II::MO_TLVP;
11688     SDLoc DL(Op);
11689     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11690                                                 GA->getValueType(0),
11691                                                 GA->getOffset(), OpFlag);
11692     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11693
11694     // With PIC32, the address is actually $g + Offset.
11695     if (PIC32)
11696       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11697                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11698                            Offset);
11699
11700     // Lowering the machine isd will make sure everything is in the right
11701     // location.
11702     SDValue Chain = DAG.getEntryNode();
11703     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11704     SDValue Args[] = { Chain, Offset };
11705     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11706
11707     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11708     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11709     MFI->setAdjustsStack(true);
11710
11711     // And our return value (tls address) is in the standard call return value
11712     // location.
11713     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11714     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11715   }
11716
11717   if (Subtarget->isTargetKnownWindowsMSVC() ||
11718       Subtarget->isTargetWindowsGNU()) {
11719     // Just use the implicit TLS architecture
11720     // Need to generate someting similar to:
11721     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11722     //                                  ; from TEB
11723     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11724     //   mov     rcx, qword [rdx+rcx*8]
11725     //   mov     eax, .tls$:tlsvar
11726     //   [rax+rcx] contains the address
11727     // Windows 64bit: gs:0x58
11728     // Windows 32bit: fs:__tls_array
11729
11730     SDLoc dl(GA);
11731     SDValue Chain = DAG.getEntryNode();
11732
11733     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11734     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11735     // use its literal value of 0x2C.
11736     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11737                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11738                                                              256)
11739                                         : Type::getInt32PtrTy(*DAG.getContext(),
11740                                                               257));
11741
11742     SDValue TlsArray = Subtarget->is64Bit()
11743                            ? DAG.getIntPtrConstant(0x58, dl)
11744                            : (Subtarget->isTargetWindowsGNU()
11745                                   ? DAG.getIntPtrConstant(0x2C, dl)
11746                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11747
11748     SDValue ThreadPointer =
11749         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11750                     false, false, 0);
11751
11752     SDValue res;
11753     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11754       res = ThreadPointer;
11755     } else {
11756       // Load the _tls_index variable
11757       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11758       if (Subtarget->is64Bit())
11759         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11760                              MachinePointerInfo(), MVT::i32, false, false,
11761                              false, 0);
11762       else
11763         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11764                           false, false, 0);
11765
11766       auto &DL = DAG.getDataLayout();
11767       SDValue Scale =
11768           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11769       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11770
11771       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11772     }
11773
11774     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11775                       false, 0);
11776
11777     // Get the offset of start of .tls section
11778     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11779                                              GA->getValueType(0),
11780                                              GA->getOffset(), X86II::MO_SECREL);
11781     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11782
11783     // The address of the thread local variable is the add of the thread
11784     // pointer with the offset of the variable.
11785     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11786   }
11787
11788   llvm_unreachable("TLS not implemented for this target.");
11789 }
11790
11791 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11792 /// and take a 2 x i32 value to shift plus a shift amount.
11793 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11794   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11795   MVT VT = Op.getSimpleValueType();
11796   unsigned VTBits = VT.getSizeInBits();
11797   SDLoc dl(Op);
11798   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11799   SDValue ShOpLo = Op.getOperand(0);
11800   SDValue ShOpHi = Op.getOperand(1);
11801   SDValue ShAmt  = Op.getOperand(2);
11802   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11803   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11804   // during isel.
11805   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11806                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11807   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11808                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11809                        : DAG.getConstant(0, dl, VT);
11810
11811   SDValue Tmp2, Tmp3;
11812   if (Op.getOpcode() == ISD::SHL_PARTS) {
11813     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11814     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11815   } else {
11816     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11817     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11818   }
11819
11820   // If the shift amount is larger or equal than the width of a part we can't
11821   // rely on the results of shld/shrd. Insert a test and select the appropriate
11822   // values for large shift amounts.
11823   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11824                                 DAG.getConstant(VTBits, dl, MVT::i8));
11825   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11826                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11827
11828   SDValue Hi, Lo;
11829   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11830   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11831   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11832
11833   if (Op.getOpcode() == ISD::SHL_PARTS) {
11834     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11835     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11836   } else {
11837     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11838     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11839   }
11840
11841   SDValue Ops[2] = { Lo, Hi };
11842   return DAG.getMergeValues(Ops, dl);
11843 }
11844
11845 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11846                                            SelectionDAG &DAG) const {
11847   SDValue Src = Op.getOperand(0);
11848   MVT SrcVT = Src.getSimpleValueType();
11849   MVT VT = Op.getSimpleValueType();
11850   SDLoc dl(Op);
11851
11852   if (SrcVT.isVector()) {
11853     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11854       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11855                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11856                          DAG.getUNDEF(SrcVT)));
11857     }
11858     if (SrcVT.getVectorElementType() == MVT::i1) {
11859       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11860       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11861                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11862     }
11863     return SDValue();
11864   }
11865
11866   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11867          "Unknown SINT_TO_FP to lower!");
11868
11869   // These are really Legal; return the operand so the caller accepts it as
11870   // Legal.
11871   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11872     return Op;
11873   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11874       Subtarget->is64Bit()) {
11875     return Op;
11876   }
11877
11878   unsigned Size = SrcVT.getSizeInBits()/8;
11879   MachineFunction &MF = DAG.getMachineFunction();
11880   auto PtrVT = getPointerTy(MF.getDataLayout());
11881   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11882   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11883   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11884                                StackSlot,
11885                                MachinePointerInfo::getFixedStack(SSFI),
11886                                false, false, 0);
11887   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11888 }
11889
11890 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11891                                      SDValue StackSlot,
11892                                      SelectionDAG &DAG) const {
11893   // Build the FILD
11894   SDLoc DL(Op);
11895   SDVTList Tys;
11896   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11897   if (useSSE)
11898     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11899   else
11900     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11901
11902   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11903
11904   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11905   MachineMemOperand *MMO;
11906   if (FI) {
11907     int SSFI = FI->getIndex();
11908     MMO =
11909       DAG.getMachineFunction()
11910       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11911                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11912   } else {
11913     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11914     StackSlot = StackSlot.getOperand(1);
11915   }
11916   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11917   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11918                                            X86ISD::FILD, DL,
11919                                            Tys, Ops, SrcVT, MMO);
11920
11921   if (useSSE) {
11922     Chain = Result.getValue(1);
11923     SDValue InFlag = Result.getValue(2);
11924
11925     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11926     // shouldn't be necessary except that RFP cannot be live across
11927     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11928     MachineFunction &MF = DAG.getMachineFunction();
11929     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11930     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11931     auto PtrVT = getPointerTy(MF.getDataLayout());
11932     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11933     Tys = DAG.getVTList(MVT::Other);
11934     SDValue Ops[] = {
11935       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11936     };
11937     MachineMemOperand *MMO =
11938       DAG.getMachineFunction()
11939       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11940                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11941
11942     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11943                                     Ops, Op.getValueType(), MMO);
11944     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11945                          MachinePointerInfo::getFixedStack(SSFI),
11946                          false, false, false, 0);
11947   }
11948
11949   return Result;
11950 }
11951
11952 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11953 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11954                                                SelectionDAG &DAG) const {
11955   // This algorithm is not obvious. Here it is what we're trying to output:
11956   /*
11957      movq       %rax,  %xmm0
11958      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11959      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11960      #ifdef __SSE3__
11961        haddpd   %xmm0, %xmm0
11962      #else
11963        pshufd   $0x4e, %xmm0, %xmm1
11964        addpd    %xmm1, %xmm0
11965      #endif
11966   */
11967
11968   SDLoc dl(Op);
11969   LLVMContext *Context = DAG.getContext();
11970
11971   // Build some magic constants.
11972   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11973   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11974   auto PtrVT = getPointerTy(DAG.getDataLayout());
11975   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11976
11977   SmallVector<Constant*,2> CV1;
11978   CV1.push_back(
11979     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11980                                       APInt(64, 0x4330000000000000ULL))));
11981   CV1.push_back(
11982     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11983                                       APInt(64, 0x4530000000000000ULL))));
11984   Constant *C1 = ConstantVector::get(CV1);
11985   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11986
11987   // Load the 64-bit value into an XMM register.
11988   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11989                             Op.getOperand(0));
11990   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11991                               MachinePointerInfo::getConstantPool(),
11992                               false, false, false, 16);
11993   SDValue Unpck1 =
11994       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11995
11996   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11997                               MachinePointerInfo::getConstantPool(),
11998                               false, false, false, 16);
11999   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
12000   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
12001   SDValue Result;
12002
12003   if (Subtarget->hasSSE3()) {
12004     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
12005     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
12006   } else {
12007     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
12008     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
12009                                            S2F, 0x4E, DAG);
12010     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
12011                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
12012   }
12013
12014   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
12015                      DAG.getIntPtrConstant(0, dl));
12016 }
12017
12018 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
12019 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
12020                                                SelectionDAG &DAG) const {
12021   SDLoc dl(Op);
12022   // FP constant to bias correct the final result.
12023   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
12024                                    MVT::f64);
12025
12026   // Load the 32-bit value into an XMM register.
12027   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12028                              Op.getOperand(0));
12029
12030   // Zero out the upper parts of the register.
12031   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12032
12033   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12034                      DAG.getBitcast(MVT::v2f64, Load),
12035                      DAG.getIntPtrConstant(0, dl));
12036
12037   // Or the load with the bias.
12038   SDValue Or = DAG.getNode(
12039       ISD::OR, dl, MVT::v2i64,
12040       DAG.getBitcast(MVT::v2i64,
12041                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12042       DAG.getBitcast(MVT::v2i64,
12043                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12044   Or =
12045       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12046                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12047
12048   // Subtract the bias.
12049   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12050
12051   // Handle final rounding.
12052   EVT DestVT = Op.getValueType();
12053
12054   if (DestVT.bitsLT(MVT::f64))
12055     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12056                        DAG.getIntPtrConstant(0, dl));
12057   if (DestVT.bitsGT(MVT::f64))
12058     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12059
12060   // Handle final rounding.
12061   return Sub;
12062 }
12063
12064 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12065                                      const X86Subtarget &Subtarget) {
12066   // The algorithm is the following:
12067   // #ifdef __SSE4_1__
12068   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12069   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12070   //                                 (uint4) 0x53000000, 0xaa);
12071   // #else
12072   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12073   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12074   // #endif
12075   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12076   //     return (float4) lo + fhi;
12077
12078   SDLoc DL(Op);
12079   SDValue V = Op->getOperand(0);
12080   EVT VecIntVT = V.getValueType();
12081   bool Is128 = VecIntVT == MVT::v4i32;
12082   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12083   // If we convert to something else than the supported type, e.g., to v4f64,
12084   // abort early.
12085   if (VecFloatVT != Op->getValueType(0))
12086     return SDValue();
12087
12088   unsigned NumElts = VecIntVT.getVectorNumElements();
12089   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12090          "Unsupported custom type");
12091   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12092
12093   // In the #idef/#else code, we have in common:
12094   // - The vector of constants:
12095   // -- 0x4b000000
12096   // -- 0x53000000
12097   // - A shift:
12098   // -- v >> 16
12099
12100   // Create the splat vector for 0x4b000000.
12101   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12102   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12103                            CstLow, CstLow, CstLow, CstLow};
12104   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12105                                   makeArrayRef(&CstLowArray[0], NumElts));
12106   // Create the splat vector for 0x53000000.
12107   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12108   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12109                             CstHigh, CstHigh, CstHigh, CstHigh};
12110   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12111                                    makeArrayRef(&CstHighArray[0], NumElts));
12112
12113   // Create the right shift.
12114   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12115   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12116                              CstShift, CstShift, CstShift, CstShift};
12117   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12118                                     makeArrayRef(&CstShiftArray[0], NumElts));
12119   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12120
12121   SDValue Low, High;
12122   if (Subtarget.hasSSE41()) {
12123     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12124     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12125     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12126     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12127     // Low will be bitcasted right away, so do not bother bitcasting back to its
12128     // original type.
12129     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12130                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12131     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12132     //                                 (uint4) 0x53000000, 0xaa);
12133     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12134     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12135     // High will be bitcasted right away, so do not bother bitcasting back to
12136     // its original type.
12137     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12138                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12139   } else {
12140     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12141     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12142                                      CstMask, CstMask, CstMask);
12143     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12144     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12145     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12146
12147     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12148     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12149   }
12150
12151   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12152   SDValue CstFAdd = DAG.getConstantFP(
12153       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12154   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12155                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12156   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12157                                    makeArrayRef(&CstFAddArray[0], NumElts));
12158
12159   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12160   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12161   SDValue FHigh =
12162       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12163   //     return (float4) lo + fhi;
12164   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12165   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12166 }
12167
12168 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12169                                                SelectionDAG &DAG) const {
12170   SDValue N0 = Op.getOperand(0);
12171   MVT SVT = N0.getSimpleValueType();
12172   SDLoc dl(Op);
12173
12174   switch (SVT.SimpleTy) {
12175   default:
12176     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12177   case MVT::v4i8:
12178   case MVT::v4i16:
12179   case MVT::v8i8:
12180   case MVT::v8i16: {
12181     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12182     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12183                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12184   }
12185   case MVT::v4i32:
12186   case MVT::v8i32:
12187     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12188   case MVT::v16i8:
12189   case MVT::v16i16:
12190     if (Subtarget->hasAVX512())
12191       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12192                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12193   }
12194   llvm_unreachable(nullptr);
12195 }
12196
12197 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12198                                            SelectionDAG &DAG) const {
12199   SDValue N0 = Op.getOperand(0);
12200   SDLoc dl(Op);
12201   auto PtrVT = getPointerTy(DAG.getDataLayout());
12202
12203   if (Op.getValueType().isVector())
12204     return lowerUINT_TO_FP_vec(Op, DAG);
12205
12206   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12207   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12208   // the optimization here.
12209   if (DAG.SignBitIsZero(N0))
12210     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12211
12212   MVT SrcVT = N0.getSimpleValueType();
12213   MVT DstVT = Op.getSimpleValueType();
12214   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12215     return LowerUINT_TO_FP_i64(Op, DAG);
12216   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12217     return LowerUINT_TO_FP_i32(Op, DAG);
12218   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12219     return SDValue();
12220
12221   // Make a 64-bit buffer, and use it to build an FILD.
12222   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12223   if (SrcVT == MVT::i32) {
12224     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12225     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12226     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12227                                   StackSlot, MachinePointerInfo(),
12228                                   false, false, 0);
12229     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12230                                   OffsetSlot, MachinePointerInfo(),
12231                                   false, false, 0);
12232     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12233     return Fild;
12234   }
12235
12236   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12237   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12238                                StackSlot, MachinePointerInfo(),
12239                                false, false, 0);
12240   // For i64 source, we need to add the appropriate power of 2 if the input
12241   // was negative.  This is the same as the optimization in
12242   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12243   // we must be careful to do the computation in x87 extended precision, not
12244   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12245   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12246   MachineMemOperand *MMO =
12247     DAG.getMachineFunction()
12248     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12249                           MachineMemOperand::MOLoad, 8, 8);
12250
12251   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12252   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12253   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12254                                          MVT::i64, MMO);
12255
12256   APInt FF(32, 0x5F800000ULL);
12257
12258   // Check whether the sign bit is set.
12259   SDValue SignSet = DAG.getSetCC(
12260       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12261       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12262
12263   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12264   SDValue FudgePtr = DAG.getConstantPool(
12265       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12266
12267   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12268   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12269   SDValue Four = DAG.getIntPtrConstant(4, dl);
12270   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12271                                Zero, Four);
12272   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12273
12274   // Load the value out, extending it from f32 to f80.
12275   // FIXME: Avoid the extend by constructing the right constant pool?
12276   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12277                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12278                                  MVT::f32, false, false, false, 4);
12279   // Extend everything to 80 bits to force it to be done on x87.
12280   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12281   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12282                      DAG.getIntPtrConstant(0, dl));
12283 }
12284
12285 std::pair<SDValue,SDValue>
12286 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12287                                     bool IsSigned, bool IsReplace) const {
12288   SDLoc DL(Op);
12289
12290   EVT DstTy = Op.getValueType();
12291   auto PtrVT = getPointerTy(DAG.getDataLayout());
12292
12293   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12294     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12295     DstTy = MVT::i64;
12296   }
12297
12298   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12299          DstTy.getSimpleVT() >= MVT::i16 &&
12300          "Unknown FP_TO_INT to lower!");
12301
12302   // These are really Legal.
12303   if (DstTy == MVT::i32 &&
12304       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12305     return std::make_pair(SDValue(), SDValue());
12306   if (Subtarget->is64Bit() &&
12307       DstTy == MVT::i64 &&
12308       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12309     return std::make_pair(SDValue(), SDValue());
12310
12311   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12312   // stack slot, or into the FTOL runtime function.
12313   MachineFunction &MF = DAG.getMachineFunction();
12314   unsigned MemSize = DstTy.getSizeInBits()/8;
12315   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12316   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12317
12318   unsigned Opc;
12319   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12320     Opc = X86ISD::WIN_FTOL;
12321   else
12322     switch (DstTy.getSimpleVT().SimpleTy) {
12323     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12324     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12325     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12326     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12327     }
12328
12329   SDValue Chain = DAG.getEntryNode();
12330   SDValue Value = Op.getOperand(0);
12331   EVT TheVT = Op.getOperand(0).getValueType();
12332   // FIXME This causes a redundant load/store if the SSE-class value is already
12333   // in memory, such as if it is on the callstack.
12334   if (isScalarFPTypeInSSEReg(TheVT)) {
12335     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12336     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12337                          MachinePointerInfo::getFixedStack(SSFI),
12338                          false, false, 0);
12339     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12340     SDValue Ops[] = {
12341       Chain, StackSlot, DAG.getValueType(TheVT)
12342     };
12343
12344     MachineMemOperand *MMO =
12345       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12346                               MachineMemOperand::MOLoad, MemSize, MemSize);
12347     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12348     Chain = Value.getValue(1);
12349     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12350     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12351   }
12352
12353   MachineMemOperand *MMO =
12354     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12355                             MachineMemOperand::MOStore, MemSize, MemSize);
12356
12357   if (Opc != X86ISD::WIN_FTOL) {
12358     // Build the FP_TO_INT*_IN_MEM
12359     SDValue Ops[] = { Chain, Value, StackSlot };
12360     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12361                                            Ops, DstTy, MMO);
12362     return std::make_pair(FIST, StackSlot);
12363   } else {
12364     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12365       DAG.getVTList(MVT::Other, MVT::Glue),
12366       Chain, Value);
12367     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12368       MVT::i32, ftol.getValue(1));
12369     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12370       MVT::i32, eax.getValue(2));
12371     SDValue Ops[] = { eax, edx };
12372     SDValue pair = IsReplace
12373       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12374       : DAG.getMergeValues(Ops, DL);
12375     return std::make_pair(pair, SDValue());
12376   }
12377 }
12378
12379 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12380                               const X86Subtarget *Subtarget) {
12381   MVT VT = Op->getSimpleValueType(0);
12382   SDValue In = Op->getOperand(0);
12383   MVT InVT = In.getSimpleValueType();
12384   SDLoc dl(Op);
12385
12386   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12387     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12388
12389   // Optimize vectors in AVX mode:
12390   //
12391   //   v8i16 -> v8i32
12392   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12393   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12394   //   Concat upper and lower parts.
12395   //
12396   //   v4i32 -> v4i64
12397   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12398   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12399   //   Concat upper and lower parts.
12400   //
12401
12402   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12403       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12404       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12405     return SDValue();
12406
12407   if (Subtarget->hasInt256())
12408     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12409
12410   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12411   SDValue Undef = DAG.getUNDEF(InVT);
12412   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12413   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12414   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12415
12416   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12417                              VT.getVectorNumElements()/2);
12418
12419   OpLo = DAG.getBitcast(HVT, OpLo);
12420   OpHi = DAG.getBitcast(HVT, OpHi);
12421
12422   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12423 }
12424
12425 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12426                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12427   MVT VT = Op->getSimpleValueType(0);
12428   SDValue In = Op->getOperand(0);
12429   MVT InVT = In.getSimpleValueType();
12430   SDLoc DL(Op);
12431   unsigned int NumElts = VT.getVectorNumElements();
12432   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12433     return SDValue();
12434
12435   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12436     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12437
12438   assert(InVT.getVectorElementType() == MVT::i1);
12439   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12440   SDValue One =
12441    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12442   SDValue Zero =
12443    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12444
12445   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12446   if (VT.is512BitVector())
12447     return V;
12448   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12449 }
12450
12451 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12452                                SelectionDAG &DAG) {
12453   if (Subtarget->hasFp256())
12454     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12455       return Res;
12456
12457   return SDValue();
12458 }
12459
12460 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12461                                 SelectionDAG &DAG) {
12462   SDLoc DL(Op);
12463   MVT VT = Op.getSimpleValueType();
12464   SDValue In = Op.getOperand(0);
12465   MVT SVT = In.getSimpleValueType();
12466
12467   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12468     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12469
12470   if (Subtarget->hasFp256())
12471     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12472       return Res;
12473
12474   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12475          VT.getVectorNumElements() != SVT.getVectorNumElements());
12476   return SDValue();
12477 }
12478
12479 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12480   SDLoc DL(Op);
12481   MVT VT = Op.getSimpleValueType();
12482   SDValue In = Op.getOperand(0);
12483   MVT InVT = In.getSimpleValueType();
12484
12485   if (VT == MVT::i1) {
12486     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12487            "Invalid scalar TRUNCATE operation");
12488     if (InVT.getSizeInBits() >= 32)
12489       return SDValue();
12490     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12491     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12492   }
12493   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12494          "Invalid TRUNCATE operation");
12495
12496   // move vector to mask - truncate solution for SKX
12497   if (VT.getVectorElementType() == MVT::i1) {
12498     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12499         Subtarget->hasBWI())
12500       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12501     if ((InVT.is256BitVector() || InVT.is128BitVector())
12502         && InVT.getScalarSizeInBits() <= 16 &&
12503         Subtarget->hasBWI() && Subtarget->hasVLX())
12504       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12505     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12506         Subtarget->hasDQI())
12507       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12508     if ((InVT.is256BitVector() || InVT.is128BitVector())
12509         && InVT.getScalarSizeInBits() >= 32 &&
12510         Subtarget->hasDQI() && Subtarget->hasVLX())
12511       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12512   }
12513
12514   if (VT.getVectorElementType() == MVT::i1) {
12515     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12516     unsigned NumElts = InVT.getVectorNumElements();
12517     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12518     if (InVT.getSizeInBits() < 512) {
12519       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12520       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12521       InVT = ExtVT;
12522     }
12523
12524     SDValue OneV =
12525      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12526     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12527     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12528   }
12529
12530   // vpmovqb/w/d, vpmovdb/w, vpmovwb
12531   if (((!InVT.is512BitVector() && Subtarget->hasVLX()) || InVT.is512BitVector()) &&
12532       (InVT.getVectorElementType() != MVT::i16 || Subtarget->hasBWI()))
12533     return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12534
12535   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12536     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12537     if (Subtarget->hasInt256()) {
12538       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12539       In = DAG.getBitcast(MVT::v8i32, In);
12540       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12541                                 ShufMask);
12542       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12543                          DAG.getIntPtrConstant(0, DL));
12544     }
12545
12546     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12547                                DAG.getIntPtrConstant(0, DL));
12548     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12549                                DAG.getIntPtrConstant(2, DL));
12550     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12551     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12552     static const int ShufMask[] = {0, 2, 4, 6};
12553     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12554   }
12555
12556   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12557     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12558     if (Subtarget->hasInt256()) {
12559       In = DAG.getBitcast(MVT::v32i8, In);
12560
12561       SmallVector<SDValue,32> pshufbMask;
12562       for (unsigned i = 0; i < 2; ++i) {
12563         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12564         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12565         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12566         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12567         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12568         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12569         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12570         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12571         for (unsigned j = 0; j < 8; ++j)
12572           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12573       }
12574       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12575       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12576       In = DAG.getBitcast(MVT::v4i64, In);
12577
12578       static const int ShufMask[] = {0,  2,  -1,  -1};
12579       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12580                                 &ShufMask[0]);
12581       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12582                        DAG.getIntPtrConstant(0, DL));
12583       return DAG.getBitcast(VT, In);
12584     }
12585
12586     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12587                                DAG.getIntPtrConstant(0, DL));
12588
12589     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12590                                DAG.getIntPtrConstant(4, DL));
12591
12592     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12593     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12594
12595     // The PSHUFB mask:
12596     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12597                                    -1, -1, -1, -1, -1, -1, -1, -1};
12598
12599     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12600     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12601     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12602
12603     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12604     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12605
12606     // The MOVLHPS Mask:
12607     static const int ShufMask2[] = {0, 1, 4, 5};
12608     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12609     return DAG.getBitcast(MVT::v8i16, res);
12610   }
12611
12612   // Handle truncation of V256 to V128 using shuffles.
12613   if (!VT.is128BitVector() || !InVT.is256BitVector())
12614     return SDValue();
12615
12616   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12617
12618   unsigned NumElems = VT.getVectorNumElements();
12619   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12620
12621   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12622   // Prepare truncation shuffle mask
12623   for (unsigned i = 0; i != NumElems; ++i)
12624     MaskVec[i] = i * 2;
12625   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12626                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12627   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12628                      DAG.getIntPtrConstant(0, DL));
12629 }
12630
12631 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12632                                            SelectionDAG &DAG) const {
12633   assert(!Op.getSimpleValueType().isVector());
12634
12635   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12636     /*IsSigned=*/ true, /*IsReplace=*/ false);
12637   SDValue FIST = Vals.first, StackSlot = Vals.second;
12638   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12639   if (!FIST.getNode()) return Op;
12640
12641   if (StackSlot.getNode())
12642     // Load the result.
12643     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12644                        FIST, StackSlot, MachinePointerInfo(),
12645                        false, false, false, 0);
12646
12647   // The node is the result.
12648   return FIST;
12649 }
12650
12651 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12652                                            SelectionDAG &DAG) const {
12653   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12654     /*IsSigned=*/ false, /*IsReplace=*/ false);
12655   SDValue FIST = Vals.first, StackSlot = Vals.second;
12656   assert(FIST.getNode() && "Unexpected failure");
12657
12658   if (StackSlot.getNode())
12659     // Load the result.
12660     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12661                        FIST, StackSlot, MachinePointerInfo(),
12662                        false, false, false, 0);
12663
12664   // The node is the result.
12665   return FIST;
12666 }
12667
12668 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12669   SDLoc DL(Op);
12670   MVT VT = Op.getSimpleValueType();
12671   SDValue In = Op.getOperand(0);
12672   MVT SVT = In.getSimpleValueType();
12673
12674   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12675
12676   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12677                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12678                                  In, DAG.getUNDEF(SVT)));
12679 }
12680
12681 /// The only differences between FABS and FNEG are the mask and the logic op.
12682 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12683 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12684   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12685          "Wrong opcode for lowering FABS or FNEG.");
12686
12687   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12688
12689   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12690   // into an FNABS. We'll lower the FABS after that if it is still in use.
12691   if (IsFABS)
12692     for (SDNode *User : Op->uses())
12693       if (User->getOpcode() == ISD::FNEG)
12694         return Op;
12695
12696   SDValue Op0 = Op.getOperand(0);
12697   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12698
12699   SDLoc dl(Op);
12700   MVT VT = Op.getSimpleValueType();
12701   // Assume scalar op for initialization; update for vector if needed.
12702   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12703   // generate a 16-byte vector constant and logic op even for the scalar case.
12704   // Using a 16-byte mask allows folding the load of the mask with
12705   // the logic op, so it can save (~4 bytes) on code size.
12706   MVT EltVT = VT;
12707   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12708   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12709   // decide if we should generate a 16-byte constant mask when we only need 4 or
12710   // 8 bytes for the scalar case.
12711   if (VT.isVector()) {
12712     EltVT = VT.getVectorElementType();
12713     NumElts = VT.getVectorNumElements();
12714   }
12715
12716   unsigned EltBits = EltVT.getSizeInBits();
12717   LLVMContext *Context = DAG.getContext();
12718   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12719   APInt MaskElt =
12720     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12721   Constant *C = ConstantInt::get(*Context, MaskElt);
12722   C = ConstantVector::getSplat(NumElts, C);
12723   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12724   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12725   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12726   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12727                              MachinePointerInfo::getConstantPool(),
12728                              false, false, false, Alignment);
12729
12730   if (VT.isVector()) {
12731     // For a vector, cast operands to a vector type, perform the logic op,
12732     // and cast the result back to the original value type.
12733     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12734     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12735     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12736                               : DAG.getBitcast(VecVT, Op0);
12737     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12738     return DAG.getBitcast(VT,
12739                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12740   }
12741
12742   // If not vector, then scalar.
12743   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12744   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12745   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12746 }
12747
12748 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12749   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12750   LLVMContext *Context = DAG.getContext();
12751   SDValue Op0 = Op.getOperand(0);
12752   SDValue Op1 = Op.getOperand(1);
12753   SDLoc dl(Op);
12754   MVT VT = Op.getSimpleValueType();
12755   MVT SrcVT = Op1.getSimpleValueType();
12756
12757   // If second operand is smaller, extend it first.
12758   if (SrcVT.bitsLT(VT)) {
12759     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12760     SrcVT = VT;
12761   }
12762   // And if it is bigger, shrink it first.
12763   if (SrcVT.bitsGT(VT)) {
12764     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12765     SrcVT = VT;
12766   }
12767
12768   // At this point the operands and the result should have the same
12769   // type, and that won't be f80 since that is not custom lowered.
12770
12771   const fltSemantics &Sem =
12772       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12773   const unsigned SizeInBits = VT.getSizeInBits();
12774
12775   SmallVector<Constant *, 4> CV(
12776       VT == MVT::f64 ? 2 : 4,
12777       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12778
12779   // First, clear all bits but the sign bit from the second operand (sign).
12780   CV[0] = ConstantFP::get(*Context,
12781                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12782   Constant *C = ConstantVector::get(CV);
12783   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12784   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12785   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12786                               MachinePointerInfo::getConstantPool(),
12787                               false, false, false, 16);
12788   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12789
12790   // Next, clear the sign bit from the first operand (magnitude).
12791   // If it's a constant, we can clear it here.
12792   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12793     APFloat APF = Op0CN->getValueAPF();
12794     // If the magnitude is a positive zero, the sign bit alone is enough.
12795     if (APF.isPosZero())
12796       return SignBit;
12797     APF.clearSign();
12798     CV[0] = ConstantFP::get(*Context, APF);
12799   } else {
12800     CV[0] = ConstantFP::get(
12801         *Context,
12802         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12803   }
12804   C = ConstantVector::get(CV);
12805   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12806   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12807                             MachinePointerInfo::getConstantPool(),
12808                             false, false, false, 16);
12809   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12810   if (!isa<ConstantFPSDNode>(Op0))
12811     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12812
12813   // OR the magnitude value with the sign bit.
12814   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12815 }
12816
12817 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12818   SDValue N0 = Op.getOperand(0);
12819   SDLoc dl(Op);
12820   MVT VT = Op.getSimpleValueType();
12821
12822   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12823   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12824                                   DAG.getConstant(1, dl, VT));
12825   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12826 }
12827
12828 // Check whether an OR'd tree is PTEST-able.
12829 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12830                                       SelectionDAG &DAG) {
12831   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12832
12833   if (!Subtarget->hasSSE41())
12834     return SDValue();
12835
12836   if (!Op->hasOneUse())
12837     return SDValue();
12838
12839   SDNode *N = Op.getNode();
12840   SDLoc DL(N);
12841
12842   SmallVector<SDValue, 8> Opnds;
12843   DenseMap<SDValue, unsigned> VecInMap;
12844   SmallVector<SDValue, 8> VecIns;
12845   EVT VT = MVT::Other;
12846
12847   // Recognize a special case where a vector is casted into wide integer to
12848   // test all 0s.
12849   Opnds.push_back(N->getOperand(0));
12850   Opnds.push_back(N->getOperand(1));
12851
12852   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12853     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12854     // BFS traverse all OR'd operands.
12855     if (I->getOpcode() == ISD::OR) {
12856       Opnds.push_back(I->getOperand(0));
12857       Opnds.push_back(I->getOperand(1));
12858       // Re-evaluate the number of nodes to be traversed.
12859       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12860       continue;
12861     }
12862
12863     // Quit if a non-EXTRACT_VECTOR_ELT
12864     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12865       return SDValue();
12866
12867     // Quit if without a constant index.
12868     SDValue Idx = I->getOperand(1);
12869     if (!isa<ConstantSDNode>(Idx))
12870       return SDValue();
12871
12872     SDValue ExtractedFromVec = I->getOperand(0);
12873     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12874     if (M == VecInMap.end()) {
12875       VT = ExtractedFromVec.getValueType();
12876       // Quit if not 128/256-bit vector.
12877       if (!VT.is128BitVector() && !VT.is256BitVector())
12878         return SDValue();
12879       // Quit if not the same type.
12880       if (VecInMap.begin() != VecInMap.end() &&
12881           VT != VecInMap.begin()->first.getValueType())
12882         return SDValue();
12883       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12884       VecIns.push_back(ExtractedFromVec);
12885     }
12886     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12887   }
12888
12889   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12890          "Not extracted from 128-/256-bit vector.");
12891
12892   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12893
12894   for (DenseMap<SDValue, unsigned>::const_iterator
12895         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12896     // Quit if not all elements are used.
12897     if (I->second != FullMask)
12898       return SDValue();
12899   }
12900
12901   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12902
12903   // Cast all vectors into TestVT for PTEST.
12904   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12905     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12906
12907   // If more than one full vectors are evaluated, OR them first before PTEST.
12908   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12909     // Each iteration will OR 2 nodes and append the result until there is only
12910     // 1 node left, i.e. the final OR'd value of all vectors.
12911     SDValue LHS = VecIns[Slot];
12912     SDValue RHS = VecIns[Slot + 1];
12913     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12914   }
12915
12916   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12917                      VecIns.back(), VecIns.back());
12918 }
12919
12920 /// \brief return true if \c Op has a use that doesn't just read flags.
12921 static bool hasNonFlagsUse(SDValue Op) {
12922   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12923        ++UI) {
12924     SDNode *User = *UI;
12925     unsigned UOpNo = UI.getOperandNo();
12926     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12927       // Look pass truncate.
12928       UOpNo = User->use_begin().getOperandNo();
12929       User = *User->use_begin();
12930     }
12931
12932     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12933         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12934       return true;
12935   }
12936   return false;
12937 }
12938
12939 /// Emit nodes that will be selected as "test Op0,Op0", or something
12940 /// equivalent.
12941 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12942                                     SelectionDAG &DAG) const {
12943   if (Op.getValueType() == MVT::i1) {
12944     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12945     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12946                        DAG.getConstant(0, dl, MVT::i8));
12947   }
12948   // CF and OF aren't always set the way we want. Determine which
12949   // of these we need.
12950   bool NeedCF = false;
12951   bool NeedOF = false;
12952   switch (X86CC) {
12953   default: break;
12954   case X86::COND_A: case X86::COND_AE:
12955   case X86::COND_B: case X86::COND_BE:
12956     NeedCF = true;
12957     break;
12958   case X86::COND_G: case X86::COND_GE:
12959   case X86::COND_L: case X86::COND_LE:
12960   case X86::COND_O: case X86::COND_NO: {
12961     // Check if we really need to set the
12962     // Overflow flag. If NoSignedWrap is present
12963     // that is not actually needed.
12964     switch (Op->getOpcode()) {
12965     case ISD::ADD:
12966     case ISD::SUB:
12967     case ISD::MUL:
12968     case ISD::SHL: {
12969       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12970       if (BinNode->Flags.hasNoSignedWrap())
12971         break;
12972     }
12973     default:
12974       NeedOF = true;
12975       break;
12976     }
12977     break;
12978   }
12979   }
12980   // See if we can use the EFLAGS value from the operand instead of
12981   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12982   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12983   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12984     // Emit a CMP with 0, which is the TEST pattern.
12985     //if (Op.getValueType() == MVT::i1)
12986     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12987     //                     DAG.getConstant(0, MVT::i1));
12988     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12989                        DAG.getConstant(0, dl, Op.getValueType()));
12990   }
12991   unsigned Opcode = 0;
12992   unsigned NumOperands = 0;
12993
12994   // Truncate operations may prevent the merge of the SETCC instruction
12995   // and the arithmetic instruction before it. Attempt to truncate the operands
12996   // of the arithmetic instruction and use a reduced bit-width instruction.
12997   bool NeedTruncation = false;
12998   SDValue ArithOp = Op;
12999   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
13000     SDValue Arith = Op->getOperand(0);
13001     // Both the trunc and the arithmetic op need to have one user each.
13002     if (Arith->hasOneUse())
13003       switch (Arith.getOpcode()) {
13004         default: break;
13005         case ISD::ADD:
13006         case ISD::SUB:
13007         case ISD::AND:
13008         case ISD::OR:
13009         case ISD::XOR: {
13010           NeedTruncation = true;
13011           ArithOp = Arith;
13012         }
13013       }
13014   }
13015
13016   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
13017   // which may be the result of a CAST.  We use the variable 'Op', which is the
13018   // non-casted variable when we check for possible users.
13019   switch (ArithOp.getOpcode()) {
13020   case ISD::ADD:
13021     // Due to an isel shortcoming, be conservative if this add is likely to be
13022     // selected as part of a load-modify-store instruction. When the root node
13023     // in a match is a store, isel doesn't know how to remap non-chain non-flag
13024     // uses of other nodes in the match, such as the ADD in this case. This
13025     // leads to the ADD being left around and reselected, with the result being
13026     // two adds in the output.  Alas, even if none our users are stores, that
13027     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13028     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13029     // climbing the DAG back to the root, and it doesn't seem to be worth the
13030     // effort.
13031     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13032          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13033       if (UI->getOpcode() != ISD::CopyToReg &&
13034           UI->getOpcode() != ISD::SETCC &&
13035           UI->getOpcode() != ISD::STORE)
13036         goto default_case;
13037
13038     if (ConstantSDNode *C =
13039         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13040       // An add of one will be selected as an INC.
13041       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13042         Opcode = X86ISD::INC;
13043         NumOperands = 1;
13044         break;
13045       }
13046
13047       // An add of negative one (subtract of one) will be selected as a DEC.
13048       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13049         Opcode = X86ISD::DEC;
13050         NumOperands = 1;
13051         break;
13052       }
13053     }
13054
13055     // Otherwise use a regular EFLAGS-setting add.
13056     Opcode = X86ISD::ADD;
13057     NumOperands = 2;
13058     break;
13059   case ISD::SHL:
13060   case ISD::SRL:
13061     // If we have a constant logical shift that's only used in a comparison
13062     // against zero turn it into an equivalent AND. This allows turning it into
13063     // a TEST instruction later.
13064     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13065         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13066       EVT VT = Op.getValueType();
13067       unsigned BitWidth = VT.getSizeInBits();
13068       unsigned ShAmt = Op->getConstantOperandVal(1);
13069       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13070         break;
13071       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13072                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13073                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13074       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13075         break;
13076       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13077                                 DAG.getConstant(Mask, dl, VT));
13078       DAG.ReplaceAllUsesWith(Op, New);
13079       Op = New;
13080     }
13081     break;
13082
13083   case ISD::AND:
13084     // If the primary and result isn't used, don't bother using X86ISD::AND,
13085     // because a TEST instruction will be better.
13086     if (!hasNonFlagsUse(Op))
13087       break;
13088     // FALL THROUGH
13089   case ISD::SUB:
13090   case ISD::OR:
13091   case ISD::XOR:
13092     // Due to the ISEL shortcoming noted above, be conservative if this op is
13093     // likely to be selected as part of a load-modify-store instruction.
13094     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13095            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13096       if (UI->getOpcode() == ISD::STORE)
13097         goto default_case;
13098
13099     // Otherwise use a regular EFLAGS-setting instruction.
13100     switch (ArithOp.getOpcode()) {
13101     default: llvm_unreachable("unexpected operator!");
13102     case ISD::SUB: Opcode = X86ISD::SUB; break;
13103     case ISD::XOR: Opcode = X86ISD::XOR; break;
13104     case ISD::AND: Opcode = X86ISD::AND; break;
13105     case ISD::OR: {
13106       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13107         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13108         if (EFLAGS.getNode())
13109           return EFLAGS;
13110       }
13111       Opcode = X86ISD::OR;
13112       break;
13113     }
13114     }
13115
13116     NumOperands = 2;
13117     break;
13118   case X86ISD::ADD:
13119   case X86ISD::SUB:
13120   case X86ISD::INC:
13121   case X86ISD::DEC:
13122   case X86ISD::OR:
13123   case X86ISD::XOR:
13124   case X86ISD::AND:
13125     return SDValue(Op.getNode(), 1);
13126   default:
13127   default_case:
13128     break;
13129   }
13130
13131   // If we found that truncation is beneficial, perform the truncation and
13132   // update 'Op'.
13133   if (NeedTruncation) {
13134     EVT VT = Op.getValueType();
13135     SDValue WideVal = Op->getOperand(0);
13136     EVT WideVT = WideVal.getValueType();
13137     unsigned ConvertedOp = 0;
13138     // Use a target machine opcode to prevent further DAGCombine
13139     // optimizations that may separate the arithmetic operations
13140     // from the setcc node.
13141     switch (WideVal.getOpcode()) {
13142       default: break;
13143       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13144       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13145       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13146       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13147       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13148     }
13149
13150     if (ConvertedOp) {
13151       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13152       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13153         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13154         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13155         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13156       }
13157     }
13158   }
13159
13160   if (Opcode == 0)
13161     // Emit a CMP with 0, which is the TEST pattern.
13162     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13163                        DAG.getConstant(0, dl, Op.getValueType()));
13164
13165   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13166   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13167
13168   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13169   DAG.ReplaceAllUsesWith(Op, New);
13170   return SDValue(New.getNode(), 1);
13171 }
13172
13173 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13174 /// equivalent.
13175 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13176                                    SDLoc dl, SelectionDAG &DAG) const {
13177   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13178     if (C->getAPIntValue() == 0)
13179       return EmitTest(Op0, X86CC, dl, DAG);
13180
13181      if (Op0.getValueType() == MVT::i1)
13182        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13183   }
13184
13185   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13186        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13187     // Do the comparison at i32 if it's smaller, besides the Atom case.
13188     // This avoids subregister aliasing issues. Keep the smaller reference
13189     // if we're optimizing for size, however, as that'll allow better folding
13190     // of memory operations.
13191     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13192         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13193             Attribute::MinSize) &&
13194         !Subtarget->isAtom()) {
13195       unsigned ExtendOp =
13196           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13197       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13198       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13199     }
13200     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13201     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13202     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13203                               Op0, Op1);
13204     return SDValue(Sub.getNode(), 1);
13205   }
13206   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13207 }
13208
13209 /// Convert a comparison if required by the subtarget.
13210 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13211                                                  SelectionDAG &DAG) const {
13212   // If the subtarget does not support the FUCOMI instruction, floating-point
13213   // comparisons have to be converted.
13214   if (Subtarget->hasCMov() ||
13215       Cmp.getOpcode() != X86ISD::CMP ||
13216       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13217       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13218     return Cmp;
13219
13220   // The instruction selector will select an FUCOM instruction instead of
13221   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13222   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13223   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13224   SDLoc dl(Cmp);
13225   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13226   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13227   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13228                             DAG.getConstant(8, dl, MVT::i8));
13229   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13230   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13231 }
13232
13233 /// The minimum architected relative accuracy is 2^-12. We need one
13234 /// Newton-Raphson step to have a good float result (24 bits of precision).
13235 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13236                                             DAGCombinerInfo &DCI,
13237                                             unsigned &RefinementSteps,
13238                                             bool &UseOneConstNR) const {
13239   EVT VT = Op.getValueType();
13240   const char *RecipOp;
13241
13242   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13243   // TODO: Add support for AVX512 (v16f32).
13244   // It is likely not profitable to do this for f64 because a double-precision
13245   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13246   // instructions: convert to single, rsqrtss, convert back to double, refine
13247   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13248   // along with FMA, this could be a throughput win.
13249   if (VT == MVT::f32 && Subtarget->hasSSE1())
13250     RecipOp = "sqrtf";
13251   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13252            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13253     RecipOp = "vec-sqrtf";
13254   else
13255     return SDValue();
13256
13257   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13258   if (!Recips.isEnabled(RecipOp))
13259     return SDValue();
13260
13261   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13262   UseOneConstNR = false;
13263   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13264 }
13265
13266 /// The minimum architected relative accuracy is 2^-12. We need one
13267 /// Newton-Raphson step to have a good float result (24 bits of precision).
13268 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13269                                             DAGCombinerInfo &DCI,
13270                                             unsigned &RefinementSteps) const {
13271   EVT VT = Op.getValueType();
13272   const char *RecipOp;
13273
13274   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13275   // TODO: Add support for AVX512 (v16f32).
13276   // It is likely not profitable to do this for f64 because a double-precision
13277   // reciprocal estimate with refinement on x86 prior to FMA requires
13278   // 15 instructions: convert to single, rcpss, convert back to double, refine
13279   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13280   // along with FMA, this could be a throughput win.
13281   if (VT == MVT::f32 && Subtarget->hasSSE1())
13282     RecipOp = "divf";
13283   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13284            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13285     RecipOp = "vec-divf";
13286   else
13287     return SDValue();
13288
13289   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13290   if (!Recips.isEnabled(RecipOp))
13291     return SDValue();
13292
13293   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13294   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13295 }
13296
13297 /// If we have at least two divisions that use the same divisor, convert to
13298 /// multplication by a reciprocal. This may need to be adjusted for a given
13299 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13300 /// This is because we still need one division to calculate the reciprocal and
13301 /// then we need two multiplies by that reciprocal as replacements for the
13302 /// original divisions.
13303 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13304   return NumUsers > 1;
13305 }
13306
13307 static bool isAllOnes(SDValue V) {
13308   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13309   return C && C->isAllOnesValue();
13310 }
13311
13312 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13313 /// if it's possible.
13314 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13315                                      SDLoc dl, SelectionDAG &DAG) const {
13316   SDValue Op0 = And.getOperand(0);
13317   SDValue Op1 = And.getOperand(1);
13318   if (Op0.getOpcode() == ISD::TRUNCATE)
13319     Op0 = Op0.getOperand(0);
13320   if (Op1.getOpcode() == ISD::TRUNCATE)
13321     Op1 = Op1.getOperand(0);
13322
13323   SDValue LHS, RHS;
13324   if (Op1.getOpcode() == ISD::SHL)
13325     std::swap(Op0, Op1);
13326   if (Op0.getOpcode() == ISD::SHL) {
13327     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13328       if (And00C->getZExtValue() == 1) {
13329         // If we looked past a truncate, check that it's only truncating away
13330         // known zeros.
13331         unsigned BitWidth = Op0.getValueSizeInBits();
13332         unsigned AndBitWidth = And.getValueSizeInBits();
13333         if (BitWidth > AndBitWidth) {
13334           APInt Zeros, Ones;
13335           DAG.computeKnownBits(Op0, Zeros, Ones);
13336           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13337             return SDValue();
13338         }
13339         LHS = Op1;
13340         RHS = Op0.getOperand(1);
13341       }
13342   } else if (Op1.getOpcode() == ISD::Constant) {
13343     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13344     uint64_t AndRHSVal = AndRHS->getZExtValue();
13345     SDValue AndLHS = Op0;
13346
13347     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13348       LHS = AndLHS.getOperand(0);
13349       RHS = AndLHS.getOperand(1);
13350     }
13351
13352     // Use BT if the immediate can't be encoded in a TEST instruction.
13353     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13354       LHS = AndLHS;
13355       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13356     }
13357   }
13358
13359   if (LHS.getNode()) {
13360     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13361     // instruction.  Since the shift amount is in-range-or-undefined, we know
13362     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13363     // the encoding for the i16 version is larger than the i32 version.
13364     // Also promote i16 to i32 for performance / code size reason.
13365     if (LHS.getValueType() == MVT::i8 ||
13366         LHS.getValueType() == MVT::i16)
13367       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13368
13369     // If the operand types disagree, extend the shift amount to match.  Since
13370     // BT ignores high bits (like shifts) we can use anyextend.
13371     if (LHS.getValueType() != RHS.getValueType())
13372       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13373
13374     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13375     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13376     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13377                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13378   }
13379
13380   return SDValue();
13381 }
13382
13383 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13384 /// mask CMPs.
13385 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13386                               SDValue &Op1) {
13387   unsigned SSECC;
13388   bool Swap = false;
13389
13390   // SSE Condition code mapping:
13391   //  0 - EQ
13392   //  1 - LT
13393   //  2 - LE
13394   //  3 - UNORD
13395   //  4 - NEQ
13396   //  5 - NLT
13397   //  6 - NLE
13398   //  7 - ORD
13399   switch (SetCCOpcode) {
13400   default: llvm_unreachable("Unexpected SETCC condition");
13401   case ISD::SETOEQ:
13402   case ISD::SETEQ:  SSECC = 0; break;
13403   case ISD::SETOGT:
13404   case ISD::SETGT:  Swap = true; // Fallthrough
13405   case ISD::SETLT:
13406   case ISD::SETOLT: SSECC = 1; break;
13407   case ISD::SETOGE:
13408   case ISD::SETGE:  Swap = true; // Fallthrough
13409   case ISD::SETLE:
13410   case ISD::SETOLE: SSECC = 2; break;
13411   case ISD::SETUO:  SSECC = 3; break;
13412   case ISD::SETUNE:
13413   case ISD::SETNE:  SSECC = 4; break;
13414   case ISD::SETULE: Swap = true; // Fallthrough
13415   case ISD::SETUGE: SSECC = 5; break;
13416   case ISD::SETULT: Swap = true; // Fallthrough
13417   case ISD::SETUGT: SSECC = 6; break;
13418   case ISD::SETO:   SSECC = 7; break;
13419   case ISD::SETUEQ:
13420   case ISD::SETONE: SSECC = 8; break;
13421   }
13422   if (Swap)
13423     std::swap(Op0, Op1);
13424
13425   return SSECC;
13426 }
13427
13428 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13429 // ones, and then concatenate the result back.
13430 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13431   MVT VT = Op.getSimpleValueType();
13432
13433   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13434          "Unsupported value type for operation");
13435
13436   unsigned NumElems = VT.getVectorNumElements();
13437   SDLoc dl(Op);
13438   SDValue CC = Op.getOperand(2);
13439
13440   // Extract the LHS vectors
13441   SDValue LHS = Op.getOperand(0);
13442   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13443   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13444
13445   // Extract the RHS vectors
13446   SDValue RHS = Op.getOperand(1);
13447   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13448   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13449
13450   // Issue the operation on the smaller types and concatenate the result back
13451   MVT EltVT = VT.getVectorElementType();
13452   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13453   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13454                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13455                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13456 }
13457
13458 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13459   SDValue Op0 = Op.getOperand(0);
13460   SDValue Op1 = Op.getOperand(1);
13461   SDValue CC = Op.getOperand(2);
13462   MVT VT = Op.getSimpleValueType();
13463   SDLoc dl(Op);
13464
13465   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13466          "Unexpected type for boolean compare operation");
13467   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13468   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13469                                DAG.getConstant(-1, dl, VT));
13470   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13471                                DAG.getConstant(-1, dl, VT));
13472   switch (SetCCOpcode) {
13473   default: llvm_unreachable("Unexpected SETCC condition");
13474   case ISD::SETEQ:
13475     // (x == y) -> ~(x ^ y)
13476     return DAG.getNode(ISD::XOR, dl, VT,
13477                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13478                        DAG.getConstant(-1, dl, VT));
13479   case ISD::SETNE:
13480     // (x != y) -> (x ^ y)
13481     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13482   case ISD::SETUGT:
13483   case ISD::SETGT:
13484     // (x > y) -> (x & ~y)
13485     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13486   case ISD::SETULT:
13487   case ISD::SETLT:
13488     // (x < y) -> (~x & y)
13489     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13490   case ISD::SETULE:
13491   case ISD::SETLE:
13492     // (x <= y) -> (~x | y)
13493     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13494   case ISD::SETUGE:
13495   case ISD::SETGE:
13496     // (x >=y) -> (x | ~y)
13497     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13498   }
13499 }
13500
13501 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13502                                      const X86Subtarget *Subtarget) {
13503   SDValue Op0 = Op.getOperand(0);
13504   SDValue Op1 = Op.getOperand(1);
13505   SDValue CC = Op.getOperand(2);
13506   MVT VT = Op.getSimpleValueType();
13507   SDLoc dl(Op);
13508
13509   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13510          Op.getValueType().getScalarType() == MVT::i1 &&
13511          "Cannot set masked compare for this operation");
13512
13513   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13514   unsigned  Opc = 0;
13515   bool Unsigned = false;
13516   bool Swap = false;
13517   unsigned SSECC;
13518   switch (SetCCOpcode) {
13519   default: llvm_unreachable("Unexpected SETCC condition");
13520   case ISD::SETNE:  SSECC = 4; break;
13521   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13522   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13523   case ISD::SETLT:  Swap = true; //fall-through
13524   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13525   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13526   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13527   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13528   case ISD::SETULE: Unsigned = true; //fall-through
13529   case ISD::SETLE:  SSECC = 2; break;
13530   }
13531
13532   if (Swap)
13533     std::swap(Op0, Op1);
13534   if (Opc)
13535     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13536   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13537   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13538                      DAG.getConstant(SSECC, dl, MVT::i8));
13539 }
13540
13541 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13542 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13543 /// return an empty value.
13544 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13545 {
13546   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13547   if (!BV)
13548     return SDValue();
13549
13550   MVT VT = Op1.getSimpleValueType();
13551   MVT EVT = VT.getVectorElementType();
13552   unsigned n = VT.getVectorNumElements();
13553   SmallVector<SDValue, 8> ULTOp1;
13554
13555   for (unsigned i = 0; i < n; ++i) {
13556     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13557     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13558       return SDValue();
13559
13560     // Avoid underflow.
13561     APInt Val = Elt->getAPIntValue();
13562     if (Val == 0)
13563       return SDValue();
13564
13565     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13566   }
13567
13568   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13569 }
13570
13571 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13572                            SelectionDAG &DAG) {
13573   SDValue Op0 = Op.getOperand(0);
13574   SDValue Op1 = Op.getOperand(1);
13575   SDValue CC = Op.getOperand(2);
13576   MVT VT = Op.getSimpleValueType();
13577   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13578   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13579   SDLoc dl(Op);
13580
13581   if (isFP) {
13582 #ifndef NDEBUG
13583     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13584     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13585 #endif
13586
13587     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13588     unsigned Opc = X86ISD::CMPP;
13589     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13590       assert(VT.getVectorNumElements() <= 16);
13591       Opc = X86ISD::CMPM;
13592     }
13593     // In the two special cases we can't handle, emit two comparisons.
13594     if (SSECC == 8) {
13595       unsigned CC0, CC1;
13596       unsigned CombineOpc;
13597       if (SetCCOpcode == ISD::SETUEQ) {
13598         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13599       } else {
13600         assert(SetCCOpcode == ISD::SETONE);
13601         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13602       }
13603
13604       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13605                                  DAG.getConstant(CC0, dl, MVT::i8));
13606       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13607                                  DAG.getConstant(CC1, dl, MVT::i8));
13608       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13609     }
13610     // Handle all other FP comparisons here.
13611     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13612                        DAG.getConstant(SSECC, dl, MVT::i8));
13613   }
13614
13615   // Break 256-bit integer vector compare into smaller ones.
13616   if (VT.is256BitVector() && !Subtarget->hasInt256())
13617     return Lower256IntVSETCC(Op, DAG);
13618
13619   EVT OpVT = Op1.getValueType();
13620   if (OpVT.getVectorElementType() == MVT::i1)
13621     return LowerBoolVSETCC_AVX512(Op, DAG);
13622
13623   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13624   if (Subtarget->hasAVX512()) {
13625     if (Op1.getValueType().is512BitVector() ||
13626         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13627         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13628       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13629
13630     // In AVX-512 architecture setcc returns mask with i1 elements,
13631     // But there is no compare instruction for i8 and i16 elements in KNL.
13632     // We are not talking about 512-bit operands in this case, these
13633     // types are illegal.
13634     if (MaskResult &&
13635         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13636          OpVT.getVectorElementType().getSizeInBits() >= 8))
13637       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13638                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13639   }
13640
13641   // We are handling one of the integer comparisons here.  Since SSE only has
13642   // GT and EQ comparisons for integer, swapping operands and multiple
13643   // operations may be required for some comparisons.
13644   unsigned Opc;
13645   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13646   bool Subus = false;
13647
13648   switch (SetCCOpcode) {
13649   default: llvm_unreachable("Unexpected SETCC condition");
13650   case ISD::SETNE:  Invert = true;
13651   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13652   case ISD::SETLT:  Swap = true;
13653   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13654   case ISD::SETGE:  Swap = true;
13655   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13656                     Invert = true; break;
13657   case ISD::SETULT: Swap = true;
13658   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13659                     FlipSigns = true; break;
13660   case ISD::SETUGE: Swap = true;
13661   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13662                     FlipSigns = true; Invert = true; break;
13663   }
13664
13665   // Special case: Use min/max operations for SETULE/SETUGE
13666   MVT VET = VT.getVectorElementType();
13667   bool hasMinMax =
13668        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13669     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13670
13671   if (hasMinMax) {
13672     switch (SetCCOpcode) {
13673     default: break;
13674     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13675     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13676     }
13677
13678     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13679   }
13680
13681   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13682   if (!MinMax && hasSubus) {
13683     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13684     // Op0 u<= Op1:
13685     //   t = psubus Op0, Op1
13686     //   pcmpeq t, <0..0>
13687     switch (SetCCOpcode) {
13688     default: break;
13689     case ISD::SETULT: {
13690       // If the comparison is against a constant we can turn this into a
13691       // setule.  With psubus, setule does not require a swap.  This is
13692       // beneficial because the constant in the register is no longer
13693       // destructed as the destination so it can be hoisted out of a loop.
13694       // Only do this pre-AVX since vpcmp* is no longer destructive.
13695       if (Subtarget->hasAVX())
13696         break;
13697       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13698       if (ULEOp1.getNode()) {
13699         Op1 = ULEOp1;
13700         Subus = true; Invert = false; Swap = false;
13701       }
13702       break;
13703     }
13704     // Psubus is better than flip-sign because it requires no inversion.
13705     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13706     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13707     }
13708
13709     if (Subus) {
13710       Opc = X86ISD::SUBUS;
13711       FlipSigns = false;
13712     }
13713   }
13714
13715   if (Swap)
13716     std::swap(Op0, Op1);
13717
13718   // Check that the operation in question is available (most are plain SSE2,
13719   // but PCMPGTQ and PCMPEQQ have different requirements).
13720   if (VT == MVT::v2i64) {
13721     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13722       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13723
13724       // First cast everything to the right type.
13725       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13726       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13727
13728       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13729       // bits of the inputs before performing those operations. The lower
13730       // compare is always unsigned.
13731       SDValue SB;
13732       if (FlipSigns) {
13733         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13734       } else {
13735         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13736         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13737         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13738                          Sign, Zero, Sign, Zero);
13739       }
13740       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13741       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13742
13743       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13744       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13745       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13746
13747       // Create masks for only the low parts/high parts of the 64 bit integers.
13748       static const int MaskHi[] = { 1, 1, 3, 3 };
13749       static const int MaskLo[] = { 0, 0, 2, 2 };
13750       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13751       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13752       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13753
13754       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13755       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13756
13757       if (Invert)
13758         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13759
13760       return DAG.getBitcast(VT, Result);
13761     }
13762
13763     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13764       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13765       // pcmpeqd + pshufd + pand.
13766       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13767
13768       // First cast everything to the right type.
13769       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13770       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13771
13772       // Do the compare.
13773       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13774
13775       // Make sure the lower and upper halves are both all-ones.
13776       static const int Mask[] = { 1, 0, 3, 2 };
13777       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13778       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13779
13780       if (Invert)
13781         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13782
13783       return DAG.getBitcast(VT, Result);
13784     }
13785   }
13786
13787   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13788   // bits of the inputs before performing those operations.
13789   if (FlipSigns) {
13790     EVT EltVT = VT.getVectorElementType();
13791     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13792                                  VT);
13793     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13794     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13795   }
13796
13797   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13798
13799   // If the logical-not of the result is required, perform that now.
13800   if (Invert)
13801     Result = DAG.getNOT(dl, Result, VT);
13802
13803   if (MinMax)
13804     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13805
13806   if (Subus)
13807     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13808                          getZeroVector(VT, Subtarget, DAG, dl));
13809
13810   return Result;
13811 }
13812
13813 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13814
13815   MVT VT = Op.getSimpleValueType();
13816
13817   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13818
13819   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13820          && "SetCC type must be 8-bit or 1-bit integer");
13821   SDValue Op0 = Op.getOperand(0);
13822   SDValue Op1 = Op.getOperand(1);
13823   SDLoc dl(Op);
13824   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13825
13826   // Optimize to BT if possible.
13827   // Lower (X & (1 << N)) == 0 to BT(X, N).
13828   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13829   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13830   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13831       Op1.getOpcode() == ISD::Constant &&
13832       cast<ConstantSDNode>(Op1)->isNullValue() &&
13833       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13834     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13835     if (NewSetCC.getNode()) {
13836       if (VT == MVT::i1)
13837         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13838       return NewSetCC;
13839     }
13840   }
13841
13842   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13843   // these.
13844   if (Op1.getOpcode() == ISD::Constant &&
13845       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13846        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13847       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13848
13849     // If the input is a setcc, then reuse the input setcc or use a new one with
13850     // the inverted condition.
13851     if (Op0.getOpcode() == X86ISD::SETCC) {
13852       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13853       bool Invert = (CC == ISD::SETNE) ^
13854         cast<ConstantSDNode>(Op1)->isNullValue();
13855       if (!Invert)
13856         return Op0;
13857
13858       CCode = X86::GetOppositeBranchCondition(CCode);
13859       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13860                                   DAG.getConstant(CCode, dl, MVT::i8),
13861                                   Op0.getOperand(1));
13862       if (VT == MVT::i1)
13863         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13864       return SetCC;
13865     }
13866   }
13867   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13868       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13869       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13870
13871     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13872     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13873   }
13874
13875   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13876   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13877   if (X86CC == X86::COND_INVALID)
13878     return SDValue();
13879
13880   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13881   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13882   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13883                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13884   if (VT == MVT::i1)
13885     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13886   return SetCC;
13887 }
13888
13889 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13890 static bool isX86LogicalCmp(SDValue Op) {
13891   unsigned Opc = Op.getNode()->getOpcode();
13892   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13893       Opc == X86ISD::SAHF)
13894     return true;
13895   if (Op.getResNo() == 1 &&
13896       (Opc == X86ISD::ADD ||
13897        Opc == X86ISD::SUB ||
13898        Opc == X86ISD::ADC ||
13899        Opc == X86ISD::SBB ||
13900        Opc == X86ISD::SMUL ||
13901        Opc == X86ISD::UMUL ||
13902        Opc == X86ISD::INC ||
13903        Opc == X86ISD::DEC ||
13904        Opc == X86ISD::OR ||
13905        Opc == X86ISD::XOR ||
13906        Opc == X86ISD::AND))
13907     return true;
13908
13909   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13910     return true;
13911
13912   return false;
13913 }
13914
13915 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13916   if (V.getOpcode() != ISD::TRUNCATE)
13917     return false;
13918
13919   SDValue VOp0 = V.getOperand(0);
13920   unsigned InBits = VOp0.getValueSizeInBits();
13921   unsigned Bits = V.getValueSizeInBits();
13922   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13923 }
13924
13925 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13926   bool addTest = true;
13927   SDValue Cond  = Op.getOperand(0);
13928   SDValue Op1 = Op.getOperand(1);
13929   SDValue Op2 = Op.getOperand(2);
13930   SDLoc DL(Op);
13931   EVT VT = Op1.getValueType();
13932   SDValue CC;
13933
13934   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13935   // are available or VBLENDV if AVX is available.
13936   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13937   if (Cond.getOpcode() == ISD::SETCC &&
13938       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13939        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13940       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13941     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13942     int SSECC = translateX86FSETCC(
13943         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13944
13945     if (SSECC != 8) {
13946       if (Subtarget->hasAVX512()) {
13947         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13948                                   DAG.getConstant(SSECC, DL, MVT::i8));
13949         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13950       }
13951
13952       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13953                                 DAG.getConstant(SSECC, DL, MVT::i8));
13954
13955       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13956       // of 3 logic instructions for size savings and potentially speed.
13957       // Unfortunately, there is no scalar form of VBLENDV.
13958
13959       // If either operand is a constant, don't try this. We can expect to
13960       // optimize away at least one of the logic instructions later in that
13961       // case, so that sequence would be faster than a variable blend.
13962
13963       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13964       // uses XMM0 as the selection register. That may need just as many
13965       // instructions as the AND/ANDN/OR sequence due to register moves, so
13966       // don't bother.
13967
13968       if (Subtarget->hasAVX() &&
13969           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13970
13971         // Convert to vectors, do a VSELECT, and convert back to scalar.
13972         // All of the conversions should be optimized away.
13973
13974         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13975         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13976         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13977         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13978
13979         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13980         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13981
13982         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13983
13984         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13985                            VSel, DAG.getIntPtrConstant(0, DL));
13986       }
13987       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13988       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13989       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13990     }
13991   }
13992
13993   if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13994     SDValue Op1Scalar;
13995     if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13996       Op1Scalar = ConvertI1VectorToInteger(Op1, DAG);
13997     else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13998       Op1Scalar = Op1.getOperand(0);
13999     SDValue Op2Scalar;
14000     if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
14001       Op2Scalar = ConvertI1VectorToInteger(Op2, DAG);
14002     else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
14003       Op2Scalar = Op2.getOperand(0);
14004     if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
14005       SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
14006                                       Op1Scalar.getValueType(),
14007                                       Cond, Op1Scalar, Op2Scalar);
14008       if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
14009         return DAG.getBitcast(VT, newSelect);
14010       SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
14011       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
14012                          DAG.getIntPtrConstant(0, DL));
14013     }
14014   }
14015
14016   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
14017     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
14018     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14019                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
14020     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
14021                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
14022     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
14023                                     Cond, Op1, Op2);
14024     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
14025   }
14026
14027   if (Cond.getOpcode() == ISD::SETCC) {
14028     SDValue NewCond = LowerSETCC(Cond, DAG);
14029     if (NewCond.getNode())
14030       Cond = NewCond;
14031   }
14032
14033   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14034   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14035   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14036   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14037   if (Cond.getOpcode() == X86ISD::SETCC &&
14038       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14039       isZero(Cond.getOperand(1).getOperand(1))) {
14040     SDValue Cmp = Cond.getOperand(1);
14041
14042     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14043
14044     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14045         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14046       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14047
14048       SDValue CmpOp0 = Cmp.getOperand(0);
14049       // Apply further optimizations for special cases
14050       // (select (x != 0), -1, 0) -> neg & sbb
14051       // (select (x == 0), 0, -1) -> neg & sbb
14052       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14053         if (YC->isNullValue() &&
14054             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14055           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14056           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14057                                     DAG.getConstant(0, DL,
14058                                                     CmpOp0.getValueType()),
14059                                     CmpOp0);
14060           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14061                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14062                                     SDValue(Neg.getNode(), 1));
14063           return Res;
14064         }
14065
14066       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14067                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14068       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14069
14070       SDValue Res =   // Res = 0 or -1.
14071         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14072                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14073
14074       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14075         Res = DAG.getNOT(DL, Res, Res.getValueType());
14076
14077       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14078       if (!N2C || !N2C->isNullValue())
14079         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14080       return Res;
14081     }
14082   }
14083
14084   // Look past (and (setcc_carry (cmp ...)), 1).
14085   if (Cond.getOpcode() == ISD::AND &&
14086       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14087     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14088     if (C && C->getAPIntValue() == 1)
14089       Cond = Cond.getOperand(0);
14090   }
14091
14092   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14093   // setting operand in place of the X86ISD::SETCC.
14094   unsigned CondOpcode = Cond.getOpcode();
14095   if (CondOpcode == X86ISD::SETCC ||
14096       CondOpcode == X86ISD::SETCC_CARRY) {
14097     CC = Cond.getOperand(0);
14098
14099     SDValue Cmp = Cond.getOperand(1);
14100     unsigned Opc = Cmp.getOpcode();
14101     MVT VT = Op.getSimpleValueType();
14102
14103     bool IllegalFPCMov = false;
14104     if (VT.isFloatingPoint() && !VT.isVector() &&
14105         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14106       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14107
14108     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14109         Opc == X86ISD::BT) { // FIXME
14110       Cond = Cmp;
14111       addTest = false;
14112     }
14113   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14114              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14115              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14116               Cond.getOperand(0).getValueType() != MVT::i8)) {
14117     SDValue LHS = Cond.getOperand(0);
14118     SDValue RHS = Cond.getOperand(1);
14119     unsigned X86Opcode;
14120     unsigned X86Cond;
14121     SDVTList VTs;
14122     switch (CondOpcode) {
14123     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14124     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14125     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14126     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14127     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14128     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14129     default: llvm_unreachable("unexpected overflowing operator");
14130     }
14131     if (CondOpcode == ISD::UMULO)
14132       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14133                           MVT::i32);
14134     else
14135       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14136
14137     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14138
14139     if (CondOpcode == ISD::UMULO)
14140       Cond = X86Op.getValue(2);
14141     else
14142       Cond = X86Op.getValue(1);
14143
14144     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14145     addTest = false;
14146   }
14147
14148   if (addTest) {
14149     // Look pass the truncate if the high bits are known zero.
14150     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14151         Cond = Cond.getOperand(0);
14152
14153     // We know the result of AND is compared against zero. Try to match
14154     // it to BT.
14155     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14156       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14157       if (NewSetCC.getNode()) {
14158         CC = NewSetCC.getOperand(0);
14159         Cond = NewSetCC.getOperand(1);
14160         addTest = false;
14161       }
14162     }
14163   }
14164
14165   if (addTest) {
14166     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14167     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14168   }
14169
14170   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14171   // a <  b ?  0 : -1 -> RES = setcc_carry
14172   // a >= b ? -1 :  0 -> RES = setcc_carry
14173   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14174   if (Cond.getOpcode() == X86ISD::SUB) {
14175     Cond = ConvertCmpIfNecessary(Cond, DAG);
14176     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14177
14178     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14179         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14180       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14181                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14182                                 Cond);
14183       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14184         return DAG.getNOT(DL, Res, Res.getValueType());
14185       return Res;
14186     }
14187   }
14188
14189   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14190   // widen the cmov and push the truncate through. This avoids introducing a new
14191   // branch during isel and doesn't add any extensions.
14192   if (Op.getValueType() == MVT::i8 &&
14193       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14194     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14195     if (T1.getValueType() == T2.getValueType() &&
14196         // Blacklist CopyFromReg to avoid partial register stalls.
14197         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14198       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14199       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14200       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14201     }
14202   }
14203
14204   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14205   // condition is true.
14206   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14207   SDValue Ops[] = { Op2, Op1, CC, Cond };
14208   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14209 }
14210
14211 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14212                                        const X86Subtarget *Subtarget,
14213                                        SelectionDAG &DAG) {
14214   MVT VT = Op->getSimpleValueType(0);
14215   SDValue In = Op->getOperand(0);
14216   MVT InVT = In.getSimpleValueType();
14217   MVT VTElt = VT.getVectorElementType();
14218   MVT InVTElt = InVT.getVectorElementType();
14219   SDLoc dl(Op);
14220
14221   // SKX processor
14222   if ((InVTElt == MVT::i1) &&
14223       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14224         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14225
14226        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14227         VTElt.getSizeInBits() <= 16)) ||
14228
14229        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14230         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14231
14232        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14233         VTElt.getSizeInBits() >= 32))))
14234     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14235
14236   unsigned int NumElts = VT.getVectorNumElements();
14237
14238   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14239     return SDValue();
14240
14241   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14242     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14243       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14244     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14245   }
14246
14247   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14248   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14249   SDValue NegOne =
14250    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14251                    ExtVT);
14252   SDValue Zero =
14253    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14254
14255   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14256   if (VT.is512BitVector())
14257     return V;
14258   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14259 }
14260
14261 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14262                                              const X86Subtarget *Subtarget,
14263                                              SelectionDAG &DAG) {
14264   SDValue In = Op->getOperand(0);
14265   MVT VT = Op->getSimpleValueType(0);
14266   MVT InVT = In.getSimpleValueType();
14267   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14268
14269   MVT InSVT = InVT.getScalarType();
14270   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14271
14272   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14273     return SDValue();
14274   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14275     return SDValue();
14276
14277   SDLoc dl(Op);
14278
14279   // SSE41 targets can use the pmovsx* instructions directly.
14280   if (Subtarget->hasSSE41())
14281     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14282
14283   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14284   SDValue Curr = In;
14285   MVT CurrVT = InVT;
14286
14287   // As SRAI is only available on i16/i32 types, we expand only up to i32
14288   // and handle i64 separately.
14289   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14290     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14291     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14292     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14293     Curr = DAG.getBitcast(CurrVT, Curr);
14294   }
14295
14296   SDValue SignExt = Curr;
14297   if (CurrVT != InVT) {
14298     unsigned SignExtShift =
14299         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14300     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14301                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14302   }
14303
14304   if (CurrVT == VT)
14305     return SignExt;
14306
14307   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14308     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14309                                DAG.getConstant(31, dl, MVT::i8));
14310     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14311     return DAG.getBitcast(VT, Ext);
14312   }
14313
14314   return SDValue();
14315 }
14316
14317 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14318                                 SelectionDAG &DAG) {
14319   MVT VT = Op->getSimpleValueType(0);
14320   SDValue In = Op->getOperand(0);
14321   MVT InVT = In.getSimpleValueType();
14322   SDLoc dl(Op);
14323
14324   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14325     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14326
14327   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14328       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14329       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14330     return SDValue();
14331
14332   if (Subtarget->hasInt256())
14333     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14334
14335   // Optimize vectors in AVX mode
14336   // Sign extend  v8i16 to v8i32 and
14337   //              v4i32 to v4i64
14338   //
14339   // Divide input vector into two parts
14340   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14341   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14342   // concat the vectors to original VT
14343
14344   unsigned NumElems = InVT.getVectorNumElements();
14345   SDValue Undef = DAG.getUNDEF(InVT);
14346
14347   SmallVector<int,8> ShufMask1(NumElems, -1);
14348   for (unsigned i = 0; i != NumElems/2; ++i)
14349     ShufMask1[i] = i;
14350
14351   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14352
14353   SmallVector<int,8> ShufMask2(NumElems, -1);
14354   for (unsigned i = 0; i != NumElems/2; ++i)
14355     ShufMask2[i] = i + NumElems/2;
14356
14357   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14358
14359   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14360                                 VT.getVectorNumElements()/2);
14361
14362   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14363   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14364
14365   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14366 }
14367
14368 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14369 // may emit an illegal shuffle but the expansion is still better than scalar
14370 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14371 // we'll emit a shuffle and a arithmetic shift.
14372 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14373 // TODO: It is possible to support ZExt by zeroing the undef values during
14374 // the shuffle phase or after the shuffle.
14375 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14376                                  SelectionDAG &DAG) {
14377   MVT RegVT = Op.getSimpleValueType();
14378   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14379   assert(RegVT.isInteger() &&
14380          "We only custom lower integer vector sext loads.");
14381
14382   // Nothing useful we can do without SSE2 shuffles.
14383   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14384
14385   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14386   SDLoc dl(Ld);
14387   EVT MemVT = Ld->getMemoryVT();
14388   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14389   unsigned RegSz = RegVT.getSizeInBits();
14390
14391   ISD::LoadExtType Ext = Ld->getExtensionType();
14392
14393   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14394          && "Only anyext and sext are currently implemented.");
14395   assert(MemVT != RegVT && "Cannot extend to the same type");
14396   assert(MemVT.isVector() && "Must load a vector from memory");
14397
14398   unsigned NumElems = RegVT.getVectorNumElements();
14399   unsigned MemSz = MemVT.getSizeInBits();
14400   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14401
14402   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14403     // The only way in which we have a legal 256-bit vector result but not the
14404     // integer 256-bit operations needed to directly lower a sextload is if we
14405     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14406     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14407     // correctly legalized. We do this late to allow the canonical form of
14408     // sextload to persist throughout the rest of the DAG combiner -- it wants
14409     // to fold together any extensions it can, and so will fuse a sign_extend
14410     // of an sextload into a sextload targeting a wider value.
14411     SDValue Load;
14412     if (MemSz == 128) {
14413       // Just switch this to a normal load.
14414       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14415                                        "it must be a legal 128-bit vector "
14416                                        "type!");
14417       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14418                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14419                   Ld->isInvariant(), Ld->getAlignment());
14420     } else {
14421       assert(MemSz < 128 &&
14422              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14423       // Do an sext load to a 128-bit vector type. We want to use the same
14424       // number of elements, but elements half as wide. This will end up being
14425       // recursively lowered by this routine, but will succeed as we definitely
14426       // have all the necessary features if we're using AVX1.
14427       EVT HalfEltVT =
14428           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14429       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14430       Load =
14431           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14432                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14433                          Ld->isNonTemporal(), Ld->isInvariant(),
14434                          Ld->getAlignment());
14435     }
14436
14437     // Replace chain users with the new chain.
14438     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14439     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14440
14441     // Finally, do a normal sign-extend to the desired register.
14442     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14443   }
14444
14445   // All sizes must be a power of two.
14446   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14447          "Non-power-of-two elements are not custom lowered!");
14448
14449   // Attempt to load the original value using scalar loads.
14450   // Find the largest scalar type that divides the total loaded size.
14451   MVT SclrLoadTy = MVT::i8;
14452   for (MVT Tp : MVT::integer_valuetypes()) {
14453     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14454       SclrLoadTy = Tp;
14455     }
14456   }
14457
14458   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14459   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14460       (64 <= MemSz))
14461     SclrLoadTy = MVT::f64;
14462
14463   // Calculate the number of scalar loads that we need to perform
14464   // in order to load our vector from memory.
14465   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14466
14467   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14468          "Can only lower sext loads with a single scalar load!");
14469
14470   unsigned loadRegZize = RegSz;
14471   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14472     loadRegZize = 128;
14473
14474   // Represent our vector as a sequence of elements which are the
14475   // largest scalar that we can load.
14476   EVT LoadUnitVecVT = EVT::getVectorVT(
14477       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14478
14479   // Represent the data using the same element type that is stored in
14480   // memory. In practice, we ''widen'' MemVT.
14481   EVT WideVecVT =
14482       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14483                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14484
14485   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14486          "Invalid vector type");
14487
14488   // We can't shuffle using an illegal type.
14489   assert(TLI.isTypeLegal(WideVecVT) &&
14490          "We only lower types that form legal widened vector types");
14491
14492   SmallVector<SDValue, 8> Chains;
14493   SDValue Ptr = Ld->getBasePtr();
14494   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14495                                       TLI.getPointerTy(DAG.getDataLayout()));
14496   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14497
14498   for (unsigned i = 0; i < NumLoads; ++i) {
14499     // Perform a single load.
14500     SDValue ScalarLoad =
14501         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14502                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14503                     Ld->getAlignment());
14504     Chains.push_back(ScalarLoad.getValue(1));
14505     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14506     // another round of DAGCombining.
14507     if (i == 0)
14508       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14509     else
14510       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14511                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14512
14513     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14514   }
14515
14516   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14517
14518   // Bitcast the loaded value to a vector of the original element type, in
14519   // the size of the target vector type.
14520   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14521   unsigned SizeRatio = RegSz / MemSz;
14522
14523   if (Ext == ISD::SEXTLOAD) {
14524     // If we have SSE4.1, we can directly emit a VSEXT node.
14525     if (Subtarget->hasSSE41()) {
14526       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14527       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14528       return Sext;
14529     }
14530
14531     // Otherwise we'll shuffle the small elements in the high bits of the
14532     // larger type and perform an arithmetic shift. If the shift is not legal
14533     // it's better to scalarize.
14534     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14535            "We can't implement a sext load without an arithmetic right shift!");
14536
14537     // Redistribute the loaded elements into the different locations.
14538     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14539     for (unsigned i = 0; i != NumElems; ++i)
14540       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14541
14542     SDValue Shuff = DAG.getVectorShuffle(
14543         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14544
14545     Shuff = DAG.getBitcast(RegVT, Shuff);
14546
14547     // Build the arithmetic shift.
14548     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14549                    MemVT.getVectorElementType().getSizeInBits();
14550     Shuff =
14551         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14552                     DAG.getConstant(Amt, dl, RegVT));
14553
14554     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14555     return Shuff;
14556   }
14557
14558   // Redistribute the loaded elements into the different locations.
14559   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14560   for (unsigned i = 0; i != NumElems; ++i)
14561     ShuffleVec[i * SizeRatio] = i;
14562
14563   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14564                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14565
14566   // Bitcast to the requested type.
14567   Shuff = DAG.getBitcast(RegVT, Shuff);
14568   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14569   return Shuff;
14570 }
14571
14572 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14573 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14574 // from the AND / OR.
14575 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14576   Opc = Op.getOpcode();
14577   if (Opc != ISD::OR && Opc != ISD::AND)
14578     return false;
14579   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14580           Op.getOperand(0).hasOneUse() &&
14581           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14582           Op.getOperand(1).hasOneUse());
14583 }
14584
14585 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14586 // 1 and that the SETCC node has a single use.
14587 static bool isXor1OfSetCC(SDValue Op) {
14588   if (Op.getOpcode() != ISD::XOR)
14589     return false;
14590   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14591   if (N1C && N1C->getAPIntValue() == 1) {
14592     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14593       Op.getOperand(0).hasOneUse();
14594   }
14595   return false;
14596 }
14597
14598 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14599   bool addTest = true;
14600   SDValue Chain = Op.getOperand(0);
14601   SDValue Cond  = Op.getOperand(1);
14602   SDValue Dest  = Op.getOperand(2);
14603   SDLoc dl(Op);
14604   SDValue CC;
14605   bool Inverted = false;
14606
14607   if (Cond.getOpcode() == ISD::SETCC) {
14608     // Check for setcc([su]{add,sub,mul}o == 0).
14609     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14610         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14611         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14612         Cond.getOperand(0).getResNo() == 1 &&
14613         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14614          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14615          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14616          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14617          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14618          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14619       Inverted = true;
14620       Cond = Cond.getOperand(0);
14621     } else {
14622       SDValue NewCond = LowerSETCC(Cond, DAG);
14623       if (NewCond.getNode())
14624         Cond = NewCond;
14625     }
14626   }
14627 #if 0
14628   // FIXME: LowerXALUO doesn't handle these!!
14629   else if (Cond.getOpcode() == X86ISD::ADD  ||
14630            Cond.getOpcode() == X86ISD::SUB  ||
14631            Cond.getOpcode() == X86ISD::SMUL ||
14632            Cond.getOpcode() == X86ISD::UMUL)
14633     Cond = LowerXALUO(Cond, DAG);
14634 #endif
14635
14636   // Look pass (and (setcc_carry (cmp ...)), 1).
14637   if (Cond.getOpcode() == ISD::AND &&
14638       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14639     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14640     if (C && C->getAPIntValue() == 1)
14641       Cond = Cond.getOperand(0);
14642   }
14643
14644   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14645   // setting operand in place of the X86ISD::SETCC.
14646   unsigned CondOpcode = Cond.getOpcode();
14647   if (CondOpcode == X86ISD::SETCC ||
14648       CondOpcode == X86ISD::SETCC_CARRY) {
14649     CC = Cond.getOperand(0);
14650
14651     SDValue Cmp = Cond.getOperand(1);
14652     unsigned Opc = Cmp.getOpcode();
14653     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14654     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14655       Cond = Cmp;
14656       addTest = false;
14657     } else {
14658       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14659       default: break;
14660       case X86::COND_O:
14661       case X86::COND_B:
14662         // These can only come from an arithmetic instruction with overflow,
14663         // e.g. SADDO, UADDO.
14664         Cond = Cond.getNode()->getOperand(1);
14665         addTest = false;
14666         break;
14667       }
14668     }
14669   }
14670   CondOpcode = Cond.getOpcode();
14671   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14672       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14673       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14674        Cond.getOperand(0).getValueType() != MVT::i8)) {
14675     SDValue LHS = Cond.getOperand(0);
14676     SDValue RHS = Cond.getOperand(1);
14677     unsigned X86Opcode;
14678     unsigned X86Cond;
14679     SDVTList VTs;
14680     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14681     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14682     // X86ISD::INC).
14683     switch (CondOpcode) {
14684     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14685     case ISD::SADDO:
14686       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14687         if (C->isOne()) {
14688           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14689           break;
14690         }
14691       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14692     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14693     case ISD::SSUBO:
14694       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14695         if (C->isOne()) {
14696           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14697           break;
14698         }
14699       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14700     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14701     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14702     default: llvm_unreachable("unexpected overflowing operator");
14703     }
14704     if (Inverted)
14705       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14706     if (CondOpcode == ISD::UMULO)
14707       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14708                           MVT::i32);
14709     else
14710       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14711
14712     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14713
14714     if (CondOpcode == ISD::UMULO)
14715       Cond = X86Op.getValue(2);
14716     else
14717       Cond = X86Op.getValue(1);
14718
14719     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14720     addTest = false;
14721   } else {
14722     unsigned CondOpc;
14723     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14724       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14725       if (CondOpc == ISD::OR) {
14726         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14727         // two branches instead of an explicit OR instruction with a
14728         // separate test.
14729         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14730             isX86LogicalCmp(Cmp)) {
14731           CC = Cond.getOperand(0).getOperand(0);
14732           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14733                               Chain, Dest, CC, Cmp);
14734           CC = Cond.getOperand(1).getOperand(0);
14735           Cond = Cmp;
14736           addTest = false;
14737         }
14738       } else { // ISD::AND
14739         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14740         // two branches instead of an explicit AND instruction with a
14741         // separate test. However, we only do this if this block doesn't
14742         // have a fall-through edge, because this requires an explicit
14743         // jmp when the condition is false.
14744         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14745             isX86LogicalCmp(Cmp) &&
14746             Op.getNode()->hasOneUse()) {
14747           X86::CondCode CCode =
14748             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14749           CCode = X86::GetOppositeBranchCondition(CCode);
14750           CC = DAG.getConstant(CCode, dl, MVT::i8);
14751           SDNode *User = *Op.getNode()->use_begin();
14752           // Look for an unconditional branch following this conditional branch.
14753           // We need this because we need to reverse the successors in order
14754           // to implement FCMP_OEQ.
14755           if (User->getOpcode() == ISD::BR) {
14756             SDValue FalseBB = User->getOperand(1);
14757             SDNode *NewBR =
14758               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14759             assert(NewBR == User);
14760             (void)NewBR;
14761             Dest = FalseBB;
14762
14763             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14764                                 Chain, Dest, CC, Cmp);
14765             X86::CondCode CCode =
14766               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14767             CCode = X86::GetOppositeBranchCondition(CCode);
14768             CC = DAG.getConstant(CCode, dl, MVT::i8);
14769             Cond = Cmp;
14770             addTest = false;
14771           }
14772         }
14773       }
14774     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14775       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14776       // It should be transformed during dag combiner except when the condition
14777       // is set by a arithmetics with overflow node.
14778       X86::CondCode CCode =
14779         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14780       CCode = X86::GetOppositeBranchCondition(CCode);
14781       CC = DAG.getConstant(CCode, dl, MVT::i8);
14782       Cond = Cond.getOperand(0).getOperand(1);
14783       addTest = false;
14784     } else if (Cond.getOpcode() == ISD::SETCC &&
14785                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14786       // For FCMP_OEQ, we can emit
14787       // two branches instead of an explicit AND instruction with a
14788       // separate test. However, we only do this if this block doesn't
14789       // have a fall-through edge, because this requires an explicit
14790       // jmp when the condition is false.
14791       if (Op.getNode()->hasOneUse()) {
14792         SDNode *User = *Op.getNode()->use_begin();
14793         // Look for an unconditional branch following this conditional branch.
14794         // We need this because we need to reverse the successors in order
14795         // to implement FCMP_OEQ.
14796         if (User->getOpcode() == ISD::BR) {
14797           SDValue FalseBB = User->getOperand(1);
14798           SDNode *NewBR =
14799             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14800           assert(NewBR == User);
14801           (void)NewBR;
14802           Dest = FalseBB;
14803
14804           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14805                                     Cond.getOperand(0), Cond.getOperand(1));
14806           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14807           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14808           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14809                               Chain, Dest, CC, Cmp);
14810           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14811           Cond = Cmp;
14812           addTest = false;
14813         }
14814       }
14815     } else if (Cond.getOpcode() == ISD::SETCC &&
14816                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14817       // For FCMP_UNE, we can emit
14818       // two branches instead of an explicit AND instruction with a
14819       // separate test. However, we only do this if this block doesn't
14820       // have a fall-through edge, because this requires an explicit
14821       // jmp when the condition is false.
14822       if (Op.getNode()->hasOneUse()) {
14823         SDNode *User = *Op.getNode()->use_begin();
14824         // Look for an unconditional branch following this conditional branch.
14825         // We need this because we need to reverse the successors in order
14826         // to implement FCMP_UNE.
14827         if (User->getOpcode() == ISD::BR) {
14828           SDValue FalseBB = User->getOperand(1);
14829           SDNode *NewBR =
14830             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14831           assert(NewBR == User);
14832           (void)NewBR;
14833
14834           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14835                                     Cond.getOperand(0), Cond.getOperand(1));
14836           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14837           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14838           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14839                               Chain, Dest, CC, Cmp);
14840           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14841           Cond = Cmp;
14842           addTest = false;
14843           Dest = FalseBB;
14844         }
14845       }
14846     }
14847   }
14848
14849   if (addTest) {
14850     // Look pass the truncate if the high bits are known zero.
14851     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14852         Cond = Cond.getOperand(0);
14853
14854     // We know the result of AND is compared against zero. Try to match
14855     // it to BT.
14856     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14857       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14858       if (NewSetCC.getNode()) {
14859         CC = NewSetCC.getOperand(0);
14860         Cond = NewSetCC.getOperand(1);
14861         addTest = false;
14862       }
14863     }
14864   }
14865
14866   if (addTest) {
14867     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14868     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14869     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14870   }
14871   Cond = ConvertCmpIfNecessary(Cond, DAG);
14872   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14873                      Chain, Dest, CC, Cond);
14874 }
14875
14876 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14877 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14878 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14879 // that the guard pages used by the OS virtual memory manager are allocated in
14880 // correct sequence.
14881 SDValue
14882 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14883                                            SelectionDAG &DAG) const {
14884   MachineFunction &MF = DAG.getMachineFunction();
14885   bool SplitStack = MF.shouldSplitStack();
14886   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14887                SplitStack;
14888   SDLoc dl(Op);
14889
14890   if (!Lower) {
14891     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14892     SDNode* Node = Op.getNode();
14893
14894     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14895     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14896         " not tell us which reg is the stack pointer!");
14897     EVT VT = Node->getValueType(0);
14898     SDValue Tmp1 = SDValue(Node, 0);
14899     SDValue Tmp2 = SDValue(Node, 1);
14900     SDValue Tmp3 = Node->getOperand(2);
14901     SDValue Chain = Tmp1.getOperand(0);
14902
14903     // Chain the dynamic stack allocation so that it doesn't modify the stack
14904     // pointer when other instructions are using the stack.
14905     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14906         SDLoc(Node));
14907
14908     SDValue Size = Tmp2.getOperand(1);
14909     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14910     Chain = SP.getValue(1);
14911     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14912     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14913     unsigned StackAlign = TFI.getStackAlignment();
14914     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14915     if (Align > StackAlign)
14916       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14917           DAG.getConstant(-(uint64_t)Align, dl, VT));
14918     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14919
14920     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14921         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14922         SDLoc(Node));
14923
14924     SDValue Ops[2] = { Tmp1, Tmp2 };
14925     return DAG.getMergeValues(Ops, dl);
14926   }
14927
14928   // Get the inputs.
14929   SDValue Chain = Op.getOperand(0);
14930   SDValue Size  = Op.getOperand(1);
14931   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14932   EVT VT = Op.getNode()->getValueType(0);
14933
14934   bool Is64Bit = Subtarget->is64Bit();
14935   MVT SPTy = getPointerTy(DAG.getDataLayout());
14936
14937   if (SplitStack) {
14938     MachineRegisterInfo &MRI = MF.getRegInfo();
14939
14940     if (Is64Bit) {
14941       // The 64 bit implementation of segmented stacks needs to clobber both r10
14942       // r11. This makes it impossible to use it along with nested parameters.
14943       const Function *F = MF.getFunction();
14944
14945       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14946            I != E; ++I)
14947         if (I->hasNestAttr())
14948           report_fatal_error("Cannot use segmented stacks with functions that "
14949                              "have nested arguments.");
14950     }
14951
14952     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14953     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14954     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14955     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14956                                 DAG.getRegister(Vreg, SPTy));
14957     SDValue Ops1[2] = { Value, Chain };
14958     return DAG.getMergeValues(Ops1, dl);
14959   } else {
14960     SDValue Flag;
14961     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14962
14963     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14964     Flag = Chain.getValue(1);
14965     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14966
14967     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14968
14969     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14970     unsigned SPReg = RegInfo->getStackRegister();
14971     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14972     Chain = SP.getValue(1);
14973
14974     if (Align) {
14975       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14976                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14977       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14978     }
14979
14980     SDValue Ops1[2] = { SP, Chain };
14981     return DAG.getMergeValues(Ops1, dl);
14982   }
14983 }
14984
14985 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14986   MachineFunction &MF = DAG.getMachineFunction();
14987   auto PtrVT = getPointerTy(MF.getDataLayout());
14988   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14989
14990   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14991   SDLoc DL(Op);
14992
14993   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14994     // vastart just stores the address of the VarArgsFrameIndex slot into the
14995     // memory location argument.
14996     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14997     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14998                         MachinePointerInfo(SV), false, false, 0);
14999   }
15000
15001   // __va_list_tag:
15002   //   gp_offset         (0 - 6 * 8)
15003   //   fp_offset         (48 - 48 + 8 * 16)
15004   //   overflow_arg_area (point to parameters coming in memory).
15005   //   reg_save_area
15006   SmallVector<SDValue, 8> MemOps;
15007   SDValue FIN = Op.getOperand(1);
15008   // Store gp_offset
15009   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
15010                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
15011                                                DL, MVT::i32),
15012                                FIN, MachinePointerInfo(SV), false, false, 0);
15013   MemOps.push_back(Store);
15014
15015   // Store fp_offset
15016   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15017   Store = DAG.getStore(Op.getOperand(0), DL,
15018                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
15019                                        MVT::i32),
15020                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
15021   MemOps.push_back(Store);
15022
15023   // Store ptr to overflow_arg_area
15024   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
15025   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
15026   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
15027                        MachinePointerInfo(SV, 8),
15028                        false, false, 0);
15029   MemOps.push_back(Store);
15030
15031   // Store ptr to reg_save_area.
15032   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15033   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15034   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15035                        MachinePointerInfo(SV, 16), false, false, 0);
15036   MemOps.push_back(Store);
15037   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15038 }
15039
15040 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15041   assert(Subtarget->is64Bit() &&
15042          "LowerVAARG only handles 64-bit va_arg!");
15043   assert((Subtarget->isTargetLinux() ||
15044           Subtarget->isTargetDarwin()) &&
15045           "Unhandled target in LowerVAARG");
15046   assert(Op.getNode()->getNumOperands() == 4);
15047   SDValue Chain = Op.getOperand(0);
15048   SDValue SrcPtr = Op.getOperand(1);
15049   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15050   unsigned Align = Op.getConstantOperandVal(3);
15051   SDLoc dl(Op);
15052
15053   EVT ArgVT = Op.getNode()->getValueType(0);
15054   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15055   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15056   uint8_t ArgMode;
15057
15058   // Decide which area this value should be read from.
15059   // TODO: Implement the AMD64 ABI in its entirety. This simple
15060   // selection mechanism works only for the basic types.
15061   if (ArgVT == MVT::f80) {
15062     llvm_unreachable("va_arg for f80 not yet implemented");
15063   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15064     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15065   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15066     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15067   } else {
15068     llvm_unreachable("Unhandled argument type in LowerVAARG");
15069   }
15070
15071   if (ArgMode == 2) {
15072     // Sanity Check: Make sure using fp_offset makes sense.
15073     assert(!Subtarget->useSoftFloat() &&
15074            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15075                Attribute::NoImplicitFloat)) &&
15076            Subtarget->hasSSE1());
15077   }
15078
15079   // Insert VAARG_64 node into the DAG
15080   // VAARG_64 returns two values: Variable Argument Address, Chain
15081   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15082                        DAG.getConstant(ArgMode, dl, MVT::i8),
15083                        DAG.getConstant(Align, dl, MVT::i32)};
15084   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15085   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15086                                           VTs, InstOps, MVT::i64,
15087                                           MachinePointerInfo(SV),
15088                                           /*Align=*/0,
15089                                           /*Volatile=*/false,
15090                                           /*ReadMem=*/true,
15091                                           /*WriteMem=*/true);
15092   Chain = VAARG.getValue(1);
15093
15094   // Load the next argument and return it
15095   return DAG.getLoad(ArgVT, dl,
15096                      Chain,
15097                      VAARG,
15098                      MachinePointerInfo(),
15099                      false, false, false, 0);
15100 }
15101
15102 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15103                            SelectionDAG &DAG) {
15104   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15105   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15106   SDValue Chain = Op.getOperand(0);
15107   SDValue DstPtr = Op.getOperand(1);
15108   SDValue SrcPtr = Op.getOperand(2);
15109   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15110   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15111   SDLoc DL(Op);
15112
15113   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15114                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15115                        false, false,
15116                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15117 }
15118
15119 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15120 // amount is a constant. Takes immediate version of shift as input.
15121 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15122                                           SDValue SrcOp, uint64_t ShiftAmt,
15123                                           SelectionDAG &DAG) {
15124   MVT ElementType = VT.getVectorElementType();
15125
15126   // Fold this packed shift into its first operand if ShiftAmt is 0.
15127   if (ShiftAmt == 0)
15128     return SrcOp;
15129
15130   // Check for ShiftAmt >= element width
15131   if (ShiftAmt >= ElementType.getSizeInBits()) {
15132     if (Opc == X86ISD::VSRAI)
15133       ShiftAmt = ElementType.getSizeInBits() - 1;
15134     else
15135       return DAG.getConstant(0, dl, VT);
15136   }
15137
15138   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15139          && "Unknown target vector shift-by-constant node");
15140
15141   // Fold this packed vector shift into a build vector if SrcOp is a
15142   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15143   if (VT == SrcOp.getSimpleValueType() &&
15144       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15145     SmallVector<SDValue, 8> Elts;
15146     unsigned NumElts = SrcOp->getNumOperands();
15147     ConstantSDNode *ND;
15148
15149     switch(Opc) {
15150     default: llvm_unreachable(nullptr);
15151     case X86ISD::VSHLI:
15152       for (unsigned i=0; i!=NumElts; ++i) {
15153         SDValue CurrentOp = SrcOp->getOperand(i);
15154         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15155           Elts.push_back(CurrentOp);
15156           continue;
15157         }
15158         ND = cast<ConstantSDNode>(CurrentOp);
15159         const APInt &C = ND->getAPIntValue();
15160         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15161       }
15162       break;
15163     case X86ISD::VSRLI:
15164       for (unsigned i=0; i!=NumElts; ++i) {
15165         SDValue CurrentOp = SrcOp->getOperand(i);
15166         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15167           Elts.push_back(CurrentOp);
15168           continue;
15169         }
15170         ND = cast<ConstantSDNode>(CurrentOp);
15171         const APInt &C = ND->getAPIntValue();
15172         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15173       }
15174       break;
15175     case X86ISD::VSRAI:
15176       for (unsigned i=0; i!=NumElts; ++i) {
15177         SDValue CurrentOp = SrcOp->getOperand(i);
15178         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15179           Elts.push_back(CurrentOp);
15180           continue;
15181         }
15182         ND = cast<ConstantSDNode>(CurrentOp);
15183         const APInt &C = ND->getAPIntValue();
15184         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15185       }
15186       break;
15187     }
15188
15189     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15190   }
15191
15192   return DAG.getNode(Opc, dl, VT, SrcOp,
15193                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15194 }
15195
15196 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15197 // may or may not be a constant. Takes immediate version of shift as input.
15198 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15199                                    SDValue SrcOp, SDValue ShAmt,
15200                                    SelectionDAG &DAG) {
15201   MVT SVT = ShAmt.getSimpleValueType();
15202   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15203
15204   // Catch shift-by-constant.
15205   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15206     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15207                                       CShAmt->getZExtValue(), DAG);
15208
15209   // Change opcode to non-immediate version
15210   switch (Opc) {
15211     default: llvm_unreachable("Unknown target vector shift node");
15212     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15213     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15214     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15215   }
15216
15217   const X86Subtarget &Subtarget =
15218       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15219   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15220       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15221     // Let the shuffle legalizer expand this shift amount node.
15222     SDValue Op0 = ShAmt.getOperand(0);
15223     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15224     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15225   } else {
15226     // Need to build a vector containing shift amount.
15227     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15228     SmallVector<SDValue, 4> ShOps;
15229     ShOps.push_back(ShAmt);
15230     if (SVT == MVT::i32) {
15231       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15232       ShOps.push_back(DAG.getUNDEF(SVT));
15233     }
15234     ShOps.push_back(DAG.getUNDEF(SVT));
15235
15236     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15237     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15238   }
15239
15240   // The return type has to be a 128-bit type with the same element
15241   // type as the input type.
15242   MVT EltVT = VT.getVectorElementType();
15243   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15244
15245   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15246   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15247 }
15248
15249 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15250 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15251 /// necessary casting or extending for \p Mask when lowering masking intrinsics
15252 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15253                                     SDValue PreservedSrc,
15254                                     const X86Subtarget *Subtarget,
15255                                     SelectionDAG &DAG) {
15256     EVT VT = Op.getValueType();
15257     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15258                                   MVT::i1, VT.getVectorNumElements());
15259     SDValue VMask = SDValue();
15260     unsigned OpcodeSelect = ISD::VSELECT;
15261     SDLoc dl(Op);
15262
15263     assert(MaskVT.isSimple() && "invalid mask type");
15264
15265     if (isAllOnes(Mask))
15266       return Op;
15267
15268     if (MaskVT.bitsGT(Mask.getValueType())) {
15269       EVT newMaskVT =  EVT::getIntegerVT(*DAG.getContext(),
15270                                          MaskVT.getSizeInBits());
15271       VMask = DAG.getBitcast(MaskVT,
15272                              DAG.getNode(ISD::ANY_EXTEND, dl, newMaskVT, Mask));
15273     } else {
15274       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15275                                        Mask.getValueType().getSizeInBits());
15276       // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15277       // are extracted by EXTRACT_SUBVECTOR.
15278       VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15279                           DAG.getBitcast(BitcastVT, Mask),
15280                           DAG.getIntPtrConstant(0, dl));
15281     }
15282
15283     switch (Op.getOpcode()) {
15284       default: break;
15285       case X86ISD::PCMPEQM:
15286       case X86ISD::PCMPGTM:
15287       case X86ISD::CMPM:
15288       case X86ISD::CMPMU:
15289         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15290       case X86ISD::VTRUNC:
15291       case X86ISD::VTRUNCS:
15292       case X86ISD::VTRUNCUS:
15293         // We can't use ISD::VSELECT here because it is not always "Legal"
15294         // for the destination type. For example vpmovqb require only AVX512
15295         // and vselect that can operate on byte element type require BWI
15296         OpcodeSelect = X86ISD::SELECT;
15297         break;
15298     }
15299     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15300       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15301     return DAG.getNode(OpcodeSelect, dl, VT, VMask, Op, PreservedSrc);
15302 }
15303
15304 /// \brief Creates an SDNode for a predicated scalar operation.
15305 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15306 /// The mask is comming as MVT::i8 and it should be truncated
15307 /// to MVT::i1 while lowering masking intrinsics.
15308 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15309 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15310 /// a scalar instruction.
15311 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15312                                     SDValue PreservedSrc,
15313                                     const X86Subtarget *Subtarget,
15314                                     SelectionDAG &DAG) {
15315     if (isAllOnes(Mask))
15316       return Op;
15317
15318     EVT VT = Op.getValueType();
15319     SDLoc dl(Op);
15320     // The mask should be of type MVT::i1
15321     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15322
15323     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15324       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15325     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15326 }
15327
15328 static int getSEHRegistrationNodeSize(const Function *Fn) {
15329   if (!Fn->hasPersonalityFn())
15330     report_fatal_error(
15331         "querying registration node size for function without personality");
15332   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15333   // WinEHStatePass for the full struct definition.
15334   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15335   case EHPersonality::MSVC_X86SEH: return 24;
15336   case EHPersonality::MSVC_CXX: return 16;
15337   default: break;
15338   }
15339   report_fatal_error("can only recover FP for MSVC EH personality functions");
15340 }
15341
15342 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15343 /// function or when returning to a parent frame after catching an exception, we
15344 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15345 /// Here's the math:
15346 ///   RegNodeBase = EntryEBP - RegNodeSize
15347 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15348 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15349 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15350 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15351                                    SDValue EntryEBP) {
15352   MachineFunction &MF = DAG.getMachineFunction();
15353   SDLoc dl;
15354
15355   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15356   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15357
15358   // It's possible that the parent function no longer has a personality function
15359   // if the exceptional code was optimized away, in which case we just return
15360   // the incoming EBP.
15361   if (!Fn->hasPersonalityFn())
15362     return EntryEBP;
15363
15364   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15365
15366   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15367   // registration.
15368   MCSymbol *OffsetSym =
15369       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15370           GlobalValue::getRealLinkageName(Fn->getName()));
15371   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15372   SDValue RegNodeFrameOffset =
15373       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15374
15375   // RegNodeBase = EntryEBP - RegNodeSize
15376   // ParentFP = RegNodeBase - RegNodeFrameOffset
15377   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15378                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15379   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15380 }
15381
15382 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15383                                        SelectionDAG &DAG) {
15384   SDLoc dl(Op);
15385   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15386   EVT VT = Op.getValueType();
15387   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15388   if (IntrData) {
15389     switch(IntrData->Type) {
15390     case INTR_TYPE_1OP:
15391       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15392     case INTR_TYPE_2OP:
15393       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15394         Op.getOperand(2));
15395     case INTR_TYPE_3OP:
15396       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15397         Op.getOperand(2), Op.getOperand(3));
15398     case INTR_TYPE_4OP:
15399       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15400         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15401     case INTR_TYPE_1OP_MASK_RM: {
15402       SDValue Src = Op.getOperand(1);
15403       SDValue PassThru = Op.getOperand(2);
15404       SDValue Mask = Op.getOperand(3);
15405       SDValue RoundingMode;
15406       // We allways add rounding mode to the Node.
15407       // If the rounding mode is not specified, we add the 
15408       // "current direction" mode.
15409       if (Op.getNumOperands() == 4)
15410         RoundingMode =
15411           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15412       else
15413         RoundingMode = Op.getOperand(4);
15414       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15415       if (IntrWithRoundingModeOpcode != 0)
15416         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15417             X86::STATIC_ROUNDING::CUR_DIRECTION)
15418           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15419                                       dl, Op.getValueType(), Src, RoundingMode),
15420                                       Mask, PassThru, Subtarget, DAG);
15421       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15422                                               RoundingMode),
15423                                   Mask, PassThru, Subtarget, DAG);
15424     }
15425     case INTR_TYPE_1OP_MASK: {
15426       SDValue Src = Op.getOperand(1);
15427       SDValue PassThru = Op.getOperand(2);
15428       SDValue Mask = Op.getOperand(3);
15429       // We add rounding mode to the Node when
15430       //   - RM Opcode is specified and
15431       //   - RM is not "current direction".
15432       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15433       if (IntrWithRoundingModeOpcode != 0) {
15434         SDValue Rnd = Op.getOperand(4);
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                                       Src, Rnd),
15440                                       Mask, PassThru, Subtarget, DAG);
15441         }
15442       }
15443       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15444                                   Mask, PassThru, Subtarget, DAG);
15445     }
15446     case INTR_TYPE_SCALAR_MASK_RM: {
15447       SDValue Src1 = Op.getOperand(1);
15448       SDValue Src2 = Op.getOperand(2);
15449       SDValue Src0 = Op.getOperand(3);
15450       SDValue Mask = Op.getOperand(4);
15451       // There are 2 kinds of intrinsics in this group:
15452       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15453       // (2) With rounding mode and sae - 7 operands.
15454       if (Op.getNumOperands() == 6) {
15455         SDValue Sae  = Op.getOperand(5);
15456         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15457         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15458                                                 Sae),
15459                                     Mask, Src0, Subtarget, DAG);
15460       }
15461       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15462       SDValue RoundingMode  = Op.getOperand(5);
15463       SDValue Sae  = Op.getOperand(6);
15464       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15465                                               RoundingMode, Sae),
15466                                   Mask, Src0, Subtarget, DAG);
15467     }
15468     case INTR_TYPE_2OP_MASK: {
15469       SDValue Src1 = Op.getOperand(1);
15470       SDValue Src2 = Op.getOperand(2);
15471       SDValue PassThru = Op.getOperand(3);
15472       SDValue Mask = Op.getOperand(4);
15473       // We specify 2 possible opcodes for intrinsics with rounding modes.
15474       // First, we check if the intrinsic may have non-default rounding mode,
15475       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15476       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15477       if (IntrWithRoundingModeOpcode != 0) {
15478         SDValue Rnd = Op.getOperand(5);
15479         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15480         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15481           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15482                                       dl, Op.getValueType(),
15483                                       Src1, Src2, Rnd),
15484                                       Mask, PassThru, Subtarget, DAG);
15485         }
15486       }
15487       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15488                                               Src1,Src2),
15489                                   Mask, PassThru, Subtarget, DAG);
15490     }
15491     case INTR_TYPE_2OP_MASK_RM: {
15492       SDValue Src1 = Op.getOperand(1);
15493       SDValue Src2 = Op.getOperand(2);
15494       SDValue PassThru = Op.getOperand(3);
15495       SDValue Mask = Op.getOperand(4);
15496       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15497       // First, we check if the intrinsic have rounding mode (6 operands),
15498       // if not, we set rounding mode to "current".
15499       SDValue Rnd;
15500       if (Op.getNumOperands() == 6)
15501         Rnd = Op.getOperand(5);
15502       else
15503         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15504       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15505                                               Src1, Src2, Rnd),
15506                                   Mask, PassThru, Subtarget, DAG);
15507     }
15508     case INTR_TYPE_3OP_MASK_RM: {
15509       SDValue Src1 = Op.getOperand(1);
15510       SDValue Src2 = Op.getOperand(2);
15511       SDValue Imm = Op.getOperand(3);
15512       SDValue PassThru = Op.getOperand(4);
15513       SDValue Mask = Op.getOperand(5);
15514       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15515       // First, we check if the intrinsic have rounding mode (7 operands),
15516       // if not, we set rounding mode to "current".
15517       SDValue Rnd;
15518       if (Op.getNumOperands() == 7)
15519         Rnd = Op.getOperand(6);
15520       else
15521         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15522       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15523         Src1, Src2, Imm, Rnd),
15524         Mask, PassThru, Subtarget, DAG);
15525     }
15526     case INTR_TYPE_3OP_MASK: {
15527       SDValue Src1 = Op.getOperand(1);
15528       SDValue Src2 = Op.getOperand(2);
15529       SDValue Src3 = Op.getOperand(3);
15530       SDValue PassThru = Op.getOperand(4);
15531       SDValue Mask = Op.getOperand(5);
15532       // We specify 2 possible opcodes for intrinsics with rounding modes.
15533       // First, we check if the intrinsic may have non-default rounding mode,
15534       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15535       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15536       if (IntrWithRoundingModeOpcode != 0) {
15537         SDValue Rnd = Op.getOperand(6);
15538         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15539         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15540           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15541                                       dl, Op.getValueType(),
15542                                       Src1, Src2, Src3, Rnd),
15543                                       Mask, PassThru, Subtarget, DAG);
15544         }
15545       }
15546       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15547                                               Src1, Src2, Src3),
15548                                   Mask, PassThru, Subtarget, DAG);
15549     }
15550     case VPERM_3OP_MASKZ:
15551     case VPERM_3OP_MASK:
15552     case FMA_OP_MASK3:
15553     case FMA_OP_MASKZ:
15554     case FMA_OP_MASK: {
15555       SDValue Src1 = Op.getOperand(1);
15556       SDValue Src2 = Op.getOperand(2);
15557       SDValue Src3 = Op.getOperand(3);
15558       SDValue Mask = Op.getOperand(4);
15559       EVT VT = Op.getValueType();
15560       SDValue PassThru = SDValue();
15561
15562       // set PassThru element
15563       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15564         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15565       else if (IntrData->Type == FMA_OP_MASK3)
15566         PassThru = Src3;
15567       else
15568         PassThru = Src1;
15569
15570       // We specify 2 possible opcodes for intrinsics with rounding modes.
15571       // First, we check if the intrinsic may have non-default rounding mode,
15572       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15573       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15574       if (IntrWithRoundingModeOpcode != 0) {
15575         SDValue Rnd = Op.getOperand(5);
15576         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15577             X86::STATIC_ROUNDING::CUR_DIRECTION)
15578           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15579                                                   dl, Op.getValueType(),
15580                                                   Src1, Src2, Src3, Rnd),
15581                                       Mask, PassThru, Subtarget, DAG);
15582       }
15583       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15584                                               dl, Op.getValueType(),
15585                                               Src1, Src2, Src3),
15586                                   Mask, PassThru, Subtarget, DAG);
15587     }
15588     case CMP_MASK:
15589     case CMP_MASK_CC: {
15590       // Comparison intrinsics with masks.
15591       // Example of transformation:
15592       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15593       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15594       // (i8 (bitcast
15595       //   (v8i1 (insert_subvector undef,
15596       //           (v2i1 (and (PCMPEQM %a, %b),
15597       //                      (extract_subvector
15598       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15599       EVT VT = Op.getOperand(1).getValueType();
15600       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15601                                     VT.getVectorNumElements());
15602       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15603       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15604                                        Mask.getValueType().getSizeInBits());
15605       SDValue Cmp;
15606       if (IntrData->Type == CMP_MASK_CC) {
15607         SDValue CC = Op.getOperand(3);
15608         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15609         // We specify 2 possible opcodes for intrinsics with rounding modes.
15610         // First, we check if the intrinsic may have non-default rounding mode,
15611         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15612         if (IntrData->Opc1 != 0) {
15613           SDValue Rnd = Op.getOperand(5);
15614           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15615               X86::STATIC_ROUNDING::CUR_DIRECTION)
15616             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15617                               Op.getOperand(2), CC, Rnd);
15618         }
15619         //default rounding mode
15620         if(!Cmp.getNode())
15621             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15622                               Op.getOperand(2), CC);
15623
15624       } else {
15625         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15626         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15627                           Op.getOperand(2));
15628       }
15629       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15630                                              DAG.getTargetConstant(0, dl,
15631                                                                    MaskVT),
15632                                              Subtarget, DAG);
15633       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15634                                 DAG.getUNDEF(BitcastVT), CmpMask,
15635                                 DAG.getIntPtrConstant(0, dl));
15636       return DAG.getBitcast(Op.getValueType(), Res);
15637     }
15638     case COMI: { // Comparison intrinsics
15639       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15640       SDValue LHS = Op.getOperand(1);
15641       SDValue RHS = Op.getOperand(2);
15642       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15643       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15644       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15645       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15646                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15647       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15648     }
15649     case VSHIFT:
15650       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15651                                  Op.getOperand(1), Op.getOperand(2), DAG);
15652     case VSHIFT_MASK:
15653       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15654                                                       Op.getSimpleValueType(),
15655                                                       Op.getOperand(1),
15656                                                       Op.getOperand(2), DAG),
15657                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15658                                   DAG);
15659     case COMPRESS_EXPAND_IN_REG: {
15660       SDValue Mask = Op.getOperand(3);
15661       SDValue DataToCompress = Op.getOperand(1);
15662       SDValue PassThru = Op.getOperand(2);
15663       if (isAllOnes(Mask)) // return data as is
15664         return Op.getOperand(1);
15665
15666       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15667                                               DataToCompress),
15668                                   Mask, PassThru, Subtarget, DAG);
15669     }
15670     case BLEND: {
15671       SDValue Mask = Op.getOperand(3);
15672       EVT VT = Op.getValueType();
15673       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15674                                     VT.getVectorNumElements());
15675       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15676                                        Mask.getValueType().getSizeInBits());
15677       SDLoc dl(Op);
15678       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15679                                   DAG.getBitcast(BitcastVT, Mask),
15680                                   DAG.getIntPtrConstant(0, dl));
15681       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15682                          Op.getOperand(2));
15683     }
15684     default:
15685       break;
15686     }
15687   }
15688
15689   switch (IntNo) {
15690   default: return SDValue();    // Don't custom lower most intrinsics.
15691
15692   case Intrinsic::x86_avx2_permd:
15693   case Intrinsic::x86_avx2_permps:
15694     // Operands intentionally swapped. Mask is last operand to intrinsic,
15695     // but second operand for node/instruction.
15696     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15697                        Op.getOperand(2), Op.getOperand(1));
15698
15699   // ptest and testp intrinsics. The intrinsic these come from are designed to
15700   // return an integer value, not just an instruction so lower it to the ptest
15701   // or testp pattern and a setcc for the result.
15702   case Intrinsic::x86_sse41_ptestz:
15703   case Intrinsic::x86_sse41_ptestc:
15704   case Intrinsic::x86_sse41_ptestnzc:
15705   case Intrinsic::x86_avx_ptestz_256:
15706   case Intrinsic::x86_avx_ptestc_256:
15707   case Intrinsic::x86_avx_ptestnzc_256:
15708   case Intrinsic::x86_avx_vtestz_ps:
15709   case Intrinsic::x86_avx_vtestc_ps:
15710   case Intrinsic::x86_avx_vtestnzc_ps:
15711   case Intrinsic::x86_avx_vtestz_pd:
15712   case Intrinsic::x86_avx_vtestc_pd:
15713   case Intrinsic::x86_avx_vtestnzc_pd:
15714   case Intrinsic::x86_avx_vtestz_ps_256:
15715   case Intrinsic::x86_avx_vtestc_ps_256:
15716   case Intrinsic::x86_avx_vtestnzc_ps_256:
15717   case Intrinsic::x86_avx_vtestz_pd_256:
15718   case Intrinsic::x86_avx_vtestc_pd_256:
15719   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15720     bool IsTestPacked = false;
15721     unsigned X86CC;
15722     switch (IntNo) {
15723     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15724     case Intrinsic::x86_avx_vtestz_ps:
15725     case Intrinsic::x86_avx_vtestz_pd:
15726     case Intrinsic::x86_avx_vtestz_ps_256:
15727     case Intrinsic::x86_avx_vtestz_pd_256:
15728       IsTestPacked = true; // Fallthrough
15729     case Intrinsic::x86_sse41_ptestz:
15730     case Intrinsic::x86_avx_ptestz_256:
15731       // ZF = 1
15732       X86CC = X86::COND_E;
15733       break;
15734     case Intrinsic::x86_avx_vtestc_ps:
15735     case Intrinsic::x86_avx_vtestc_pd:
15736     case Intrinsic::x86_avx_vtestc_ps_256:
15737     case Intrinsic::x86_avx_vtestc_pd_256:
15738       IsTestPacked = true; // Fallthrough
15739     case Intrinsic::x86_sse41_ptestc:
15740     case Intrinsic::x86_avx_ptestc_256:
15741       // CF = 1
15742       X86CC = X86::COND_B;
15743       break;
15744     case Intrinsic::x86_avx_vtestnzc_ps:
15745     case Intrinsic::x86_avx_vtestnzc_pd:
15746     case Intrinsic::x86_avx_vtestnzc_ps_256:
15747     case Intrinsic::x86_avx_vtestnzc_pd_256:
15748       IsTestPacked = true; // Fallthrough
15749     case Intrinsic::x86_sse41_ptestnzc:
15750     case Intrinsic::x86_avx_ptestnzc_256:
15751       // ZF and CF = 0
15752       X86CC = X86::COND_A;
15753       break;
15754     }
15755
15756     SDValue LHS = Op.getOperand(1);
15757     SDValue RHS = Op.getOperand(2);
15758     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15759     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15760     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15761     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15762     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15763   }
15764   case Intrinsic::x86_avx512_kortestz_w:
15765   case Intrinsic::x86_avx512_kortestc_w: {
15766     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15767     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15768     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15769     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15770     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15771     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15772     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15773   }
15774
15775   case Intrinsic::x86_sse42_pcmpistria128:
15776   case Intrinsic::x86_sse42_pcmpestria128:
15777   case Intrinsic::x86_sse42_pcmpistric128:
15778   case Intrinsic::x86_sse42_pcmpestric128:
15779   case Intrinsic::x86_sse42_pcmpistrio128:
15780   case Intrinsic::x86_sse42_pcmpestrio128:
15781   case Intrinsic::x86_sse42_pcmpistris128:
15782   case Intrinsic::x86_sse42_pcmpestris128:
15783   case Intrinsic::x86_sse42_pcmpistriz128:
15784   case Intrinsic::x86_sse42_pcmpestriz128: {
15785     unsigned Opcode;
15786     unsigned X86CC;
15787     switch (IntNo) {
15788     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15789     case Intrinsic::x86_sse42_pcmpistria128:
15790       Opcode = X86ISD::PCMPISTRI;
15791       X86CC = X86::COND_A;
15792       break;
15793     case Intrinsic::x86_sse42_pcmpestria128:
15794       Opcode = X86ISD::PCMPESTRI;
15795       X86CC = X86::COND_A;
15796       break;
15797     case Intrinsic::x86_sse42_pcmpistric128:
15798       Opcode = X86ISD::PCMPISTRI;
15799       X86CC = X86::COND_B;
15800       break;
15801     case Intrinsic::x86_sse42_pcmpestric128:
15802       Opcode = X86ISD::PCMPESTRI;
15803       X86CC = X86::COND_B;
15804       break;
15805     case Intrinsic::x86_sse42_pcmpistrio128:
15806       Opcode = X86ISD::PCMPISTRI;
15807       X86CC = X86::COND_O;
15808       break;
15809     case Intrinsic::x86_sse42_pcmpestrio128:
15810       Opcode = X86ISD::PCMPESTRI;
15811       X86CC = X86::COND_O;
15812       break;
15813     case Intrinsic::x86_sse42_pcmpistris128:
15814       Opcode = X86ISD::PCMPISTRI;
15815       X86CC = X86::COND_S;
15816       break;
15817     case Intrinsic::x86_sse42_pcmpestris128:
15818       Opcode = X86ISD::PCMPESTRI;
15819       X86CC = X86::COND_S;
15820       break;
15821     case Intrinsic::x86_sse42_pcmpistriz128:
15822       Opcode = X86ISD::PCMPISTRI;
15823       X86CC = X86::COND_E;
15824       break;
15825     case Intrinsic::x86_sse42_pcmpestriz128:
15826       Opcode = X86ISD::PCMPESTRI;
15827       X86CC = X86::COND_E;
15828       break;
15829     }
15830     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15831     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15832     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15833     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15834                                 DAG.getConstant(X86CC, dl, MVT::i8),
15835                                 SDValue(PCMP.getNode(), 1));
15836     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15837   }
15838
15839   case Intrinsic::x86_sse42_pcmpistri128:
15840   case Intrinsic::x86_sse42_pcmpestri128: {
15841     unsigned Opcode;
15842     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15843       Opcode = X86ISD::PCMPISTRI;
15844     else
15845       Opcode = X86ISD::PCMPESTRI;
15846
15847     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15848     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15849     return DAG.getNode(Opcode, dl, VTs, NewOps);
15850   }
15851
15852   case Intrinsic::x86_seh_lsda: {
15853     // Compute the symbol for the LSDA. We know it'll get emitted later.
15854     MachineFunction &MF = DAG.getMachineFunction();
15855     SDValue Op1 = Op.getOperand(1);
15856     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15857     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15858         GlobalValue::getRealLinkageName(Fn->getName()));
15859
15860     // Generate a simple absolute symbol reference. This intrinsic is only
15861     // supported on 32-bit Windows, which isn't PIC.
15862     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15863     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15864   }
15865
15866   case Intrinsic::x86_seh_recoverfp: {
15867     SDValue FnOp = Op.getOperand(1);
15868     SDValue IncomingFPOp = Op.getOperand(2);
15869     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15870     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15871     if (!Fn)
15872       report_fatal_error(
15873           "llvm.x86.seh.recoverfp must take a function as the first argument");
15874     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15875   }
15876
15877   case Intrinsic::localaddress: {
15878     // Returns one of the stack, base, or frame pointer registers, depending on
15879     // which is used to reference local variables.
15880     MachineFunction &MF = DAG.getMachineFunction();
15881     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15882     unsigned Reg;
15883     if (RegInfo->hasBasePointer(MF))
15884       Reg = RegInfo->getBaseRegister();
15885     else // This function handles the SP or FP case.
15886       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15887     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15888   }
15889   }
15890 }
15891
15892 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15893                               SDValue Src, SDValue Mask, SDValue Base,
15894                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15895                               const X86Subtarget * Subtarget) {
15896   SDLoc dl(Op);
15897   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15898   if (!C)
15899     llvm_unreachable("Invalid scale type");
15900   unsigned ScaleVal = C->getZExtValue();
15901   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15902     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15903
15904   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15905   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15906                              Index.getSimpleValueType().getVectorNumElements());
15907   SDValue MaskInReg;
15908   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15909   if (MaskC)
15910     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15911   else {
15912     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15913                                      Mask.getValueType().getSizeInBits());
15914
15915     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15916     // are extracted by EXTRACT_SUBVECTOR.
15917     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15918                             DAG.getBitcast(BitcastVT, Mask),
15919                             DAG.getIntPtrConstant(0, dl));
15920   }
15921   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15922   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15923   SDValue Segment = DAG.getRegister(0, MVT::i32);
15924   if (Src.getOpcode() == ISD::UNDEF)
15925     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15926   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15927   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15928   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15929   return DAG.getMergeValues(RetOps, dl);
15930 }
15931
15932 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15933                                SDValue Src, SDValue Mask, SDValue Base,
15934                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15935   SDLoc dl(Op);
15936   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15937   if (!C)
15938     llvm_unreachable("Invalid scale type");
15939   unsigned ScaleVal = C->getZExtValue();
15940   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15941     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15942
15943   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15944   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15945   SDValue Segment = DAG.getRegister(0, MVT::i32);
15946   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15947                              Index.getSimpleValueType().getVectorNumElements());
15948   SDValue MaskInReg;
15949   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15950   if (MaskC)
15951     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15952   else {
15953     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15954                                      Mask.getValueType().getSizeInBits());
15955
15956     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15957     // are extracted by EXTRACT_SUBVECTOR.
15958     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15959                             DAG.getBitcast(BitcastVT, Mask),
15960                             DAG.getIntPtrConstant(0, dl));
15961   }
15962   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15963   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15964   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15965   return SDValue(Res, 1);
15966 }
15967
15968 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15969                                SDValue Mask, SDValue Base, SDValue Index,
15970                                SDValue ScaleOp, SDValue Chain) {
15971   SDLoc dl(Op);
15972   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15973   assert(C && "Invalid scale type");
15974   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15975   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15976   SDValue Segment = DAG.getRegister(0, MVT::i32);
15977   EVT MaskVT =
15978     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15979   SDValue MaskInReg;
15980   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15981   if (MaskC)
15982     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15983   else
15984     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15985   //SDVTList VTs = DAG.getVTList(MVT::Other);
15986   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15987   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15988   return SDValue(Res, 0);
15989 }
15990
15991 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15992 // read performance monitor counters (x86_rdpmc).
15993 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15994                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15995                               SmallVectorImpl<SDValue> &Results) {
15996   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15997   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15998   SDValue LO, HI;
15999
16000   // The ECX register is used to select the index of the performance counter
16001   // to read.
16002   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
16003                                    N->getOperand(2));
16004   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
16005
16006   // Reads the content of a 64-bit performance counter and returns it in the
16007   // registers EDX:EAX.
16008   if (Subtarget->is64Bit()) {
16009     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16010     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16011                             LO.getValue(2));
16012   } else {
16013     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16014     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16015                             LO.getValue(2));
16016   }
16017   Chain = HI.getValue(1);
16018
16019   if (Subtarget->is64Bit()) {
16020     // The EAX register is loaded with the low-order 32 bits. The EDX register
16021     // is loaded with the supported high-order bits of the counter.
16022     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16023                               DAG.getConstant(32, DL, MVT::i8));
16024     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16025     Results.push_back(Chain);
16026     return;
16027   }
16028
16029   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16030   SDValue Ops[] = { LO, HI };
16031   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16032   Results.push_back(Pair);
16033   Results.push_back(Chain);
16034 }
16035
16036 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
16037 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
16038 // also used to custom lower READCYCLECOUNTER nodes.
16039 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
16040                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
16041                               SmallVectorImpl<SDValue> &Results) {
16042   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
16043   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
16044   SDValue LO, HI;
16045
16046   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16047   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16048   // and the EAX register is loaded with the low-order 32 bits.
16049   if (Subtarget->is64Bit()) {
16050     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16051     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16052                             LO.getValue(2));
16053   } else {
16054     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16055     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16056                             LO.getValue(2));
16057   }
16058   SDValue Chain = HI.getValue(1);
16059
16060   if (Opcode == X86ISD::RDTSCP_DAG) {
16061     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16062
16063     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16064     // the ECX register. Add 'ecx' explicitly to the chain.
16065     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16066                                      HI.getValue(2));
16067     // Explicitly store the content of ECX at the location passed in input
16068     // to the 'rdtscp' intrinsic.
16069     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16070                          MachinePointerInfo(), false, false, 0);
16071   }
16072
16073   if (Subtarget->is64Bit()) {
16074     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16075     // the EAX register is loaded with the low-order 32 bits.
16076     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16077                               DAG.getConstant(32, DL, MVT::i8));
16078     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16079     Results.push_back(Chain);
16080     return;
16081   }
16082
16083   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16084   SDValue Ops[] = { LO, HI };
16085   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16086   Results.push_back(Pair);
16087   Results.push_back(Chain);
16088 }
16089
16090 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16091                                      SelectionDAG &DAG) {
16092   SmallVector<SDValue, 2> Results;
16093   SDLoc DL(Op);
16094   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16095                           Results);
16096   return DAG.getMergeValues(Results, DL);
16097 }
16098
16099 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16100                                     SelectionDAG &DAG) {
16101   MachineFunction &MF = DAG.getMachineFunction();
16102   const Function *Fn = MF.getFunction();
16103   SDLoc dl(Op);
16104   SDValue Chain = Op.getOperand(0);
16105
16106   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16107          "using llvm.x86.seh.restoreframe requires a frame pointer");
16108
16109   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16110   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16111
16112   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16113   unsigned FrameReg =
16114       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16115   unsigned SPReg = RegInfo->getStackRegister();
16116   unsigned SlotSize = RegInfo->getSlotSize();
16117
16118   // Get incoming EBP.
16119   SDValue IncomingEBP =
16120       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16121
16122   // SP is saved in the first field of every registration node, so load
16123   // [EBP-RegNodeSize] into SP.
16124   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16125   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16126                                DAG.getConstant(-RegNodeSize, dl, VT));
16127   SDValue NewSP =
16128       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16129                   false, VT.getScalarSizeInBits() / 8);
16130   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16131
16132   if (!RegInfo->needsStackRealignment(MF)) {
16133     // Adjust EBP to point back to the original frame position.
16134     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16135     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16136   } else {
16137     assert(RegInfo->hasBasePointer(MF) &&
16138            "functions with Win32 EH must use frame or base pointer register");
16139
16140     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16141     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16142     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16143
16144     // Reload the spilled EBP value, now that the stack and base pointers are
16145     // set up.
16146     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16147     X86FI->setHasSEHFramePtrSave(true);
16148     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16149     X86FI->setSEHFramePtrSaveIndex(FI);
16150     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16151                                 MachinePointerInfo(), false, false, false,
16152                                 VT.getScalarSizeInBits() / 8);
16153     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16154   }
16155
16156   return Chain;
16157 }
16158
16159 /// \brief Lower intrinsics for TRUNCATE_TO_MEM case
16160 /// return truncate Store/MaskedStore Node
16161 static SDValue LowerINTRINSIC_TRUNCATE_TO_MEM(const SDValue & Op,
16162                                                SelectionDAG &DAG,
16163                                                MVT ElementType) {
16164   SDLoc dl(Op);
16165   SDValue Mask = Op.getOperand(4);
16166   SDValue DataToTruncate = Op.getOperand(3);
16167   SDValue Addr = Op.getOperand(2);
16168   SDValue Chain = Op.getOperand(0);
16169
16170   EVT VT  = DataToTruncate.getValueType();
16171   EVT SVT = EVT::getVectorVT(*DAG.getContext(),
16172                              ElementType, VT.getVectorNumElements());
16173
16174   if (isAllOnes(Mask)) // return just a truncate store
16175     return DAG.getTruncStore(Chain, dl, DataToTruncate, Addr,
16176                              MachinePointerInfo(), SVT, false, false,
16177                              SVT.getScalarSizeInBits()/8);
16178
16179   EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
16180                                 MVT::i1, VT.getVectorNumElements());
16181   EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
16182                                    Mask.getValueType().getSizeInBits());
16183   // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
16184   // are extracted by EXTRACT_SUBVECTOR.
16185   SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
16186                               DAG.getBitcast(BitcastVT, Mask),
16187                               DAG.getIntPtrConstant(0, dl));
16188
16189   MachineMemOperand *MMO = DAG.getMachineFunction().
16190     getMachineMemOperand(MachinePointerInfo(),
16191                          MachineMemOperand::MOStore, SVT.getStoreSize(),
16192                          SVT.getScalarSizeInBits()/8);
16193
16194   return DAG.getMaskedStore(Chain, dl, DataToTruncate, Addr,
16195                             VMask, SVT, MMO, true);
16196 }
16197
16198 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16199                                       SelectionDAG &DAG) {
16200   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16201
16202   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16203   if (!IntrData) {
16204     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16205       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16206     return SDValue();
16207   }
16208
16209   SDLoc dl(Op);
16210   switch(IntrData->Type) {
16211   default:
16212     llvm_unreachable("Unknown Intrinsic Type");
16213     break;
16214   case RDSEED:
16215   case RDRAND: {
16216     // Emit the node with the right value type.
16217     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16218     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16219
16220     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16221     // Otherwise return the value from Rand, which is always 0, casted to i32.
16222     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16223                       DAG.getConstant(1, dl, Op->getValueType(1)),
16224                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16225                       SDValue(Result.getNode(), 1) };
16226     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16227                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16228                                   Ops);
16229
16230     // Return { result, isValid, chain }.
16231     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16232                        SDValue(Result.getNode(), 2));
16233   }
16234   case GATHER: {
16235   //gather(v1, mask, index, base, scale);
16236     SDValue Chain = Op.getOperand(0);
16237     SDValue Src   = Op.getOperand(2);
16238     SDValue Base  = Op.getOperand(3);
16239     SDValue Index = Op.getOperand(4);
16240     SDValue Mask  = Op.getOperand(5);
16241     SDValue Scale = Op.getOperand(6);
16242     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16243                          Chain, Subtarget);
16244   }
16245   case SCATTER: {
16246   //scatter(base, mask, index, v1, scale);
16247     SDValue Chain = Op.getOperand(0);
16248     SDValue Base  = Op.getOperand(2);
16249     SDValue Mask  = Op.getOperand(3);
16250     SDValue Index = Op.getOperand(4);
16251     SDValue Src   = Op.getOperand(5);
16252     SDValue Scale = Op.getOperand(6);
16253     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16254                           Scale, Chain);
16255   }
16256   case PREFETCH: {
16257     SDValue Hint = Op.getOperand(6);
16258     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16259     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16260     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16261     SDValue Chain = Op.getOperand(0);
16262     SDValue Mask  = Op.getOperand(2);
16263     SDValue Index = Op.getOperand(3);
16264     SDValue Base  = Op.getOperand(4);
16265     SDValue Scale = Op.getOperand(5);
16266     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16267   }
16268   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16269   case RDTSC: {
16270     SmallVector<SDValue, 2> Results;
16271     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16272                             Results);
16273     return DAG.getMergeValues(Results, dl);
16274   }
16275   // Read Performance Monitoring Counters.
16276   case RDPMC: {
16277     SmallVector<SDValue, 2> Results;
16278     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16279     return DAG.getMergeValues(Results, dl);
16280   }
16281   // XTEST intrinsics.
16282   case XTEST: {
16283     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16284     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16285     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16286                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16287                                 InTrans);
16288     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16289     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16290                        Ret, SDValue(InTrans.getNode(), 1));
16291   }
16292   // ADC/ADCX/SBB
16293   case ADX: {
16294     SmallVector<SDValue, 2> Results;
16295     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16296     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16297     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16298                                 DAG.getConstant(-1, dl, MVT::i8));
16299     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16300                               Op.getOperand(4), GenCF.getValue(1));
16301     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16302                                  Op.getOperand(5), MachinePointerInfo(),
16303                                  false, false, 0);
16304     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16305                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16306                                 Res.getValue(1));
16307     Results.push_back(SetCC);
16308     Results.push_back(Store);
16309     return DAG.getMergeValues(Results, dl);
16310   }
16311   case COMPRESS_TO_MEM: {
16312     SDLoc dl(Op);
16313     SDValue Mask = Op.getOperand(4);
16314     SDValue DataToCompress = Op.getOperand(3);
16315     SDValue Addr = Op.getOperand(2);
16316     SDValue Chain = Op.getOperand(0);
16317
16318     EVT VT = DataToCompress.getValueType();
16319     if (isAllOnes(Mask)) // return just a store
16320       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16321                           MachinePointerInfo(), false, false,
16322                           VT.getScalarSizeInBits()/8);
16323
16324     SDValue Compressed =
16325       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16326                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16327     return DAG.getStore(Chain, dl, Compressed, Addr,
16328                         MachinePointerInfo(), false, false,
16329                         VT.getScalarSizeInBits()/8);
16330   }
16331   case TRUNCATE_TO_MEM_VI8:
16332     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i8);
16333   case TRUNCATE_TO_MEM_VI16:
16334     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i16);
16335   case TRUNCATE_TO_MEM_VI32:
16336     return LowerINTRINSIC_TRUNCATE_TO_MEM(Op, DAG, MVT::i32);
16337   case EXPAND_FROM_MEM: {
16338     SDLoc dl(Op);
16339     SDValue Mask = Op.getOperand(4);
16340     SDValue PassThru = Op.getOperand(3);
16341     SDValue Addr = Op.getOperand(2);
16342     SDValue Chain = Op.getOperand(0);
16343     EVT VT = Op.getValueType();
16344
16345     if (isAllOnes(Mask)) // return just a load
16346       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16347                          false, VT.getScalarSizeInBits()/8);
16348
16349     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16350                                        false, false, false,
16351                                        VT.getScalarSizeInBits()/8);
16352
16353     SDValue Results[] = {
16354       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16355                            Mask, PassThru, Subtarget, DAG), Chain};
16356     return DAG.getMergeValues(Results, dl);
16357   }
16358   }
16359 }
16360
16361 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16362                                            SelectionDAG &DAG) const {
16363   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16364   MFI->setReturnAddressIsTaken(true);
16365
16366   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16367     return SDValue();
16368
16369   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16370   SDLoc dl(Op);
16371   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16372
16373   if (Depth > 0) {
16374     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16375     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16376     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16377     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16378                        DAG.getNode(ISD::ADD, dl, PtrVT,
16379                                    FrameAddr, Offset),
16380                        MachinePointerInfo(), false, false, false, 0);
16381   }
16382
16383   // Just load the return address.
16384   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16385   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16386                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16387 }
16388
16389 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16390   MachineFunction &MF = DAG.getMachineFunction();
16391   MachineFrameInfo *MFI = MF.getFrameInfo();
16392   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16393   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16394   EVT VT = Op.getValueType();
16395
16396   MFI->setFrameAddressIsTaken(true);
16397
16398   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16399     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16400     // is not possible to crawl up the stack without looking at the unwind codes
16401     // simultaneously.
16402     int FrameAddrIndex = FuncInfo->getFAIndex();
16403     if (!FrameAddrIndex) {
16404       // Set up a frame object for the return address.
16405       unsigned SlotSize = RegInfo->getSlotSize();
16406       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16407           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16408       FuncInfo->setFAIndex(FrameAddrIndex);
16409     }
16410     return DAG.getFrameIndex(FrameAddrIndex, VT);
16411   }
16412
16413   unsigned FrameReg =
16414       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16415   SDLoc dl(Op);  // FIXME probably not meaningful
16416   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16417   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16418           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16419          "Invalid Frame Register!");
16420   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16421   while (Depth--)
16422     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16423                             MachinePointerInfo(),
16424                             false, false, false, 0);
16425   return FrameAddr;
16426 }
16427
16428 // FIXME? Maybe this could be a TableGen attribute on some registers and
16429 // this table could be generated automatically from RegInfo.
16430 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16431                                               SelectionDAG &DAG) const {
16432   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16433   const MachineFunction &MF = DAG.getMachineFunction();
16434
16435   unsigned Reg = StringSwitch<unsigned>(RegName)
16436                        .Case("esp", X86::ESP)
16437                        .Case("rsp", X86::RSP)
16438                        .Case("ebp", X86::EBP)
16439                        .Case("rbp", X86::RBP)
16440                        .Default(0);
16441
16442   if (Reg == X86::EBP || Reg == X86::RBP) {
16443     if (!TFI.hasFP(MF))
16444       report_fatal_error("register " + StringRef(RegName) +
16445                          " is allocatable: function has no frame pointer");
16446 #ifndef NDEBUG
16447     else {
16448       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16449       unsigned FrameReg =
16450           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16451       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16452              "Invalid Frame Register!");
16453     }
16454 #endif
16455   }
16456
16457   if (Reg)
16458     return Reg;
16459
16460   report_fatal_error("Invalid register name global variable");
16461 }
16462
16463 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16464                                                      SelectionDAG &DAG) const {
16465   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16466   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16467 }
16468
16469 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16470   SDValue Chain     = Op.getOperand(0);
16471   SDValue Offset    = Op.getOperand(1);
16472   SDValue Handler   = Op.getOperand(2);
16473   SDLoc dl      (Op);
16474
16475   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16476   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16477   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16478   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16479           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16480          "Invalid Frame Register!");
16481   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16482   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16483
16484   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16485                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16486                                                        dl));
16487   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16488   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16489                        false, false, 0);
16490   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16491
16492   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16493                      DAG.getRegister(StoreAddrReg, PtrVT));
16494 }
16495
16496 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16497                                                SelectionDAG &DAG) const {
16498   SDLoc DL(Op);
16499   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16500                      DAG.getVTList(MVT::i32, MVT::Other),
16501                      Op.getOperand(0), Op.getOperand(1));
16502 }
16503
16504 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16505                                                 SelectionDAG &DAG) const {
16506   SDLoc DL(Op);
16507   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16508                      Op.getOperand(0), Op.getOperand(1));
16509 }
16510
16511 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16512   return Op.getOperand(0);
16513 }
16514
16515 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16516                                                 SelectionDAG &DAG) const {
16517   SDValue Root = Op.getOperand(0);
16518   SDValue Trmp = Op.getOperand(1); // trampoline
16519   SDValue FPtr = Op.getOperand(2); // nested function
16520   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16521   SDLoc dl (Op);
16522
16523   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16524   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16525
16526   if (Subtarget->is64Bit()) {
16527     SDValue OutChains[6];
16528
16529     // Large code-model.
16530     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16531     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16532
16533     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16534     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16535
16536     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16537
16538     // Load the pointer to the nested function into R11.
16539     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16540     SDValue Addr = Trmp;
16541     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16542                                 Addr, MachinePointerInfo(TrmpAddr),
16543                                 false, false, 0);
16544
16545     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16546                        DAG.getConstant(2, dl, MVT::i64));
16547     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16548                                 MachinePointerInfo(TrmpAddr, 2),
16549                                 false, false, 2);
16550
16551     // Load the 'nest' parameter value into R10.
16552     // R10 is specified in X86CallingConv.td
16553     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16554     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16555                        DAG.getConstant(10, dl, MVT::i64));
16556     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16557                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16558                                 false, false, 0);
16559
16560     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16561                        DAG.getConstant(12, dl, MVT::i64));
16562     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16563                                 MachinePointerInfo(TrmpAddr, 12),
16564                                 false, false, 2);
16565
16566     // Jump to the nested function.
16567     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16568     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16569                        DAG.getConstant(20, dl, MVT::i64));
16570     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16571                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16572                                 false, false, 0);
16573
16574     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16575     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16576                        DAG.getConstant(22, dl, MVT::i64));
16577     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16578                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16579                                 false, false, 0);
16580
16581     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16582   } else {
16583     const Function *Func =
16584       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16585     CallingConv::ID CC = Func->getCallingConv();
16586     unsigned NestReg;
16587
16588     switch (CC) {
16589     default:
16590       llvm_unreachable("Unsupported calling convention");
16591     case CallingConv::C:
16592     case CallingConv::X86_StdCall: {
16593       // Pass 'nest' parameter in ECX.
16594       // Must be kept in sync with X86CallingConv.td
16595       NestReg = X86::ECX;
16596
16597       // Check that ECX wasn't needed by an 'inreg' parameter.
16598       FunctionType *FTy = Func->getFunctionType();
16599       const AttributeSet &Attrs = Func->getAttributes();
16600
16601       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16602         unsigned InRegCount = 0;
16603         unsigned Idx = 1;
16604
16605         for (FunctionType::param_iterator I = FTy->param_begin(),
16606              E = FTy->param_end(); I != E; ++I, ++Idx)
16607           if (Attrs.hasAttribute(Idx, Attribute::InReg)) {
16608             auto &DL = DAG.getDataLayout();
16609             // FIXME: should only count parameters that are lowered to integers.
16610             InRegCount += (DL.getTypeSizeInBits(*I) + 31) / 32;
16611           }
16612
16613         if (InRegCount > 2) {
16614           report_fatal_error("Nest register in use - reduce number of inreg"
16615                              " parameters!");
16616         }
16617       }
16618       break;
16619     }
16620     case CallingConv::X86_FastCall:
16621     case CallingConv::X86_ThisCall:
16622     case CallingConv::Fast:
16623       // Pass 'nest' parameter in EAX.
16624       // Must be kept in sync with X86CallingConv.td
16625       NestReg = X86::EAX;
16626       break;
16627     }
16628
16629     SDValue OutChains[4];
16630     SDValue Addr, Disp;
16631
16632     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16633                        DAG.getConstant(10, dl, MVT::i32));
16634     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16635
16636     // This is storing the opcode for MOV32ri.
16637     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16638     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16639     OutChains[0] = DAG.getStore(Root, dl,
16640                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16641                                 Trmp, MachinePointerInfo(TrmpAddr),
16642                                 false, false, 0);
16643
16644     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16645                        DAG.getConstant(1, dl, MVT::i32));
16646     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16647                                 MachinePointerInfo(TrmpAddr, 1),
16648                                 false, false, 1);
16649
16650     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16651     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16652                        DAG.getConstant(5, dl, MVT::i32));
16653     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16654                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16655                                 false, false, 1);
16656
16657     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16658                        DAG.getConstant(6, dl, MVT::i32));
16659     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16660                                 MachinePointerInfo(TrmpAddr, 6),
16661                                 false, false, 1);
16662
16663     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16664   }
16665 }
16666
16667 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16668                                             SelectionDAG &DAG) const {
16669   /*
16670    The rounding mode is in bits 11:10 of FPSR, and has the following
16671    settings:
16672      00 Round to nearest
16673      01 Round to -inf
16674      10 Round to +inf
16675      11 Round to 0
16676
16677   FLT_ROUNDS, on the other hand, expects the following:
16678     -1 Undefined
16679      0 Round to 0
16680      1 Round to nearest
16681      2 Round to +inf
16682      3 Round to -inf
16683
16684   To perform the conversion, we do:
16685     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16686   */
16687
16688   MachineFunction &MF = DAG.getMachineFunction();
16689   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16690   unsigned StackAlignment = TFI.getStackAlignment();
16691   MVT VT = Op.getSimpleValueType();
16692   SDLoc DL(Op);
16693
16694   // Save FP Control Word to stack slot
16695   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16696   SDValue StackSlot =
16697       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16698
16699   MachineMemOperand *MMO =
16700    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16701                            MachineMemOperand::MOStore, 2, 2);
16702
16703   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16704   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16705                                           DAG.getVTList(MVT::Other),
16706                                           Ops, MVT::i16, MMO);
16707
16708   // Load FP Control Word from stack slot
16709   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16710                             MachinePointerInfo(), false, false, false, 0);
16711
16712   // Transform as necessary
16713   SDValue CWD1 =
16714     DAG.getNode(ISD::SRL, DL, MVT::i16,
16715                 DAG.getNode(ISD::AND, DL, MVT::i16,
16716                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16717                 DAG.getConstant(11, DL, MVT::i8));
16718   SDValue CWD2 =
16719     DAG.getNode(ISD::SRL, DL, MVT::i16,
16720                 DAG.getNode(ISD::AND, DL, MVT::i16,
16721                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16722                 DAG.getConstant(9, DL, MVT::i8));
16723
16724   SDValue RetVal =
16725     DAG.getNode(ISD::AND, DL, MVT::i16,
16726                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16727                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16728                             DAG.getConstant(1, DL, MVT::i16)),
16729                 DAG.getConstant(3, DL, MVT::i16));
16730
16731   return DAG.getNode((VT.getSizeInBits() < 16 ?
16732                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16733 }
16734
16735 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16736   MVT VT = Op.getSimpleValueType();
16737   EVT OpVT = VT;
16738   unsigned NumBits = VT.getSizeInBits();
16739   SDLoc dl(Op);
16740
16741   Op = Op.getOperand(0);
16742   if (VT == MVT::i8) {
16743     // Zero extend to i32 since there is not an i8 bsr.
16744     OpVT = MVT::i32;
16745     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16746   }
16747
16748   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16749   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16750   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16751
16752   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16753   SDValue Ops[] = {
16754     Op,
16755     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16756     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16757     Op.getValue(1)
16758   };
16759   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16760
16761   // Finally xor with NumBits-1.
16762   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16763                    DAG.getConstant(NumBits - 1, dl, OpVT));
16764
16765   if (VT == MVT::i8)
16766     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16767   return Op;
16768 }
16769
16770 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16771   MVT VT = Op.getSimpleValueType();
16772   EVT OpVT = VT;
16773   unsigned NumBits = VT.getSizeInBits();
16774   SDLoc dl(Op);
16775
16776   Op = Op.getOperand(0);
16777   if (VT == MVT::i8) {
16778     // Zero extend to i32 since there is not an i8 bsr.
16779     OpVT = MVT::i32;
16780     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16781   }
16782
16783   // Issue a bsr (scan bits in reverse).
16784   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16785   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16786
16787   // And xor with NumBits-1.
16788   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16789                    DAG.getConstant(NumBits - 1, dl, OpVT));
16790
16791   if (VT == MVT::i8)
16792     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16793   return Op;
16794 }
16795
16796 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16797   MVT VT = Op.getSimpleValueType();
16798   unsigned NumBits = VT.getSizeInBits();
16799   SDLoc dl(Op);
16800   Op = Op.getOperand(0);
16801
16802   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16803   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16804   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16805
16806   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16807   SDValue Ops[] = {
16808     Op,
16809     DAG.getConstant(NumBits, dl, VT),
16810     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16811     Op.getValue(1)
16812   };
16813   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16814 }
16815
16816 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16817 // ones, and then concatenate the result back.
16818 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16819   MVT VT = Op.getSimpleValueType();
16820
16821   assert(VT.is256BitVector() && VT.isInteger() &&
16822          "Unsupported value type for operation");
16823
16824   unsigned NumElems = VT.getVectorNumElements();
16825   SDLoc dl(Op);
16826
16827   // Extract the LHS vectors
16828   SDValue LHS = Op.getOperand(0);
16829   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16830   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16831
16832   // Extract the RHS vectors
16833   SDValue RHS = Op.getOperand(1);
16834   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16835   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16836
16837   MVT EltVT = VT.getVectorElementType();
16838   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16839
16840   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16841                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16842                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16843 }
16844
16845 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16846   if (Op.getValueType() == MVT::i1)
16847     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16848                        Op.getOperand(0), Op.getOperand(1));
16849   assert(Op.getSimpleValueType().is256BitVector() &&
16850          Op.getSimpleValueType().isInteger() &&
16851          "Only handle AVX 256-bit vector integer operation");
16852   return Lower256IntArith(Op, DAG);
16853 }
16854
16855 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16856   if (Op.getValueType() == MVT::i1)
16857     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16858                        Op.getOperand(0), Op.getOperand(1));
16859   assert(Op.getSimpleValueType().is256BitVector() &&
16860          Op.getSimpleValueType().isInteger() &&
16861          "Only handle AVX 256-bit vector integer operation");
16862   return Lower256IntArith(Op, DAG);
16863 }
16864
16865 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16866                         SelectionDAG &DAG) {
16867   SDLoc dl(Op);
16868   MVT VT = Op.getSimpleValueType();
16869
16870   if (VT == MVT::i1)
16871     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16872
16873   // Decompose 256-bit ops into smaller 128-bit ops.
16874   if (VT.is256BitVector() && !Subtarget->hasInt256())
16875     return Lower256IntArith(Op, DAG);
16876
16877   SDValue A = Op.getOperand(0);
16878   SDValue B = Op.getOperand(1);
16879
16880   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16881   // pairs, multiply and truncate.
16882   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16883     if (Subtarget->hasInt256()) {
16884       if (VT == MVT::v32i8) {
16885         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16886         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16887         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16888         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16889         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16890         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16891         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16892         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16893                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16894                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16895       }
16896
16897       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16898       return DAG.getNode(
16899           ISD::TRUNCATE, dl, VT,
16900           DAG.getNode(ISD::MUL, dl, ExVT,
16901                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16902                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16903     }
16904
16905     assert(VT == MVT::v16i8 &&
16906            "Pre-AVX2 support only supports v16i8 multiplication");
16907     MVT ExVT = MVT::v8i16;
16908
16909     // Extract the lo parts and sign extend to i16
16910     SDValue ALo, BLo;
16911     if (Subtarget->hasSSE41()) {
16912       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16913       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16914     } else {
16915       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16916                               -1, 4, -1, 5, -1, 6, -1, 7};
16917       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16918       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16919       ALo = DAG.getBitcast(ExVT, ALo);
16920       BLo = DAG.getBitcast(ExVT, BLo);
16921       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16922       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16923     }
16924
16925     // Extract the hi parts and sign extend to i16
16926     SDValue AHi, BHi;
16927     if (Subtarget->hasSSE41()) {
16928       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16929                               -1, -1, -1, -1, -1, -1, -1, -1};
16930       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16931       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16932       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16933       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16934     } else {
16935       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16936                               -1, 12, -1, 13, -1, 14, -1, 15};
16937       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16938       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16939       AHi = DAG.getBitcast(ExVT, AHi);
16940       BHi = DAG.getBitcast(ExVT, BHi);
16941       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16942       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16943     }
16944
16945     // Multiply, mask the lower 8bits of the lo/hi results and pack
16946     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16947     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16948     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16949     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16950     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16951   }
16952
16953   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16954   if (VT == MVT::v4i32) {
16955     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16956            "Should not custom lower when pmuldq is available!");
16957
16958     // Extract the odd parts.
16959     static const int UnpackMask[] = { 1, -1, 3, -1 };
16960     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16961     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16962
16963     // Multiply the even parts.
16964     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16965     // Now multiply odd parts.
16966     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16967
16968     Evens = DAG.getBitcast(VT, Evens);
16969     Odds = DAG.getBitcast(VT, Odds);
16970
16971     // Merge the two vectors back together with a shuffle. This expands into 2
16972     // shuffles.
16973     static const int ShufMask[] = { 0, 4, 2, 6 };
16974     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16975   }
16976
16977   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16978          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16979
16980   //  Ahi = psrlqi(a, 32);
16981   //  Bhi = psrlqi(b, 32);
16982   //
16983   //  AloBlo = pmuludq(a, b);
16984   //  AloBhi = pmuludq(a, Bhi);
16985   //  AhiBlo = pmuludq(Ahi, b);
16986
16987   //  AloBhi = psllqi(AloBhi, 32);
16988   //  AhiBlo = psllqi(AhiBlo, 32);
16989   //  return AloBlo + AloBhi + AhiBlo;
16990
16991   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16992   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16993
16994   SDValue AhiBlo = Ahi;
16995   SDValue AloBhi = Bhi;
16996   // Bit cast to 32-bit vectors for MULUDQ
16997   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16998                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16999   A = DAG.getBitcast(MulVT, A);
17000   B = DAG.getBitcast(MulVT, B);
17001   Ahi = DAG.getBitcast(MulVT, Ahi);
17002   Bhi = DAG.getBitcast(MulVT, Bhi);
17003
17004   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
17005   // After shifting right const values the result may be all-zero.
17006   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
17007     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
17008     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
17009   }
17010   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
17011     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
17012     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
17013   }
17014
17015   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
17016   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
17017 }
17018
17019 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
17020   assert(Subtarget->isTargetWin64() && "Unexpected target");
17021   EVT VT = Op.getValueType();
17022   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
17023          "Unexpected return type for lowering");
17024
17025   RTLIB::Libcall LC;
17026   bool isSigned;
17027   switch (Op->getOpcode()) {
17028   default: llvm_unreachable("Unexpected request for libcall!");
17029   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
17030   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
17031   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
17032   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
17033   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
17034   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
17035   }
17036
17037   SDLoc dl(Op);
17038   SDValue InChain = DAG.getEntryNode();
17039
17040   TargetLowering::ArgListTy Args;
17041   TargetLowering::ArgListEntry Entry;
17042   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
17043     EVT ArgVT = Op->getOperand(i).getValueType();
17044     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
17045            "Unexpected argument type for lowering");
17046     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
17047     Entry.Node = StackPtr;
17048     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
17049                            false, false, 16);
17050     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17051     Entry.Ty = PointerType::get(ArgTy,0);
17052     Entry.isSExt = false;
17053     Entry.isZExt = false;
17054     Args.push_back(Entry);
17055   }
17056
17057   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
17058                                          getPointerTy(DAG.getDataLayout()));
17059
17060   TargetLowering::CallLoweringInfo CLI(DAG);
17061   CLI.setDebugLoc(dl).setChain(InChain)
17062     .setCallee(getLibcallCallingConv(LC),
17063                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
17064                Callee, std::move(Args), 0)
17065     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
17066
17067   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
17068   return DAG.getBitcast(VT, CallInfo.first);
17069 }
17070
17071 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
17072                              SelectionDAG &DAG) {
17073   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
17074   EVT VT = Op0.getValueType();
17075   SDLoc dl(Op);
17076
17077   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
17078          (VT == MVT::v8i32 && Subtarget->hasInt256()));
17079
17080   // PMULxD operations multiply each even value (starting at 0) of LHS with
17081   // the related value of RHS and produce a widen result.
17082   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17083   // => <2 x i64> <ae|cg>
17084   //
17085   // In other word, to have all the results, we need to perform two PMULxD:
17086   // 1. one with the even values.
17087   // 2. one with the odd values.
17088   // To achieve #2, with need to place the odd values at an even position.
17089   //
17090   // Place the odd value at an even position (basically, shift all values 1
17091   // step to the left):
17092   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17093   // <a|b|c|d> => <b|undef|d|undef>
17094   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17095   // <e|f|g|h> => <f|undef|h|undef>
17096   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17097
17098   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17099   // ints.
17100   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17101   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17102   unsigned Opcode =
17103       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17104   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17105   // => <2 x i64> <ae|cg>
17106   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17107   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17108   // => <2 x i64> <bf|dh>
17109   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17110
17111   // Shuffle it back into the right order.
17112   SDValue Highs, Lows;
17113   if (VT == MVT::v8i32) {
17114     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17115     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17116     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17117     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17118   } else {
17119     const int HighMask[] = {1, 5, 3, 7};
17120     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17121     const int LowMask[] = {0, 4, 2, 6};
17122     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17123   }
17124
17125   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17126   // unsigned multiply.
17127   if (IsSigned && !Subtarget->hasSSE41()) {
17128     SDValue ShAmt = DAG.getConstant(
17129         31, dl,
17130         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17131     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17132                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17133     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17134                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17135
17136     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17137     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17138   }
17139
17140   // The first result of MUL_LOHI is actually the low value, followed by the
17141   // high value.
17142   SDValue Ops[] = {Lows, Highs};
17143   return DAG.getMergeValues(Ops, dl);
17144 }
17145
17146 // Return true if the required (according to Opcode) shift-imm form is natively
17147 // supported by the Subtarget
17148 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17149                                         unsigned Opcode) {
17150   if (VT.getScalarSizeInBits() < 16)
17151     return false;
17152
17153   if (VT.is512BitVector() &&
17154       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17155     return true;
17156
17157   bool LShift = VT.is128BitVector() ||
17158     (VT.is256BitVector() && Subtarget->hasInt256());
17159
17160   bool AShift = LShift && (Subtarget->hasVLX() ||
17161     (VT != MVT::v2i64 && VT != MVT::v4i64));
17162   return (Opcode == ISD::SRA) ? AShift : LShift;
17163 }
17164
17165 // The shift amount is a variable, but it is the same for all vector lanes.
17166 // These instructions are defined together with shift-immediate.
17167 static
17168 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17169                                       unsigned Opcode) {
17170   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17171 }
17172
17173 // Return true if the required (according to Opcode) variable-shift form is
17174 // natively supported by the Subtarget
17175 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17176                                     unsigned Opcode) {
17177
17178   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17179     return false;
17180
17181   // vXi16 supported only on AVX-512, BWI
17182   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17183     return false;
17184
17185   if (VT.is512BitVector() || Subtarget->hasVLX())
17186     return true;
17187
17188   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17189   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17190   return (Opcode == ISD::SRA) ? AShift : LShift;
17191 }
17192
17193 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17194                                          const X86Subtarget *Subtarget) {
17195   MVT VT = Op.getSimpleValueType();
17196   SDLoc dl(Op);
17197   SDValue R = Op.getOperand(0);
17198   SDValue Amt = Op.getOperand(1);
17199
17200   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17201     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17202
17203   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17204     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17205     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17206     SDValue Ex = DAG.getBitcast(ExVT, R);
17207
17208     if (ShiftAmt >= 32) {
17209       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17210       SDValue Upper =
17211           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17212       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17213                                                  ShiftAmt - 32, DAG);
17214       if (VT == MVT::v2i64)
17215         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17216       if (VT == MVT::v4i64)
17217         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17218                                   {9, 1, 11, 3, 13, 5, 15, 7});
17219     } else {
17220       // SRA upper i32, SHL whole i64 and select lower i32.
17221       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17222                                                  ShiftAmt, DAG);
17223       SDValue Lower =
17224           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17225       Lower = DAG.getBitcast(ExVT, Lower);
17226       if (VT == MVT::v2i64)
17227         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17228       if (VT == MVT::v4i64)
17229         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17230                                   {8, 1, 10, 3, 12, 5, 14, 7});
17231     }
17232     return DAG.getBitcast(VT, Ex);
17233   };
17234
17235   // Optimize shl/srl/sra with constant shift amount.
17236   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17237     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17238       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17239
17240       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17241         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17242
17243       // i64 SRA needs to be performed as partial shifts.
17244       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17245           Op.getOpcode() == ISD::SRA)
17246         return ArithmeticShiftRight64(ShiftAmt);
17247
17248       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17249         unsigned NumElts = VT.getVectorNumElements();
17250         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17251
17252         if (Op.getOpcode() == ISD::SHL) {
17253           // Simple i8 add case
17254           if (ShiftAmt == 1)
17255             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17256
17257           // Make a large shift.
17258           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17259                                                    R, ShiftAmt, DAG);
17260           SHL = DAG.getBitcast(VT, SHL);
17261           // Zero out the rightmost bits.
17262           SmallVector<SDValue, 32> V(
17263               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17264           return DAG.getNode(ISD::AND, dl, VT, SHL,
17265                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17266         }
17267         if (Op.getOpcode() == ISD::SRL) {
17268           // Make a large shift.
17269           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17270                                                    R, ShiftAmt, DAG);
17271           SRL = DAG.getBitcast(VT, SRL);
17272           // Zero out the leftmost bits.
17273           SmallVector<SDValue, 32> V(
17274               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17275           return DAG.getNode(ISD::AND, dl, VT, SRL,
17276                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17277         }
17278         if (Op.getOpcode() == ISD::SRA) {
17279           if (ShiftAmt == 7) {
17280             // R s>> 7  ===  R s< 0
17281             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17282             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17283           }
17284
17285           // R s>> a === ((R u>> a) ^ m) - m
17286           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17287           SmallVector<SDValue, 32> V(NumElts,
17288                                      DAG.getConstant(128 >> ShiftAmt, dl,
17289                                                      MVT::i8));
17290           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17291           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17292           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17293           return Res;
17294         }
17295         llvm_unreachable("Unknown shift opcode.");
17296       }
17297     }
17298   }
17299
17300   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17301   if (!Subtarget->is64Bit() &&
17302       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17303       Amt.getOpcode() == ISD::BITCAST &&
17304       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17305     Amt = Amt.getOperand(0);
17306     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17307                      VT.getVectorNumElements();
17308     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17309     uint64_t ShiftAmt = 0;
17310     for (unsigned i = 0; i != Ratio; ++i) {
17311       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17312       if (!C)
17313         return SDValue();
17314       // 6 == Log2(64)
17315       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17316     }
17317     // Check remaining shift amounts.
17318     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17319       uint64_t ShAmt = 0;
17320       for (unsigned j = 0; j != Ratio; ++j) {
17321         ConstantSDNode *C =
17322           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17323         if (!C)
17324           return SDValue();
17325         // 6 == Log2(64)
17326         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17327       }
17328       if (ShAmt != ShiftAmt)
17329         return SDValue();
17330     }
17331
17332     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17333       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17334
17335     if (Op.getOpcode() == ISD::SRA)
17336       return ArithmeticShiftRight64(ShiftAmt);
17337   }
17338
17339   return SDValue();
17340 }
17341
17342 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17343                                         const X86Subtarget* Subtarget) {
17344   MVT VT = Op.getSimpleValueType();
17345   SDLoc dl(Op);
17346   SDValue R = Op.getOperand(0);
17347   SDValue Amt = Op.getOperand(1);
17348
17349   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17350     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17351
17352   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17353     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17354
17355   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17356     SDValue BaseShAmt;
17357     EVT EltVT = VT.getVectorElementType();
17358
17359     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17360       // Check if this build_vector node is doing a splat.
17361       // If so, then set BaseShAmt equal to the splat value.
17362       BaseShAmt = BV->getSplatValue();
17363       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17364         BaseShAmt = SDValue();
17365     } else {
17366       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17367         Amt = Amt.getOperand(0);
17368
17369       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17370       if (SVN && SVN->isSplat()) {
17371         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17372         SDValue InVec = Amt.getOperand(0);
17373         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17374           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17375                  "Unexpected shuffle index found!");
17376           BaseShAmt = InVec.getOperand(SplatIdx);
17377         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17378            if (ConstantSDNode *C =
17379                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17380              if (C->getZExtValue() == SplatIdx)
17381                BaseShAmt = InVec.getOperand(1);
17382            }
17383         }
17384
17385         if (!BaseShAmt)
17386           // Avoid introducing an extract element from a shuffle.
17387           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17388                                   DAG.getIntPtrConstant(SplatIdx, dl));
17389       }
17390     }
17391
17392     if (BaseShAmt.getNode()) {
17393       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17394       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17395         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17396       else if (EltVT.bitsLT(MVT::i32))
17397         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17398
17399       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17400     }
17401   }
17402
17403   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17404   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17405       Amt.getOpcode() == ISD::BITCAST &&
17406       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17407     Amt = Amt.getOperand(0);
17408     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17409                      VT.getVectorNumElements();
17410     std::vector<SDValue> Vals(Ratio);
17411     for (unsigned i = 0; i != Ratio; ++i)
17412       Vals[i] = Amt.getOperand(i);
17413     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17414       for (unsigned j = 0; j != Ratio; ++j)
17415         if (Vals[j] != Amt.getOperand(i + j))
17416           return SDValue();
17417     }
17418
17419     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17420       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17421   }
17422   return SDValue();
17423 }
17424
17425 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17426                           SelectionDAG &DAG) {
17427   MVT VT = Op.getSimpleValueType();
17428   SDLoc dl(Op);
17429   SDValue R = Op.getOperand(0);
17430   SDValue Amt = Op.getOperand(1);
17431
17432   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17433   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17434
17435   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17436     return V;
17437
17438   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17439       return V;
17440
17441   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17442     return Op;
17443
17444   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17445   // shifts per-lane and then shuffle the partial results back together.
17446   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17447     // Splat the shift amounts so the scalar shifts above will catch it.
17448     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17449     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17450     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17451     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17452     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17453   }
17454
17455   // If possible, lower this packed shift into a vector multiply instead of
17456   // expanding it into a sequence of scalar shifts.
17457   // Do this only if the vector shift count is a constant build_vector.
17458   if (Op.getOpcode() == ISD::SHL &&
17459       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17460        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17461       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17462     SmallVector<SDValue, 8> Elts;
17463     EVT SVT = VT.getScalarType();
17464     unsigned SVTBits = SVT.getSizeInBits();
17465     const APInt &One = APInt(SVTBits, 1);
17466     unsigned NumElems = VT.getVectorNumElements();
17467
17468     for (unsigned i=0; i !=NumElems; ++i) {
17469       SDValue Op = Amt->getOperand(i);
17470       if (Op->getOpcode() == ISD::UNDEF) {
17471         Elts.push_back(Op);
17472         continue;
17473       }
17474
17475       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17476       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17477       uint64_t ShAmt = C.getZExtValue();
17478       if (ShAmt >= SVTBits) {
17479         Elts.push_back(DAG.getUNDEF(SVT));
17480         continue;
17481       }
17482       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17483     }
17484     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17485     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17486   }
17487
17488   // Lower SHL with variable shift amount.
17489   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17490     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17491
17492     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17493                      DAG.getConstant(0x3f800000U, dl, VT));
17494     Op = DAG.getBitcast(MVT::v4f32, Op);
17495     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17496     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17497   }
17498
17499   // If possible, lower this shift as a sequence of two shifts by
17500   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17501   // Example:
17502   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17503   //
17504   // Could be rewritten as:
17505   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17506   //
17507   // The advantage is that the two shifts from the example would be
17508   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17509   // the vector shift into four scalar shifts plus four pairs of vector
17510   // insert/extract.
17511   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17512       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17513     unsigned TargetOpcode = X86ISD::MOVSS;
17514     bool CanBeSimplified;
17515     // The splat value for the first packed shift (the 'X' from the example).
17516     SDValue Amt1 = Amt->getOperand(0);
17517     // The splat value for the second packed shift (the 'Y' from the example).
17518     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17519                                         Amt->getOperand(2);
17520
17521     // See if it is possible to replace this node with a sequence of
17522     // two shifts followed by a MOVSS/MOVSD
17523     if (VT == MVT::v4i32) {
17524       // Check if it is legal to use a MOVSS.
17525       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17526                         Amt2 == Amt->getOperand(3);
17527       if (!CanBeSimplified) {
17528         // Otherwise, check if we can still simplify this node using a MOVSD.
17529         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17530                           Amt->getOperand(2) == Amt->getOperand(3);
17531         TargetOpcode = X86ISD::MOVSD;
17532         Amt2 = Amt->getOperand(2);
17533       }
17534     } else {
17535       // Do similar checks for the case where the machine value type
17536       // is MVT::v8i16.
17537       CanBeSimplified = Amt1 == Amt->getOperand(1);
17538       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17539         CanBeSimplified = Amt2 == Amt->getOperand(i);
17540
17541       if (!CanBeSimplified) {
17542         TargetOpcode = X86ISD::MOVSD;
17543         CanBeSimplified = true;
17544         Amt2 = Amt->getOperand(4);
17545         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17546           CanBeSimplified = Amt1 == Amt->getOperand(i);
17547         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17548           CanBeSimplified = Amt2 == Amt->getOperand(j);
17549       }
17550     }
17551
17552     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17553         isa<ConstantSDNode>(Amt2)) {
17554       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17555       EVT CastVT = MVT::v4i32;
17556       SDValue Splat1 =
17557         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17558       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17559       SDValue Splat2 =
17560         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17561       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17562       if (TargetOpcode == X86ISD::MOVSD)
17563         CastVT = MVT::v2i64;
17564       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17565       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17566       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17567                                             BitCast1, DAG);
17568       return DAG.getBitcast(VT, Result);
17569     }
17570   }
17571
17572   // v4i32 Non Uniform Shifts.
17573   // If the shift amount is constant we can shift each lane using the SSE2
17574   // immediate shifts, else we need to zero-extend each lane to the lower i64
17575   // and shift using the SSE2 variable shifts.
17576   // The separate results can then be blended together.
17577   if (VT == MVT::v4i32) {
17578     unsigned Opc = Op.getOpcode();
17579     SDValue Amt0, Amt1, Amt2, Amt3;
17580     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17581       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17582       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17583       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17584       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17585     } else {
17586       // ISD::SHL is handled above but we include it here for completeness.
17587       switch (Opc) {
17588       default:
17589         llvm_unreachable("Unknown target vector shift node");
17590       case ISD::SHL:
17591         Opc = X86ISD::VSHL;
17592         break;
17593       case ISD::SRL:
17594         Opc = X86ISD::VSRL;
17595         break;
17596       case ISD::SRA:
17597         Opc = X86ISD::VSRA;
17598         break;
17599       }
17600       // The SSE2 shifts use the lower i64 as the same shift amount for
17601       // all lanes and the upper i64 is ignored. These shuffle masks
17602       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17603       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17604       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17605       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17606       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17607       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17608     }
17609
17610     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17611     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17612     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17613     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17614     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17615     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17616     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17617   }
17618
17619   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17620     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17621     unsigned ShiftOpcode = Op->getOpcode();
17622
17623     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17624       // On SSE41 targets we make use of the fact that VSELECT lowers
17625       // to PBLENDVB which selects bytes based just on the sign bit.
17626       if (Subtarget->hasSSE41()) {
17627         V0 = DAG.getBitcast(VT, V0);
17628         V1 = DAG.getBitcast(VT, V1);
17629         Sel = DAG.getBitcast(VT, Sel);
17630         return DAG.getBitcast(SelVT,
17631                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17632       }
17633       // On pre-SSE41 targets we test for the sign bit by comparing to
17634       // zero - a negative value will set all bits of the lanes to true
17635       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17636       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17637       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17638       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17639     };
17640
17641     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17642     // We can safely do this using i16 shifts as we're only interested in
17643     // the 3 lower bits of each byte.
17644     Amt = DAG.getBitcast(ExtVT, Amt);
17645     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17646     Amt = DAG.getBitcast(VT, Amt);
17647
17648     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17649       // r = VSELECT(r, shift(r, 4), a);
17650       SDValue M =
17651           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17652       R = SignBitSelect(VT, Amt, M, R);
17653
17654       // a += a
17655       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17656
17657       // r = VSELECT(r, shift(r, 2), a);
17658       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17659       R = SignBitSelect(VT, Amt, M, R);
17660
17661       // a += a
17662       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17663
17664       // return VSELECT(r, shift(r, 1), a);
17665       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17666       R = SignBitSelect(VT, Amt, M, R);
17667       return R;
17668     }
17669
17670     if (Op->getOpcode() == ISD::SRA) {
17671       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17672       // so we can correctly sign extend. We don't care what happens to the
17673       // lower byte.
17674       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17675       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17676       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17677       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17678       ALo = DAG.getBitcast(ExtVT, ALo);
17679       AHi = DAG.getBitcast(ExtVT, AHi);
17680       RLo = DAG.getBitcast(ExtVT, RLo);
17681       RHi = DAG.getBitcast(ExtVT, RHi);
17682
17683       // r = VSELECT(r, shift(r, 4), a);
17684       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17685                                 DAG.getConstant(4, dl, ExtVT));
17686       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17687                                 DAG.getConstant(4, dl, ExtVT));
17688       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17689       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17690
17691       // a += a
17692       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17693       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17694
17695       // r = VSELECT(r, shift(r, 2), a);
17696       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17697                         DAG.getConstant(2, dl, ExtVT));
17698       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17699                         DAG.getConstant(2, dl, ExtVT));
17700       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17701       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17702
17703       // a += a
17704       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17705       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17706
17707       // r = VSELECT(r, shift(r, 1), a);
17708       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17709                         DAG.getConstant(1, dl, ExtVT));
17710       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17711                         DAG.getConstant(1, dl, ExtVT));
17712       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17713       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17714
17715       // Logical shift the result back to the lower byte, leaving a zero upper
17716       // byte
17717       // meaning that we can safely pack with PACKUSWB.
17718       RLo =
17719           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17720       RHi =
17721           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17722       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17723     }
17724   }
17725
17726   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17727   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17728   // solution better.
17729   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17730     MVT ExtVT = MVT::v8i32;
17731     unsigned ExtOpc =
17732         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17733     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17734     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17735     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17736                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17737   }
17738
17739   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17740     MVT ExtVT = MVT::v8i32;
17741     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17742     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17743     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17744     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17745     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17746     ALo = DAG.getBitcast(ExtVT, ALo);
17747     AHi = DAG.getBitcast(ExtVT, AHi);
17748     RLo = DAG.getBitcast(ExtVT, RLo);
17749     RHi = DAG.getBitcast(ExtVT, RHi);
17750     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17751     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17752     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17753     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17754     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17755   }
17756
17757   if (VT == MVT::v8i16) {
17758     unsigned ShiftOpcode = Op->getOpcode();
17759
17760     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17761       // On SSE41 targets we make use of the fact that VSELECT lowers
17762       // to PBLENDVB which selects bytes based just on the sign bit.
17763       if (Subtarget->hasSSE41()) {
17764         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17765         V0 = DAG.getBitcast(ExtVT, V0);
17766         V1 = DAG.getBitcast(ExtVT, V1);
17767         Sel = DAG.getBitcast(ExtVT, Sel);
17768         return DAG.getBitcast(
17769             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17770       }
17771       // On pre-SSE41 targets we splat the sign bit - a negative value will
17772       // set all bits of the lanes to true and VSELECT uses that in
17773       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17774       SDValue C =
17775           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17776       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17777     };
17778
17779     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17780     if (Subtarget->hasSSE41()) {
17781       // On SSE41 targets we need to replicate the shift mask in both
17782       // bytes for PBLENDVB.
17783       Amt = DAG.getNode(
17784           ISD::OR, dl, VT,
17785           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17786           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17787     } else {
17788       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17789     }
17790
17791     // r = VSELECT(r, shift(r, 8), a);
17792     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17793     R = SignBitSelect(Amt, M, R);
17794
17795     // a += a
17796     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17797
17798     // r = VSELECT(r, shift(r, 4), a);
17799     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17800     R = SignBitSelect(Amt, M, R);
17801
17802     // a += a
17803     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17804
17805     // r = VSELECT(r, shift(r, 2), a);
17806     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17807     R = SignBitSelect(Amt, M, R);
17808
17809     // a += a
17810     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17811
17812     // return VSELECT(r, shift(r, 1), a);
17813     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17814     R = SignBitSelect(Amt, M, R);
17815     return R;
17816   }
17817
17818   // Decompose 256-bit shifts into smaller 128-bit shifts.
17819   if (VT.is256BitVector()) {
17820     unsigned NumElems = VT.getVectorNumElements();
17821     MVT EltVT = VT.getVectorElementType();
17822     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17823
17824     // Extract the two vectors
17825     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17826     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17827
17828     // Recreate the shift amount vectors
17829     SDValue Amt1, Amt2;
17830     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17831       // Constant shift amount
17832       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17833       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17834       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17835
17836       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17837       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17838     } else {
17839       // Variable shift amount
17840       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17841       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17842     }
17843
17844     // Issue new vector shifts for the smaller types
17845     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17846     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17847
17848     // Concatenate the result back
17849     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17850   }
17851
17852   return SDValue();
17853 }
17854
17855 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17856   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17857   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17858   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17859   // has only one use.
17860   SDNode *N = Op.getNode();
17861   SDValue LHS = N->getOperand(0);
17862   SDValue RHS = N->getOperand(1);
17863   unsigned BaseOp = 0;
17864   unsigned Cond = 0;
17865   SDLoc DL(Op);
17866   switch (Op.getOpcode()) {
17867   default: llvm_unreachable("Unknown ovf instruction!");
17868   case ISD::SADDO:
17869     // A subtract of one will be selected as a INC. Note that INC doesn't
17870     // set CF, so we can't do this for UADDO.
17871     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17872       if (C->isOne()) {
17873         BaseOp = X86ISD::INC;
17874         Cond = X86::COND_O;
17875         break;
17876       }
17877     BaseOp = X86ISD::ADD;
17878     Cond = X86::COND_O;
17879     break;
17880   case ISD::UADDO:
17881     BaseOp = X86ISD::ADD;
17882     Cond = X86::COND_B;
17883     break;
17884   case ISD::SSUBO:
17885     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17886     // set CF, so we can't do this for USUBO.
17887     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17888       if (C->isOne()) {
17889         BaseOp = X86ISD::DEC;
17890         Cond = X86::COND_O;
17891         break;
17892       }
17893     BaseOp = X86ISD::SUB;
17894     Cond = X86::COND_O;
17895     break;
17896   case ISD::USUBO:
17897     BaseOp = X86ISD::SUB;
17898     Cond = X86::COND_B;
17899     break;
17900   case ISD::SMULO:
17901     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17902     Cond = X86::COND_O;
17903     break;
17904   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17905     if (N->getValueType(0) == MVT::i8) {
17906       BaseOp = X86ISD::UMUL8;
17907       Cond = X86::COND_O;
17908       break;
17909     }
17910     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17911                                  MVT::i32);
17912     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17913
17914     SDValue SetCC =
17915       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17916                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17917                   SDValue(Sum.getNode(), 2));
17918
17919     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17920   }
17921   }
17922
17923   // Also sets EFLAGS.
17924   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17925   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17926
17927   SDValue SetCC =
17928     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17929                 DAG.getConstant(Cond, DL, MVT::i32),
17930                 SDValue(Sum.getNode(), 1));
17931
17932   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17933 }
17934
17935 /// Returns true if the operand type is exactly twice the native width, and
17936 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17937 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17938 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17939 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17940   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17941
17942   if (OpWidth == 64)
17943     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17944   else if (OpWidth == 128)
17945     return Subtarget->hasCmpxchg16b();
17946   else
17947     return false;
17948 }
17949
17950 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17951   return needsCmpXchgNb(SI->getValueOperand()->getType());
17952 }
17953
17954 // Note: this turns large loads into lock cmpxchg8b/16b.
17955 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17956 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17957   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17958   return needsCmpXchgNb(PTy->getElementType());
17959 }
17960
17961 TargetLoweringBase::AtomicRMWExpansionKind
17962 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17963   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17964   const Type *MemType = AI->getType();
17965
17966   // If the operand is too big, we must see if cmpxchg8/16b is available
17967   // and default to library calls otherwise.
17968   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17969     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17970                                    : AtomicRMWExpansionKind::None;
17971   }
17972
17973   AtomicRMWInst::BinOp Op = AI->getOperation();
17974   switch (Op) {
17975   default:
17976     llvm_unreachable("Unknown atomic operation");
17977   case AtomicRMWInst::Xchg:
17978   case AtomicRMWInst::Add:
17979   case AtomicRMWInst::Sub:
17980     // It's better to use xadd, xsub or xchg for these in all cases.
17981     return AtomicRMWExpansionKind::None;
17982   case AtomicRMWInst::Or:
17983   case AtomicRMWInst::And:
17984   case AtomicRMWInst::Xor:
17985     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17986     // prefix to a normal instruction for these operations.
17987     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17988                             : AtomicRMWExpansionKind::None;
17989   case AtomicRMWInst::Nand:
17990   case AtomicRMWInst::Max:
17991   case AtomicRMWInst::Min:
17992   case AtomicRMWInst::UMax:
17993   case AtomicRMWInst::UMin:
17994     // These always require a non-trivial set of data operations on x86. We must
17995     // use a cmpxchg loop.
17996     return AtomicRMWExpansionKind::CmpXChg;
17997   }
17998 }
17999
18000 static bool hasMFENCE(const X86Subtarget& Subtarget) {
18001   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
18002   // no-sse2). There isn't any reason to disable it if the target processor
18003   // supports it.
18004   return Subtarget.hasSSE2() || Subtarget.is64Bit();
18005 }
18006
18007 LoadInst *
18008 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
18009   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
18010   const Type *MemType = AI->getType();
18011   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
18012   // there is no benefit in turning such RMWs into loads, and it is actually
18013   // harmful as it introduces a mfence.
18014   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
18015     return nullptr;
18016
18017   auto Builder = IRBuilder<>(AI);
18018   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
18019   auto SynchScope = AI->getSynchScope();
18020   // We must restrict the ordering to avoid generating loads with Release or
18021   // ReleaseAcquire orderings.
18022   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
18023   auto Ptr = AI->getPointerOperand();
18024
18025   // Before the load we need a fence. Here is an example lifted from
18026   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
18027   // is required:
18028   // Thread 0:
18029   //   x.store(1, relaxed);
18030   //   r1 = y.fetch_add(0, release);
18031   // Thread 1:
18032   //   y.fetch_add(42, acquire);
18033   //   r2 = x.load(relaxed);
18034   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
18035   // lowered to just a load without a fence. A mfence flushes the store buffer,
18036   // making the optimization clearly correct.
18037   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
18038   // otherwise, we might be able to be more agressive on relaxed idempotent
18039   // rmw. In practice, they do not look useful, so we don't try to be
18040   // especially clever.
18041   if (SynchScope == SingleThread)
18042     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
18043     // the IR level, so we must wrap it in an intrinsic.
18044     return nullptr;
18045
18046   if (!hasMFENCE(*Subtarget))
18047     // FIXME: it might make sense to use a locked operation here but on a
18048     // different cache-line to prevent cache-line bouncing. In practice it
18049     // is probably a small win, and x86 processors without mfence are rare
18050     // enough that we do not bother.
18051     return nullptr;
18052
18053   Function *MFence =
18054       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
18055   Builder.CreateCall(MFence, {});
18056
18057   // Finally we can emit the atomic load.
18058   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
18059           AI->getType()->getPrimitiveSizeInBits());
18060   Loaded->setAtomic(Order, SynchScope);
18061   AI->replaceAllUsesWith(Loaded);
18062   AI->eraseFromParent();
18063   return Loaded;
18064 }
18065
18066 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
18067                                  SelectionDAG &DAG) {
18068   SDLoc dl(Op);
18069   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
18070     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
18071   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
18072     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
18073
18074   // The only fence that needs an instruction is a sequentially-consistent
18075   // cross-thread fence.
18076   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
18077     if (hasMFENCE(*Subtarget))
18078       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
18079
18080     SDValue Chain = Op.getOperand(0);
18081     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
18082     SDValue Ops[] = {
18083       DAG.getRegister(X86::ESP, MVT::i32),     // Base
18084       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
18085       DAG.getRegister(0, MVT::i32),            // Index
18086       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
18087       DAG.getRegister(0, MVT::i32),            // Segment.
18088       Zero,
18089       Chain
18090     };
18091     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18092     return SDValue(Res, 0);
18093   }
18094
18095   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18096   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18097 }
18098
18099 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18100                              SelectionDAG &DAG) {
18101   MVT T = Op.getSimpleValueType();
18102   SDLoc DL(Op);
18103   unsigned Reg = 0;
18104   unsigned size = 0;
18105   switch(T.SimpleTy) {
18106   default: llvm_unreachable("Invalid value type!");
18107   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18108   case MVT::i16: Reg = X86::AX;  size = 2; break;
18109   case MVT::i32: Reg = X86::EAX; size = 4; break;
18110   case MVT::i64:
18111     assert(Subtarget->is64Bit() && "Node not type legal!");
18112     Reg = X86::RAX; size = 8;
18113     break;
18114   }
18115   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18116                                   Op.getOperand(2), SDValue());
18117   SDValue Ops[] = { cpIn.getValue(0),
18118                     Op.getOperand(1),
18119                     Op.getOperand(3),
18120                     DAG.getTargetConstant(size, DL, MVT::i8),
18121                     cpIn.getValue(1) };
18122   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18123   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18124   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18125                                            Ops, T, MMO);
18126
18127   SDValue cpOut =
18128     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18129   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18130                                       MVT::i32, cpOut.getValue(2));
18131   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18132                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18133                                 EFLAGS);
18134
18135   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18136   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18137   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18138   return SDValue();
18139 }
18140
18141 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18142                             SelectionDAG &DAG) {
18143   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18144   MVT DstVT = Op.getSimpleValueType();
18145
18146   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18147     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18148     if (DstVT != MVT::f64)
18149       // This conversion needs to be expanded.
18150       return SDValue();
18151
18152     SDValue InVec = Op->getOperand(0);
18153     SDLoc dl(Op);
18154     unsigned NumElts = SrcVT.getVectorNumElements();
18155     EVT SVT = SrcVT.getVectorElementType();
18156
18157     // Widen the vector in input in the case of MVT::v2i32.
18158     // Example: from MVT::v2i32 to MVT::v4i32.
18159     SmallVector<SDValue, 16> Elts;
18160     for (unsigned i = 0, e = NumElts; i != e; ++i)
18161       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18162                                  DAG.getIntPtrConstant(i, dl)));
18163
18164     // Explicitly mark the extra elements as Undef.
18165     Elts.append(NumElts, DAG.getUNDEF(SVT));
18166
18167     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18168     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18169     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18170     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18171                        DAG.getIntPtrConstant(0, dl));
18172   }
18173
18174   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18175          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18176   assert((DstVT == MVT::i64 ||
18177           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18178          "Unexpected custom BITCAST");
18179   // i64 <=> MMX conversions are Legal.
18180   if (SrcVT==MVT::i64 && DstVT.isVector())
18181     return Op;
18182   if (DstVT==MVT::i64 && SrcVT.isVector())
18183     return Op;
18184   // MMX <=> MMX conversions are Legal.
18185   if (SrcVT.isVector() && DstVT.isVector())
18186     return Op;
18187   // All other conversions need to be expanded.
18188   return SDValue();
18189 }
18190
18191 /// Compute the horizontal sum of bytes in V for the elements of VT.
18192 ///
18193 /// Requires V to be a byte vector and VT to be an integer vector type with
18194 /// wider elements than V's type. The width of the elements of VT determines
18195 /// how many bytes of V are summed horizontally to produce each element of the
18196 /// result.
18197 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18198                                       const X86Subtarget *Subtarget,
18199                                       SelectionDAG &DAG) {
18200   SDLoc DL(V);
18201   MVT ByteVecVT = V.getSimpleValueType();
18202   MVT EltVT = VT.getVectorElementType();
18203   int NumElts = VT.getVectorNumElements();
18204   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18205          "Expected value to have byte element type.");
18206   assert(EltVT != MVT::i8 &&
18207          "Horizontal byte sum only makes sense for wider elements!");
18208   unsigned VecSize = VT.getSizeInBits();
18209   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18210
18211   // PSADBW instruction horizontally add all bytes and leave the result in i64
18212   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18213   if (EltVT == MVT::i64) {
18214     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18215     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18216     return DAG.getBitcast(VT, V);
18217   }
18218
18219   if (EltVT == MVT::i32) {
18220     // We unpack the low half and high half into i32s interleaved with zeros so
18221     // that we can use PSADBW to horizontally sum them. The most useful part of
18222     // this is that it lines up the results of two PSADBW instructions to be
18223     // two v2i64 vectors which concatenated are the 4 population counts. We can
18224     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18225     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18226     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18227     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18228
18229     // Do the horizontal sums into two v2i64s.
18230     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18231     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18232                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18233     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18234                        DAG.getBitcast(ByteVecVT, High), Zeros);
18235
18236     // Merge them together.
18237     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18238     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18239                     DAG.getBitcast(ShortVecVT, Low),
18240                     DAG.getBitcast(ShortVecVT, High));
18241
18242     return DAG.getBitcast(VT, V);
18243   }
18244
18245   // The only element type left is i16.
18246   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18247
18248   // To obtain pop count for each i16 element starting from the pop count for
18249   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18250   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18251   // directly supported.
18252   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18253   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18254   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18255   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18256                   DAG.getBitcast(ByteVecVT, V));
18257   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18258 }
18259
18260 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18261                                         const X86Subtarget *Subtarget,
18262                                         SelectionDAG &DAG) {
18263   MVT VT = Op.getSimpleValueType();
18264   MVT EltVT = VT.getVectorElementType();
18265   unsigned VecSize = VT.getSizeInBits();
18266
18267   // Implement a lookup table in register by using an algorithm based on:
18268   // http://wm.ite.pl/articles/sse-popcount.html
18269   //
18270   // The general idea is that every lower byte nibble in the input vector is an
18271   // index into a in-register pre-computed pop count table. We then split up the
18272   // input vector in two new ones: (1) a vector with only the shifted-right
18273   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18274   // masked out higher ones) for each byte. PSHUB is used separately with both
18275   // to index the in-register table. Next, both are added and the result is a
18276   // i8 vector where each element contains the pop count for input byte.
18277   //
18278   // To obtain the pop count for elements != i8, we follow up with the same
18279   // approach and use additional tricks as described below.
18280   //
18281   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18282                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18283                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18284                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18285
18286   int NumByteElts = VecSize / 8;
18287   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18288   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18289   SmallVector<SDValue, 16> LUTVec;
18290   for (int i = 0; i < NumByteElts; ++i)
18291     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18292   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18293   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18294                                   DAG.getConstant(0x0F, DL, MVT::i8));
18295   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18296
18297   // High nibbles
18298   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18299   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18300   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18301
18302   // Low nibbles
18303   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18304
18305   // The input vector is used as the shuffle mask that index elements into the
18306   // LUT. After counting low and high nibbles, add the vector to obtain the
18307   // final pop count per i8 element.
18308   SDValue HighPopCnt =
18309       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18310   SDValue LowPopCnt =
18311       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18312   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18313
18314   if (EltVT == MVT::i8)
18315     return PopCnt;
18316
18317   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18318 }
18319
18320 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18321                                        const X86Subtarget *Subtarget,
18322                                        SelectionDAG &DAG) {
18323   MVT VT = Op.getSimpleValueType();
18324   assert(VT.is128BitVector() &&
18325          "Only 128-bit vector bitmath lowering supported.");
18326
18327   int VecSize = VT.getSizeInBits();
18328   MVT EltVT = VT.getVectorElementType();
18329   int Len = EltVT.getSizeInBits();
18330
18331   // This is the vectorized version of the "best" algorithm from
18332   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18333   // with a minor tweak to use a series of adds + shifts instead of vector
18334   // multiplications. Implemented for all integer vector types. We only use
18335   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18336   // much faster, even faster than using native popcnt instructions.
18337
18338   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18339     MVT VT = V.getSimpleValueType();
18340     SmallVector<SDValue, 32> Shifters(
18341         VT.getVectorNumElements(),
18342         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18343     return DAG.getNode(OpCode, DL, VT, V,
18344                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18345   };
18346   auto GetMask = [&](SDValue V, APInt Mask) {
18347     MVT VT = V.getSimpleValueType();
18348     SmallVector<SDValue, 32> Masks(
18349         VT.getVectorNumElements(),
18350         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18351     return DAG.getNode(ISD::AND, DL, VT, V,
18352                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18353   };
18354
18355   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18356   // x86, so set the SRL type to have elements at least i16 wide. This is
18357   // correct because all of our SRLs are followed immediately by a mask anyways
18358   // that handles any bits that sneak into the high bits of the byte elements.
18359   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18360
18361   SDValue V = Op;
18362
18363   // v = v - ((v >> 1) & 0x55555555...)
18364   SDValue Srl =
18365       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18366   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18367   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18368
18369   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18370   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18371   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18372   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18373   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18374
18375   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18376   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18377   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18378   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18379
18380   // At this point, V contains the byte-wise population count, and we are
18381   // merely doing a horizontal sum if necessary to get the wider element
18382   // counts.
18383   if (EltVT == MVT::i8)
18384     return V;
18385
18386   return LowerHorizontalByteSum(
18387       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18388       DAG);
18389 }
18390
18391 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18392                                 SelectionDAG &DAG) {
18393   MVT VT = Op.getSimpleValueType();
18394   // FIXME: Need to add AVX-512 support here!
18395   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18396          "Unknown CTPOP type to handle");
18397   SDLoc DL(Op.getNode());
18398   SDValue Op0 = Op.getOperand(0);
18399
18400   if (!Subtarget->hasSSSE3()) {
18401     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18402     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18403     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18404   }
18405
18406   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18407     unsigned NumElems = VT.getVectorNumElements();
18408
18409     // Extract each 128-bit vector, compute pop count and concat the result.
18410     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18411     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18412
18413     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18414                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18415                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18416   }
18417
18418   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18419 }
18420
18421 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18422                           SelectionDAG &DAG) {
18423   assert(Op.getValueType().isVector() &&
18424          "We only do custom lowering for vector population count.");
18425   return LowerVectorCTPOP(Op, Subtarget, DAG);
18426 }
18427
18428 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18429   SDNode *Node = Op.getNode();
18430   SDLoc dl(Node);
18431   EVT T = Node->getValueType(0);
18432   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18433                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18434   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18435                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18436                        Node->getOperand(0),
18437                        Node->getOperand(1), negOp,
18438                        cast<AtomicSDNode>(Node)->getMemOperand(),
18439                        cast<AtomicSDNode>(Node)->getOrdering(),
18440                        cast<AtomicSDNode>(Node)->getSynchScope());
18441 }
18442
18443 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18444   SDNode *Node = Op.getNode();
18445   SDLoc dl(Node);
18446   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18447
18448   // Convert seq_cst store -> xchg
18449   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18450   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18451   //        (The only way to get a 16-byte store is cmpxchg16b)
18452   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18453   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18454       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18455     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18456                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18457                                  Node->getOperand(0),
18458                                  Node->getOperand(1), Node->getOperand(2),
18459                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18460                                  cast<AtomicSDNode>(Node)->getOrdering(),
18461                                  cast<AtomicSDNode>(Node)->getSynchScope());
18462     return Swap.getValue(1);
18463   }
18464   // Other atomic stores have a simple pattern.
18465   return Op;
18466 }
18467
18468 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18469   EVT VT = Op.getNode()->getSimpleValueType(0);
18470
18471   // Let legalize expand this if it isn't a legal type yet.
18472   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18473     return SDValue();
18474
18475   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18476
18477   unsigned Opc;
18478   bool ExtraOp = false;
18479   switch (Op.getOpcode()) {
18480   default: llvm_unreachable("Invalid code");
18481   case ISD::ADDC: Opc = X86ISD::ADD; break;
18482   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18483   case ISD::SUBC: Opc = X86ISD::SUB; break;
18484   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18485   }
18486
18487   if (!ExtraOp)
18488     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18489                        Op.getOperand(1));
18490   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18491                      Op.getOperand(1), Op.getOperand(2));
18492 }
18493
18494 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18495                             SelectionDAG &DAG) {
18496   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18497
18498   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18499   // which returns the values as { float, float } (in XMM0) or
18500   // { double, double } (which is returned in XMM0, XMM1).
18501   SDLoc dl(Op);
18502   SDValue Arg = Op.getOperand(0);
18503   EVT ArgVT = Arg.getValueType();
18504   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18505
18506   TargetLowering::ArgListTy Args;
18507   TargetLowering::ArgListEntry Entry;
18508
18509   Entry.Node = Arg;
18510   Entry.Ty = ArgTy;
18511   Entry.isSExt = false;
18512   Entry.isZExt = false;
18513   Args.push_back(Entry);
18514
18515   bool isF64 = ArgVT == MVT::f64;
18516   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18517   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18518   // the results are returned via SRet in memory.
18519   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18520   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18521   SDValue Callee =
18522       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18523
18524   Type *RetTy = isF64
18525     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18526     : (Type*)VectorType::get(ArgTy, 4);
18527
18528   TargetLowering::CallLoweringInfo CLI(DAG);
18529   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18530     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18531
18532   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18533
18534   if (isF64)
18535     // Returned in xmm0 and xmm1.
18536     return CallResult.first;
18537
18538   // Returned in bits 0:31 and 32:64 xmm0.
18539   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18540                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18541   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18542                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18543   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18544   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18545 }
18546
18547 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18548                              SelectionDAG &DAG) {
18549   assert(Subtarget->hasAVX512() &&
18550          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18551
18552   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18553   EVT VT = N->getValue().getValueType();
18554   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18555   SDLoc dl(Op);
18556
18557   // X86 scatter kills mask register, so its type should be added to
18558   // the list of return values
18559   if (N->getNumValues() == 1) {
18560     SDValue Index = N->getIndex();
18561     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18562         !Index.getValueType().is512BitVector())
18563       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18564
18565     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18566     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18567                       N->getOperand(3), Index };
18568
18569     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18570     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18571     return SDValue(NewScatter.getNode(), 0);
18572   }
18573   return Op;
18574 }
18575
18576 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18577                             SelectionDAG &DAG) {
18578   assert(Subtarget->hasAVX512() &&
18579          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18580
18581   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18582   EVT VT = Op.getValueType();
18583   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18584   SDLoc dl(Op);
18585
18586   SDValue Index = N->getIndex();
18587   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18588       !Index.getValueType().is512BitVector()) {
18589     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18590     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18591                       N->getOperand(3), Index };
18592     DAG.UpdateNodeOperands(N, Ops);
18593   }
18594   return Op;
18595 }
18596
18597 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18598                                                     SelectionDAG &DAG) const {
18599   // TODO: Eventually, the lowering of these nodes should be informed by or
18600   // deferred to the GC strategy for the function in which they appear. For
18601   // now, however, they must be lowered to something. Since they are logically
18602   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18603   // require special handling for these nodes), lower them as literal NOOPs for
18604   // the time being.
18605   SmallVector<SDValue, 2> Ops;
18606
18607   Ops.push_back(Op.getOperand(0));
18608   if (Op->getGluedNode())
18609     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18610
18611   SDLoc OpDL(Op);
18612   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18613   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18614
18615   return NOOP;
18616 }
18617
18618 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18619                                                   SelectionDAG &DAG) const {
18620   // TODO: Eventually, the lowering of these nodes should be informed by or
18621   // deferred to the GC strategy for the function in which they appear. For
18622   // now, however, they must be lowered to something. Since they are logically
18623   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18624   // require special handling for these nodes), lower them as literal NOOPs for
18625   // the time being.
18626   SmallVector<SDValue, 2> Ops;
18627
18628   Ops.push_back(Op.getOperand(0));
18629   if (Op->getGluedNode())
18630     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18631
18632   SDLoc OpDL(Op);
18633   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18634   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18635
18636   return NOOP;
18637 }
18638
18639 /// LowerOperation - Provide custom lowering hooks for some operations.
18640 ///
18641 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18642   switch (Op.getOpcode()) {
18643   default: llvm_unreachable("Should not custom lower this!");
18644   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18645   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18646     return LowerCMP_SWAP(Op, Subtarget, DAG);
18647   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18648   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18649   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18650   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18651   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18652   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18653   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18654   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18655   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18656   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18657   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18658   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18659   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18660   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18661   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18662   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18663   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18664   case ISD::SHL_PARTS:
18665   case ISD::SRA_PARTS:
18666   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18667   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18668   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18669   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18670   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18671   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18672   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18673   case ISD::SIGN_EXTEND_VECTOR_INREG:
18674     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18675   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18676   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18677   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18678   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18679   case ISD::FABS:
18680   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18681   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18682   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18683   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18684   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18685   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18686   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18687   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18688   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18689   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18690   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18691   case ISD::INTRINSIC_VOID:
18692   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18693   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18694   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18695   case ISD::FRAME_TO_ARGS_OFFSET:
18696                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18697   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18698   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18699   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18700   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18701   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18702   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18703   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18704   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18705   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18706   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18707   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18708   case ISD::UMUL_LOHI:
18709   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18710   case ISD::SRA:
18711   case ISD::SRL:
18712   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18713   case ISD::SADDO:
18714   case ISD::UADDO:
18715   case ISD::SSUBO:
18716   case ISD::USUBO:
18717   case ISD::SMULO:
18718   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18719   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18720   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18721   case ISD::ADDC:
18722   case ISD::ADDE:
18723   case ISD::SUBC:
18724   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18725   case ISD::ADD:                return LowerADD(Op, DAG);
18726   case ISD::SUB:                return LowerSUB(Op, DAG);
18727   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18728   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18729   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18730   case ISD::GC_TRANSITION_START:
18731                                 return LowerGC_TRANSITION_START(Op, DAG);
18732   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18733   }
18734 }
18735
18736 /// ReplaceNodeResults - Replace a node with an illegal result type
18737 /// with a new node built out of custom code.
18738 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18739                                            SmallVectorImpl<SDValue>&Results,
18740                                            SelectionDAG &DAG) const {
18741   SDLoc dl(N);
18742   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18743   switch (N->getOpcode()) {
18744   default:
18745     llvm_unreachable("Do not know how to custom type legalize this operation!");
18746   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18747   case X86ISD::FMINC:
18748   case X86ISD::FMIN:
18749   case X86ISD::FMAXC:
18750   case X86ISD::FMAX: {
18751     EVT VT = N->getValueType(0);
18752     if (VT != MVT::v2f32)
18753       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18754     SDValue UNDEF = DAG.getUNDEF(VT);
18755     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18756                               N->getOperand(0), UNDEF);
18757     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18758                               N->getOperand(1), UNDEF);
18759     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18760     return;
18761   }
18762   case ISD::SIGN_EXTEND_INREG:
18763   case ISD::ADDC:
18764   case ISD::ADDE:
18765   case ISD::SUBC:
18766   case ISD::SUBE:
18767     // We don't want to expand or promote these.
18768     return;
18769   case ISD::SDIV:
18770   case ISD::UDIV:
18771   case ISD::SREM:
18772   case ISD::UREM:
18773   case ISD::SDIVREM:
18774   case ISD::UDIVREM: {
18775     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18776     Results.push_back(V);
18777     return;
18778   }
18779   case ISD::FP_TO_SINT:
18780     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18781     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18782     if (N->getOperand(0).getValueType() == MVT::f16)
18783       break;
18784     // fallthrough
18785   case ISD::FP_TO_UINT: {
18786     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18787
18788     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18789       return;
18790
18791     std::pair<SDValue,SDValue> Vals =
18792         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18793     SDValue FIST = Vals.first, StackSlot = Vals.second;
18794     if (FIST.getNode()) {
18795       EVT VT = N->getValueType(0);
18796       // Return a load from the stack slot.
18797       if (StackSlot.getNode())
18798         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18799                                       MachinePointerInfo(),
18800                                       false, false, false, 0));
18801       else
18802         Results.push_back(FIST);
18803     }
18804     return;
18805   }
18806   case ISD::UINT_TO_FP: {
18807     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18808     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18809         N->getValueType(0) != MVT::v2f32)
18810       return;
18811     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18812                                  N->getOperand(0));
18813     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18814                                      MVT::f64);
18815     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18816     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18817                              DAG.getBitcast(MVT::v2i64, VBias));
18818     Or = DAG.getBitcast(MVT::v2f64, Or);
18819     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18820     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18821     return;
18822   }
18823   case ISD::FP_ROUND: {
18824     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18825         return;
18826     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18827     Results.push_back(V);
18828     return;
18829   }
18830   case ISD::FP_EXTEND: {
18831     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18832     // No other ValueType for FP_EXTEND should reach this point.
18833     assert(N->getValueType(0) == MVT::v2f32 &&
18834            "Do not know how to legalize this Node");
18835     return;
18836   }
18837   case ISD::INTRINSIC_W_CHAIN: {
18838     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18839     switch (IntNo) {
18840     default : llvm_unreachable("Do not know how to custom type "
18841                                "legalize this intrinsic operation!");
18842     case Intrinsic::x86_rdtsc:
18843       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18844                                      Results);
18845     case Intrinsic::x86_rdtscp:
18846       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18847                                      Results);
18848     case Intrinsic::x86_rdpmc:
18849       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18850     }
18851   }
18852   case ISD::READCYCLECOUNTER: {
18853     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18854                                    Results);
18855   }
18856   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18857     EVT T = N->getValueType(0);
18858     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18859     bool Regs64bit = T == MVT::i128;
18860     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18861     SDValue cpInL, cpInH;
18862     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18863                         DAG.getConstant(0, dl, HalfT));
18864     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18865                         DAG.getConstant(1, dl, HalfT));
18866     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18867                              Regs64bit ? X86::RAX : X86::EAX,
18868                              cpInL, SDValue());
18869     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18870                              Regs64bit ? X86::RDX : X86::EDX,
18871                              cpInH, cpInL.getValue(1));
18872     SDValue swapInL, swapInH;
18873     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18874                           DAG.getConstant(0, dl, HalfT));
18875     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18876                           DAG.getConstant(1, dl, HalfT));
18877     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18878                                Regs64bit ? X86::RBX : X86::EBX,
18879                                swapInL, cpInH.getValue(1));
18880     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18881                                Regs64bit ? X86::RCX : X86::ECX,
18882                                swapInH, swapInL.getValue(1));
18883     SDValue Ops[] = { swapInH.getValue(0),
18884                       N->getOperand(1),
18885                       swapInH.getValue(1) };
18886     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18887     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18888     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18889                                   X86ISD::LCMPXCHG8_DAG;
18890     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18891     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18892                                         Regs64bit ? X86::RAX : X86::EAX,
18893                                         HalfT, Result.getValue(1));
18894     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18895                                         Regs64bit ? X86::RDX : X86::EDX,
18896                                         HalfT, cpOutL.getValue(2));
18897     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18898
18899     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18900                                         MVT::i32, cpOutH.getValue(2));
18901     SDValue Success =
18902         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18903                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18904     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18905
18906     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18907     Results.push_back(Success);
18908     Results.push_back(EFLAGS.getValue(1));
18909     return;
18910   }
18911   case ISD::ATOMIC_SWAP:
18912   case ISD::ATOMIC_LOAD_ADD:
18913   case ISD::ATOMIC_LOAD_SUB:
18914   case ISD::ATOMIC_LOAD_AND:
18915   case ISD::ATOMIC_LOAD_OR:
18916   case ISD::ATOMIC_LOAD_XOR:
18917   case ISD::ATOMIC_LOAD_NAND:
18918   case ISD::ATOMIC_LOAD_MIN:
18919   case ISD::ATOMIC_LOAD_MAX:
18920   case ISD::ATOMIC_LOAD_UMIN:
18921   case ISD::ATOMIC_LOAD_UMAX:
18922   case ISD::ATOMIC_LOAD: {
18923     // Delegate to generic TypeLegalization. Situations we can really handle
18924     // should have already been dealt with by AtomicExpandPass.cpp.
18925     break;
18926   }
18927   case ISD::BITCAST: {
18928     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18929     EVT DstVT = N->getValueType(0);
18930     EVT SrcVT = N->getOperand(0)->getValueType(0);
18931
18932     if (SrcVT != MVT::f64 ||
18933         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18934       return;
18935
18936     unsigned NumElts = DstVT.getVectorNumElements();
18937     EVT SVT = DstVT.getVectorElementType();
18938     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18939     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18940                                    MVT::v2f64, N->getOperand(0));
18941     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18942
18943     if (ExperimentalVectorWideningLegalization) {
18944       // If we are legalizing vectors by widening, we already have the desired
18945       // legal vector type, just return it.
18946       Results.push_back(ToVecInt);
18947       return;
18948     }
18949
18950     SmallVector<SDValue, 8> Elts;
18951     for (unsigned i = 0, e = NumElts; i != e; ++i)
18952       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18953                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18954
18955     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18956   }
18957   }
18958 }
18959
18960 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18961   switch ((X86ISD::NodeType)Opcode) {
18962   case X86ISD::FIRST_NUMBER:       break;
18963   case X86ISD::BSF:                return "X86ISD::BSF";
18964   case X86ISD::BSR:                return "X86ISD::BSR";
18965   case X86ISD::SHLD:               return "X86ISD::SHLD";
18966   case X86ISD::SHRD:               return "X86ISD::SHRD";
18967   case X86ISD::FAND:               return "X86ISD::FAND";
18968   case X86ISD::FANDN:              return "X86ISD::FANDN";
18969   case X86ISD::FOR:                return "X86ISD::FOR";
18970   case X86ISD::FXOR:               return "X86ISD::FXOR";
18971   case X86ISD::FILD:               return "X86ISD::FILD";
18972   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18973   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18974   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18975   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18976   case X86ISD::FLD:                return "X86ISD::FLD";
18977   case X86ISD::FST:                return "X86ISD::FST";
18978   case X86ISD::CALL:               return "X86ISD::CALL";
18979   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18980   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18981   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18982   case X86ISD::BT:                 return "X86ISD::BT";
18983   case X86ISD::CMP:                return "X86ISD::CMP";
18984   case X86ISD::COMI:               return "X86ISD::COMI";
18985   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18986   case X86ISD::CMPM:               return "X86ISD::CMPM";
18987   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18988   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18989   case X86ISD::SETCC:              return "X86ISD::SETCC";
18990   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18991   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18992   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18993   case X86ISD::CMOV:               return "X86ISD::CMOV";
18994   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18995   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18996   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18997   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18998   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18999   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
19000   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
19001   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
19002   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
19003   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
19004   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
19005   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
19006   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
19007   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
19008   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
19009   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
19010   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
19011   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
19012   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
19013   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
19014   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
19015   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
19016   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
19017   case X86ISD::HADD:               return "X86ISD::HADD";
19018   case X86ISD::HSUB:               return "X86ISD::HSUB";
19019   case X86ISD::FHADD:              return "X86ISD::FHADD";
19020   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
19021   case X86ISD::ABS:                return "X86ISD::ABS";
19022   case X86ISD::FMAX:               return "X86ISD::FMAX";
19023   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
19024   case X86ISD::FMIN:               return "X86ISD::FMIN";
19025   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
19026   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
19027   case X86ISD::FMINC:              return "X86ISD::FMINC";
19028   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
19029   case X86ISD::FRCP:               return "X86ISD::FRCP";
19030   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
19031   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
19032   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
19033   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
19034   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
19035   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
19036   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
19037   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
19038   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
19039   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
19040   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
19041   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
19042   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
19043   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
19044   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
19045   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
19046   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
19047   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
19048   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
19049   case X86ISD::VTRUNCS:            return "X86ISD::VTRUNCS";
19050   case X86ISD::VTRUNCUS:           return "X86ISD::VTRUNCUS";
19051   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
19052   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
19053   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
19054   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
19055   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
19056   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
19057   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
19058   case X86ISD::VSHL:               return "X86ISD::VSHL";
19059   case X86ISD::VSRL:               return "X86ISD::VSRL";
19060   case X86ISD::VSRA:               return "X86ISD::VSRA";
19061   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
19062   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
19063   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
19064   case X86ISD::CMPP:               return "X86ISD::CMPP";
19065   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
19066   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
19067   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
19068   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
19069   case X86ISD::ADD:                return "X86ISD::ADD";
19070   case X86ISD::SUB:                return "X86ISD::SUB";
19071   case X86ISD::ADC:                return "X86ISD::ADC";
19072   case X86ISD::SBB:                return "X86ISD::SBB";
19073   case X86ISD::SMUL:               return "X86ISD::SMUL";
19074   case X86ISD::UMUL:               return "X86ISD::UMUL";
19075   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
19076   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
19077   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
19078   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
19079   case X86ISD::INC:                return "X86ISD::INC";
19080   case X86ISD::DEC:                return "X86ISD::DEC";
19081   case X86ISD::OR:                 return "X86ISD::OR";
19082   case X86ISD::XOR:                return "X86ISD::XOR";
19083   case X86ISD::AND:                return "X86ISD::AND";
19084   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
19085   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
19086   case X86ISD::PTEST:              return "X86ISD::PTEST";
19087   case X86ISD::TESTP:              return "X86ISD::TESTP";
19088   case X86ISD::TESTM:              return "X86ISD::TESTM";
19089   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
19090   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
19091   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
19092   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19093   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19094   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19095   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19096   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19097   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19098   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19099   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19100   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19101   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19102   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19103   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19104   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19105   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19106   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19107   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19108   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19109   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19110   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19111   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19112   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19113   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19114   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19115   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19116   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19117   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19118   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19119   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19120   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19121   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19122   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19123   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19124   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19125   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19126   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19127   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19128   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19129   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19130   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19131   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19132   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19133   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19134   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19135   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19136   case X86ISD::SAHF:               return "X86ISD::SAHF";
19137   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19138   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19139   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19140   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19141   case X86ISD::FMADD:              return "X86ISD::FMADD";
19142   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19143   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19144   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19145   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19146   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19147   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19148   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19149   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19150   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19151   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19152   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19153   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19154   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19155   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19156   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19157   case X86ISD::XTEST:              return "X86ISD::XTEST";
19158   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19159   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19160   case X86ISD::SELECT:             return "X86ISD::SELECT";
19161   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19162   case X86ISD::RCP28:              return "X86ISD::RCP28";
19163   case X86ISD::EXP2:               return "X86ISD::EXP2";
19164   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19165   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19166   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19167   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19168   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19169   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19170   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19171   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19172   case X86ISD::ADDS:               return "X86ISD::ADDS";
19173   case X86ISD::SUBS:               return "X86ISD::SUBS";
19174   case X86ISD::AVG:                return "X86ISD::AVG";
19175   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19176   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19177   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19178   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19179   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19180   }
19181   return nullptr;
19182 }
19183
19184 // isLegalAddressingMode - Return true if the addressing mode represented
19185 // by AM is legal for this target, for a load/store of the specified type.
19186 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19187                                               const AddrMode &AM, Type *Ty,
19188                                               unsigned AS) const {
19189   // X86 supports extremely general addressing modes.
19190   CodeModel::Model M = getTargetMachine().getCodeModel();
19191   Reloc::Model R = getTargetMachine().getRelocationModel();
19192
19193   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19194   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19195     return false;
19196
19197   if (AM.BaseGV) {
19198     unsigned GVFlags =
19199       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19200
19201     // If a reference to this global requires an extra load, we can't fold it.
19202     if (isGlobalStubReference(GVFlags))
19203       return false;
19204
19205     // If BaseGV requires a register for the PIC base, we cannot also have a
19206     // BaseReg specified.
19207     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19208       return false;
19209
19210     // If lower 4G is not available, then we must use rip-relative addressing.
19211     if ((M != CodeModel::Small || R != Reloc::Static) &&
19212         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19213       return false;
19214   }
19215
19216   switch (AM.Scale) {
19217   case 0:
19218   case 1:
19219   case 2:
19220   case 4:
19221   case 8:
19222     // These scales always work.
19223     break;
19224   case 3:
19225   case 5:
19226   case 9:
19227     // These scales are formed with basereg+scalereg.  Only accept if there is
19228     // no basereg yet.
19229     if (AM.HasBaseReg)
19230       return false;
19231     break;
19232   default:  // Other stuff never works.
19233     return false;
19234   }
19235
19236   return true;
19237 }
19238
19239 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19240   unsigned Bits = Ty->getScalarSizeInBits();
19241
19242   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19243   // particularly cheaper than those without.
19244   if (Bits == 8)
19245     return false;
19246
19247   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19248   // variable shifts just as cheap as scalar ones.
19249   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19250     return false;
19251
19252   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19253   // fully general vector.
19254   return true;
19255 }
19256
19257 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19258   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19259     return false;
19260   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19261   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19262   return NumBits1 > NumBits2;
19263 }
19264
19265 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19266   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19267     return false;
19268
19269   if (!isTypeLegal(EVT::getEVT(Ty1)))
19270     return false;
19271
19272   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19273
19274   // Assuming the caller doesn't have a zeroext or signext return parameter,
19275   // truncation all the way down to i1 is valid.
19276   return true;
19277 }
19278
19279 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19280   return isInt<32>(Imm);
19281 }
19282
19283 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19284   // Can also use sub to handle negated immediates.
19285   return isInt<32>(Imm);
19286 }
19287
19288 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19289   if (!VT1.isInteger() || !VT2.isInteger())
19290     return false;
19291   unsigned NumBits1 = VT1.getSizeInBits();
19292   unsigned NumBits2 = VT2.getSizeInBits();
19293   return NumBits1 > NumBits2;
19294 }
19295
19296 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19297   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19298   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19299 }
19300
19301 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19302   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19303   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19304 }
19305
19306 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19307   EVT VT1 = Val.getValueType();
19308   if (isZExtFree(VT1, VT2))
19309     return true;
19310
19311   if (Val.getOpcode() != ISD::LOAD)
19312     return false;
19313
19314   if (!VT1.isSimple() || !VT1.isInteger() ||
19315       !VT2.isSimple() || !VT2.isInteger())
19316     return false;
19317
19318   switch (VT1.getSimpleVT().SimpleTy) {
19319   default: break;
19320   case MVT::i8:
19321   case MVT::i16:
19322   case MVT::i32:
19323     // X86 has 8, 16, and 32-bit zero-extending loads.
19324     return true;
19325   }
19326
19327   return false;
19328 }
19329
19330 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19331
19332 bool
19333 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19334   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19335     return false;
19336
19337   VT = VT.getScalarType();
19338
19339   if (!VT.isSimple())
19340     return false;
19341
19342   switch (VT.getSimpleVT().SimpleTy) {
19343   case MVT::f32:
19344   case MVT::f64:
19345     return true;
19346   default:
19347     break;
19348   }
19349
19350   return false;
19351 }
19352
19353 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19354   // i16 instructions are longer (0x66 prefix) and potentially slower.
19355   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19356 }
19357
19358 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19359 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19360 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19361 /// are assumed to be legal.
19362 bool
19363 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19364                                       EVT VT) const {
19365   if (!VT.isSimple())
19366     return false;
19367
19368   // Not for i1 vectors
19369   if (VT.getScalarType() == MVT::i1)
19370     return false;
19371
19372   // Very little shuffling can be done for 64-bit vectors right now.
19373   if (VT.getSizeInBits() == 64)
19374     return false;
19375
19376   // We only care that the types being shuffled are legal. The lowering can
19377   // handle any possible shuffle mask that results.
19378   return isTypeLegal(VT.getSimpleVT());
19379 }
19380
19381 bool
19382 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19383                                           EVT VT) const {
19384   // Just delegate to the generic legality, clear masks aren't special.
19385   return isShuffleMaskLegal(Mask, VT);
19386 }
19387
19388 //===----------------------------------------------------------------------===//
19389 //                           X86 Scheduler Hooks
19390 //===----------------------------------------------------------------------===//
19391
19392 /// Utility function to emit xbegin specifying the start of an RTM region.
19393 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19394                                      const TargetInstrInfo *TII) {
19395   DebugLoc DL = MI->getDebugLoc();
19396
19397   const BasicBlock *BB = MBB->getBasicBlock();
19398   MachineFunction::iterator I = MBB;
19399   ++I;
19400
19401   // For the v = xbegin(), we generate
19402   //
19403   // thisMBB:
19404   //  xbegin sinkMBB
19405   //
19406   // mainMBB:
19407   //  eax = -1
19408   //
19409   // sinkMBB:
19410   //  v = eax
19411
19412   MachineBasicBlock *thisMBB = MBB;
19413   MachineFunction *MF = MBB->getParent();
19414   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19415   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19416   MF->insert(I, mainMBB);
19417   MF->insert(I, sinkMBB);
19418
19419   // Transfer the remainder of BB and its successor edges to sinkMBB.
19420   sinkMBB->splice(sinkMBB->begin(), MBB,
19421                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19422   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19423
19424   // thisMBB:
19425   //  xbegin sinkMBB
19426   //  # fallthrough to mainMBB
19427   //  # abortion to sinkMBB
19428   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19429   thisMBB->addSuccessor(mainMBB);
19430   thisMBB->addSuccessor(sinkMBB);
19431
19432   // mainMBB:
19433   //  EAX = -1
19434   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19435   mainMBB->addSuccessor(sinkMBB);
19436
19437   // sinkMBB:
19438   // EAX is live into the sinkMBB
19439   sinkMBB->addLiveIn(X86::EAX);
19440   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19441           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19442     .addReg(X86::EAX);
19443
19444   MI->eraseFromParent();
19445   return sinkMBB;
19446 }
19447
19448 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19449 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19450 // in the .td file.
19451 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19452                                        const TargetInstrInfo *TII) {
19453   unsigned Opc;
19454   switch (MI->getOpcode()) {
19455   default: llvm_unreachable("illegal opcode!");
19456   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19457   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19458   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19459   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19460   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19461   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19462   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19463   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19464   }
19465
19466   DebugLoc dl = MI->getDebugLoc();
19467   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19468
19469   unsigned NumArgs = MI->getNumOperands();
19470   for (unsigned i = 1; i < NumArgs; ++i) {
19471     MachineOperand &Op = MI->getOperand(i);
19472     if (!(Op.isReg() && Op.isImplicit()))
19473       MIB.addOperand(Op);
19474   }
19475   if (MI->hasOneMemOperand())
19476     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19477
19478   BuildMI(*BB, MI, dl,
19479     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19480     .addReg(X86::XMM0);
19481
19482   MI->eraseFromParent();
19483   return BB;
19484 }
19485
19486 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19487 // defs in an instruction pattern
19488 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19489                                        const TargetInstrInfo *TII) {
19490   unsigned Opc;
19491   switch (MI->getOpcode()) {
19492   default: llvm_unreachable("illegal opcode!");
19493   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19494   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19495   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19496   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19497   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19498   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19499   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19500   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19501   }
19502
19503   DebugLoc dl = MI->getDebugLoc();
19504   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19505
19506   unsigned NumArgs = MI->getNumOperands(); // remove the results
19507   for (unsigned i = 1; i < NumArgs; ++i) {
19508     MachineOperand &Op = MI->getOperand(i);
19509     if (!(Op.isReg() && Op.isImplicit()))
19510       MIB.addOperand(Op);
19511   }
19512   if (MI->hasOneMemOperand())
19513     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19514
19515   BuildMI(*BB, MI, dl,
19516     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19517     .addReg(X86::ECX);
19518
19519   MI->eraseFromParent();
19520   return BB;
19521 }
19522
19523 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19524                                       const X86Subtarget *Subtarget) {
19525   DebugLoc dl = MI->getDebugLoc();
19526   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19527   // Address into RAX/EAX, other two args into ECX, EDX.
19528   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19529   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19530   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19531   for (int i = 0; i < X86::AddrNumOperands; ++i)
19532     MIB.addOperand(MI->getOperand(i));
19533
19534   unsigned ValOps = X86::AddrNumOperands;
19535   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19536     .addReg(MI->getOperand(ValOps).getReg());
19537   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19538     .addReg(MI->getOperand(ValOps+1).getReg());
19539
19540   // The instruction doesn't actually take any operands though.
19541   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19542
19543   MI->eraseFromParent(); // The pseudo is gone now.
19544   return BB;
19545 }
19546
19547 MachineBasicBlock *
19548 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19549                                                  MachineBasicBlock *MBB) const {
19550   // Emit va_arg instruction on X86-64.
19551
19552   // Operands to this pseudo-instruction:
19553   // 0  ) Output        : destination address (reg)
19554   // 1-5) Input         : va_list address (addr, i64mem)
19555   // 6  ) ArgSize       : Size (in bytes) of vararg type
19556   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19557   // 8  ) Align         : Alignment of type
19558   // 9  ) EFLAGS (implicit-def)
19559
19560   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19561   static_assert(X86::AddrNumOperands == 5,
19562                 "VAARG_64 assumes 5 address operands");
19563
19564   unsigned DestReg = MI->getOperand(0).getReg();
19565   MachineOperand &Base = MI->getOperand(1);
19566   MachineOperand &Scale = MI->getOperand(2);
19567   MachineOperand &Index = MI->getOperand(3);
19568   MachineOperand &Disp = MI->getOperand(4);
19569   MachineOperand &Segment = MI->getOperand(5);
19570   unsigned ArgSize = MI->getOperand(6).getImm();
19571   unsigned ArgMode = MI->getOperand(7).getImm();
19572   unsigned Align = MI->getOperand(8).getImm();
19573
19574   // Memory Reference
19575   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19576   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19577   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19578
19579   // Machine Information
19580   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19581   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19582   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19583   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19584   DebugLoc DL = MI->getDebugLoc();
19585
19586   // struct va_list {
19587   //   i32   gp_offset
19588   //   i32   fp_offset
19589   //   i64   overflow_area (address)
19590   //   i64   reg_save_area (address)
19591   // }
19592   // sizeof(va_list) = 24
19593   // alignment(va_list) = 8
19594
19595   unsigned TotalNumIntRegs = 6;
19596   unsigned TotalNumXMMRegs = 8;
19597   bool UseGPOffset = (ArgMode == 1);
19598   bool UseFPOffset = (ArgMode == 2);
19599   unsigned MaxOffset = TotalNumIntRegs * 8 +
19600                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19601
19602   /* Align ArgSize to a multiple of 8 */
19603   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19604   bool NeedsAlign = (Align > 8);
19605
19606   MachineBasicBlock *thisMBB = MBB;
19607   MachineBasicBlock *overflowMBB;
19608   MachineBasicBlock *offsetMBB;
19609   MachineBasicBlock *endMBB;
19610
19611   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19612   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19613   unsigned OffsetReg = 0;
19614
19615   if (!UseGPOffset && !UseFPOffset) {
19616     // If we only pull from the overflow region, we don't create a branch.
19617     // We don't need to alter control flow.
19618     OffsetDestReg = 0; // unused
19619     OverflowDestReg = DestReg;
19620
19621     offsetMBB = nullptr;
19622     overflowMBB = thisMBB;
19623     endMBB = thisMBB;
19624   } else {
19625     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19626     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19627     // If not, pull from overflow_area. (branch to overflowMBB)
19628     //
19629     //       thisMBB
19630     //         |     .
19631     //         |        .
19632     //     offsetMBB   overflowMBB
19633     //         |        .
19634     //         |     .
19635     //        endMBB
19636
19637     // Registers for the PHI in endMBB
19638     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19639     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19640
19641     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19642     MachineFunction *MF = MBB->getParent();
19643     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19644     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19645     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19646
19647     MachineFunction::iterator MBBIter = MBB;
19648     ++MBBIter;
19649
19650     // Insert the new basic blocks
19651     MF->insert(MBBIter, offsetMBB);
19652     MF->insert(MBBIter, overflowMBB);
19653     MF->insert(MBBIter, endMBB);
19654
19655     // Transfer the remainder of MBB and its successor edges to endMBB.
19656     endMBB->splice(endMBB->begin(), thisMBB,
19657                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19658     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19659
19660     // Make offsetMBB and overflowMBB successors of thisMBB
19661     thisMBB->addSuccessor(offsetMBB);
19662     thisMBB->addSuccessor(overflowMBB);
19663
19664     // endMBB is a successor of both offsetMBB and overflowMBB
19665     offsetMBB->addSuccessor(endMBB);
19666     overflowMBB->addSuccessor(endMBB);
19667
19668     // Load the offset value into a register
19669     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19670     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19671       .addOperand(Base)
19672       .addOperand(Scale)
19673       .addOperand(Index)
19674       .addDisp(Disp, UseFPOffset ? 4 : 0)
19675       .addOperand(Segment)
19676       .setMemRefs(MMOBegin, MMOEnd);
19677
19678     // Check if there is enough room left to pull this argument.
19679     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19680       .addReg(OffsetReg)
19681       .addImm(MaxOffset + 8 - ArgSizeA8);
19682
19683     // Branch to "overflowMBB" if offset >= max
19684     // Fall through to "offsetMBB" otherwise
19685     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19686       .addMBB(overflowMBB);
19687   }
19688
19689   // In offsetMBB, emit code to use the reg_save_area.
19690   if (offsetMBB) {
19691     assert(OffsetReg != 0);
19692
19693     // Read the reg_save_area address.
19694     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19695     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19696       .addOperand(Base)
19697       .addOperand(Scale)
19698       .addOperand(Index)
19699       .addDisp(Disp, 16)
19700       .addOperand(Segment)
19701       .setMemRefs(MMOBegin, MMOEnd);
19702
19703     // Zero-extend the offset
19704     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19705       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19706         .addImm(0)
19707         .addReg(OffsetReg)
19708         .addImm(X86::sub_32bit);
19709
19710     // Add the offset to the reg_save_area to get the final address.
19711     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19712       .addReg(OffsetReg64)
19713       .addReg(RegSaveReg);
19714
19715     // Compute the offset for the next argument
19716     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19717     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19718       .addReg(OffsetReg)
19719       .addImm(UseFPOffset ? 16 : 8);
19720
19721     // Store it back into the va_list.
19722     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19723       .addOperand(Base)
19724       .addOperand(Scale)
19725       .addOperand(Index)
19726       .addDisp(Disp, UseFPOffset ? 4 : 0)
19727       .addOperand(Segment)
19728       .addReg(NextOffsetReg)
19729       .setMemRefs(MMOBegin, MMOEnd);
19730
19731     // Jump to endMBB
19732     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19733       .addMBB(endMBB);
19734   }
19735
19736   //
19737   // Emit code to use overflow area
19738   //
19739
19740   // Load the overflow_area address into a register.
19741   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19742   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19743     .addOperand(Base)
19744     .addOperand(Scale)
19745     .addOperand(Index)
19746     .addDisp(Disp, 8)
19747     .addOperand(Segment)
19748     .setMemRefs(MMOBegin, MMOEnd);
19749
19750   // If we need to align it, do so. Otherwise, just copy the address
19751   // to OverflowDestReg.
19752   if (NeedsAlign) {
19753     // Align the overflow address
19754     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19755     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19756
19757     // aligned_addr = (addr + (align-1)) & ~(align-1)
19758     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19759       .addReg(OverflowAddrReg)
19760       .addImm(Align-1);
19761
19762     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19763       .addReg(TmpReg)
19764       .addImm(~(uint64_t)(Align-1));
19765   } else {
19766     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19767       .addReg(OverflowAddrReg);
19768   }
19769
19770   // Compute the next overflow address after this argument.
19771   // (the overflow address should be kept 8-byte aligned)
19772   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19773   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19774     .addReg(OverflowDestReg)
19775     .addImm(ArgSizeA8);
19776
19777   // Store the new overflow address.
19778   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19779     .addOperand(Base)
19780     .addOperand(Scale)
19781     .addOperand(Index)
19782     .addDisp(Disp, 8)
19783     .addOperand(Segment)
19784     .addReg(NextAddrReg)
19785     .setMemRefs(MMOBegin, MMOEnd);
19786
19787   // If we branched, emit the PHI to the front of endMBB.
19788   if (offsetMBB) {
19789     BuildMI(*endMBB, endMBB->begin(), DL,
19790             TII->get(X86::PHI), DestReg)
19791       .addReg(OffsetDestReg).addMBB(offsetMBB)
19792       .addReg(OverflowDestReg).addMBB(overflowMBB);
19793   }
19794
19795   // Erase the pseudo instruction
19796   MI->eraseFromParent();
19797
19798   return endMBB;
19799 }
19800
19801 MachineBasicBlock *
19802 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19803                                                  MachineInstr *MI,
19804                                                  MachineBasicBlock *MBB) const {
19805   // Emit code to save XMM registers to the stack. The ABI says that the
19806   // number of registers to save is given in %al, so it's theoretically
19807   // possible to do an indirect jump trick to avoid saving all of them,
19808   // however this code takes a simpler approach and just executes all
19809   // of the stores if %al is non-zero. It's less code, and it's probably
19810   // easier on the hardware branch predictor, and stores aren't all that
19811   // expensive anyway.
19812
19813   // Create the new basic blocks. One block contains all the XMM stores,
19814   // and one block is the final destination regardless of whether any
19815   // stores were performed.
19816   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19817   MachineFunction *F = MBB->getParent();
19818   MachineFunction::iterator MBBIter = MBB;
19819   ++MBBIter;
19820   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19821   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19822   F->insert(MBBIter, XMMSaveMBB);
19823   F->insert(MBBIter, EndMBB);
19824
19825   // Transfer the remainder of MBB and its successor edges to EndMBB.
19826   EndMBB->splice(EndMBB->begin(), MBB,
19827                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19828   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19829
19830   // The original block will now fall through to the XMM save block.
19831   MBB->addSuccessor(XMMSaveMBB);
19832   // The XMMSaveMBB will fall through to the end block.
19833   XMMSaveMBB->addSuccessor(EndMBB);
19834
19835   // Now add the instructions.
19836   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19837   DebugLoc DL = MI->getDebugLoc();
19838
19839   unsigned CountReg = MI->getOperand(0).getReg();
19840   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19841   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19842
19843   if (!Subtarget->isTargetWin64()) {
19844     // If %al is 0, branch around the XMM save block.
19845     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19846     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19847     MBB->addSuccessor(EndMBB);
19848   }
19849
19850   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19851   // that was just emitted, but clearly shouldn't be "saved".
19852   assert((MI->getNumOperands() <= 3 ||
19853           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19854           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19855          && "Expected last argument to be EFLAGS");
19856   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19857   // In the XMM save block, save all the XMM argument registers.
19858   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19859     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19860     MachineMemOperand *MMO =
19861       F->getMachineMemOperand(
19862           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19863         MachineMemOperand::MOStore,
19864         /*Size=*/16, /*Align=*/16);
19865     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19866       .addFrameIndex(RegSaveFrameIndex)
19867       .addImm(/*Scale=*/1)
19868       .addReg(/*IndexReg=*/0)
19869       .addImm(/*Disp=*/Offset)
19870       .addReg(/*Segment=*/0)
19871       .addReg(MI->getOperand(i).getReg())
19872       .addMemOperand(MMO);
19873   }
19874
19875   MI->eraseFromParent();   // The pseudo instruction is gone now.
19876
19877   return EndMBB;
19878 }
19879
19880 // The EFLAGS operand of SelectItr might be missing a kill marker
19881 // because there were multiple uses of EFLAGS, and ISel didn't know
19882 // which to mark. Figure out whether SelectItr should have had a
19883 // kill marker, and set it if it should. Returns the correct kill
19884 // marker value.
19885 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19886                                      MachineBasicBlock* BB,
19887                                      const TargetRegisterInfo* TRI) {
19888   // Scan forward through BB for a use/def of EFLAGS.
19889   MachineBasicBlock::iterator miI(std::next(SelectItr));
19890   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19891     const MachineInstr& mi = *miI;
19892     if (mi.readsRegister(X86::EFLAGS))
19893       return false;
19894     if (mi.definesRegister(X86::EFLAGS))
19895       break; // Should have kill-flag - update below.
19896   }
19897
19898   // If we hit the end of the block, check whether EFLAGS is live into a
19899   // successor.
19900   if (miI == BB->end()) {
19901     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19902                                           sEnd = BB->succ_end();
19903          sItr != sEnd; ++sItr) {
19904       MachineBasicBlock* succ = *sItr;
19905       if (succ->isLiveIn(X86::EFLAGS))
19906         return false;
19907     }
19908   }
19909
19910   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19911   // out. SelectMI should have a kill flag on EFLAGS.
19912   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19913   return true;
19914 }
19915
19916 MachineBasicBlock *
19917 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19918                                      MachineBasicBlock *BB) const {
19919   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19920   DebugLoc DL = MI->getDebugLoc();
19921
19922   // To "insert" a SELECT_CC instruction, we actually have to insert the
19923   // diamond control-flow pattern.  The incoming instruction knows the
19924   // destination vreg to set, the condition code register to branch on, the
19925   // true/false values to select between, and a branch opcode to use.
19926   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19927   MachineFunction::iterator It = BB;
19928   ++It;
19929
19930   //  thisMBB:
19931   //  ...
19932   //   TrueVal = ...
19933   //   cmpTY ccX, r1, r2
19934   //   bCC copy1MBB
19935   //   fallthrough --> copy0MBB
19936   MachineBasicBlock *thisMBB = BB;
19937   MachineFunction *F = BB->getParent();
19938
19939   // We also lower double CMOVs:
19940   //   (CMOV (CMOV F, T, cc1), T, cc2)
19941   // to two successives branches.  For that, we look for another CMOV as the
19942   // following instruction.
19943   //
19944   // Without this, we would add a PHI between the two jumps, which ends up
19945   // creating a few copies all around. For instance, for
19946   //
19947   //    (sitofp (zext (fcmp une)))
19948   //
19949   // we would generate:
19950   //
19951   //         ucomiss %xmm1, %xmm0
19952   //         movss  <1.0f>, %xmm0
19953   //         movaps  %xmm0, %xmm1
19954   //         jne     .LBB5_2
19955   //         xorps   %xmm1, %xmm1
19956   // .LBB5_2:
19957   //         jp      .LBB5_4
19958   //         movaps  %xmm1, %xmm0
19959   // .LBB5_4:
19960   //         retq
19961   //
19962   // because this custom-inserter would have generated:
19963   //
19964   //   A
19965   //   | \
19966   //   |  B
19967   //   | /
19968   //   C
19969   //   | \
19970   //   |  D
19971   //   | /
19972   //   E
19973   //
19974   // A: X = ...; Y = ...
19975   // B: empty
19976   // C: Z = PHI [X, A], [Y, B]
19977   // D: empty
19978   // E: PHI [X, C], [Z, D]
19979   //
19980   // If we lower both CMOVs in a single step, we can instead generate:
19981   //
19982   //   A
19983   //   | \
19984   //   |  C
19985   //   | /|
19986   //   |/ |
19987   //   |  |
19988   //   |  D
19989   //   | /
19990   //   E
19991   //
19992   // A: X = ...; Y = ...
19993   // D: empty
19994   // E: PHI [X, A], [X, C], [Y, D]
19995   //
19996   // Which, in our sitofp/fcmp example, gives us something like:
19997   //
19998   //         ucomiss %xmm1, %xmm0
19999   //         movss  <1.0f>, %xmm0
20000   //         jne     .LBB5_4
20001   //         jp      .LBB5_4
20002   //         xorps   %xmm0, %xmm0
20003   // .LBB5_4:
20004   //         retq
20005   //
20006   MachineInstr *NextCMOV = nullptr;
20007   MachineBasicBlock::iterator NextMIIt =
20008       std::next(MachineBasicBlock::iterator(MI));
20009   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
20010       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
20011       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
20012     NextCMOV = &*NextMIIt;
20013
20014   MachineBasicBlock *jcc1MBB = nullptr;
20015
20016   // If we have a double CMOV, we lower it to two successive branches to
20017   // the same block.  EFLAGS is used by both, so mark it as live in the second.
20018   if (NextCMOV) {
20019     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
20020     F->insert(It, jcc1MBB);
20021     jcc1MBB->addLiveIn(X86::EFLAGS);
20022   }
20023
20024   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
20025   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
20026   F->insert(It, copy0MBB);
20027   F->insert(It, sinkMBB);
20028
20029   // If the EFLAGS register isn't dead in the terminator, then claim that it's
20030   // live into the sink and copy blocks.
20031   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
20032
20033   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
20034   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
20035       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
20036     copy0MBB->addLiveIn(X86::EFLAGS);
20037     sinkMBB->addLiveIn(X86::EFLAGS);
20038   }
20039
20040   // Transfer the remainder of BB and its successor edges to sinkMBB.
20041   sinkMBB->splice(sinkMBB->begin(), BB,
20042                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
20043   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
20044
20045   // Add the true and fallthrough blocks as its successors.
20046   if (NextCMOV) {
20047     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
20048     BB->addSuccessor(jcc1MBB);
20049
20050     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
20051     // jump to the sinkMBB.
20052     jcc1MBB->addSuccessor(copy0MBB);
20053     jcc1MBB->addSuccessor(sinkMBB);
20054   } else {
20055     BB->addSuccessor(copy0MBB);
20056   }
20057
20058   // The true block target of the first (or only) branch is always sinkMBB.
20059   BB->addSuccessor(sinkMBB);
20060
20061   // Create the conditional branch instruction.
20062   unsigned Opc =
20063     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
20064   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
20065
20066   if (NextCMOV) {
20067     unsigned Opc2 = X86::GetCondBranchFromCond(
20068         (X86::CondCode)NextCMOV->getOperand(3).getImm());
20069     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
20070   }
20071
20072   //  copy0MBB:
20073   //   %FalseValue = ...
20074   //   # fallthrough to sinkMBB
20075   copy0MBB->addSuccessor(sinkMBB);
20076
20077   //  sinkMBB:
20078   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
20079   //  ...
20080   MachineInstrBuilder MIB =
20081       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
20082               MI->getOperand(0).getReg())
20083           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
20084           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
20085
20086   // If we have a double CMOV, the second Jcc provides the same incoming
20087   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
20088   if (NextCMOV) {
20089     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
20090     // Copy the PHI result to the register defined by the second CMOV.
20091     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
20092             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20093         .addReg(MI->getOperand(0).getReg());
20094     NextCMOV->eraseFromParent();
20095   }
20096
20097   MI->eraseFromParent();   // The pseudo instruction is gone now.
20098   return sinkMBB;
20099 }
20100
20101 MachineBasicBlock *
20102 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20103                                         MachineBasicBlock *BB) const {
20104   MachineFunction *MF = BB->getParent();
20105   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20106   DebugLoc DL = MI->getDebugLoc();
20107   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20108
20109   assert(MF->shouldSplitStack());
20110
20111   const bool Is64Bit = Subtarget->is64Bit();
20112   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20113
20114   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20115   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20116
20117   // BB:
20118   //  ... [Till the alloca]
20119   // If stacklet is not large enough, jump to mallocMBB
20120   //
20121   // bumpMBB:
20122   //  Allocate by subtracting from RSP
20123   //  Jump to continueMBB
20124   //
20125   // mallocMBB:
20126   //  Allocate by call to runtime
20127   //
20128   // continueMBB:
20129   //  ...
20130   //  [rest of original BB]
20131   //
20132
20133   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20134   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20135   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20136
20137   MachineRegisterInfo &MRI = MF->getRegInfo();
20138   const TargetRegisterClass *AddrRegClass =
20139       getRegClassFor(getPointerTy(MF->getDataLayout()));
20140
20141   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20142     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20143     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20144     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20145     sizeVReg = MI->getOperand(1).getReg(),
20146     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20147
20148   MachineFunction::iterator MBBIter = BB;
20149   ++MBBIter;
20150
20151   MF->insert(MBBIter, bumpMBB);
20152   MF->insert(MBBIter, mallocMBB);
20153   MF->insert(MBBIter, continueMBB);
20154
20155   continueMBB->splice(continueMBB->begin(), BB,
20156                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20157   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20158
20159   // Add code to the main basic block to check if the stack limit has been hit,
20160   // and if so, jump to mallocMBB otherwise to bumpMBB.
20161   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20162   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20163     .addReg(tmpSPVReg).addReg(sizeVReg);
20164   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20165     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20166     .addReg(SPLimitVReg);
20167   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20168
20169   // bumpMBB simply decreases the stack pointer, since we know the current
20170   // stacklet has enough space.
20171   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20172     .addReg(SPLimitVReg);
20173   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20174     .addReg(SPLimitVReg);
20175   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20176
20177   // Calls into a routine in libgcc to allocate more space from the heap.
20178   const uint32_t *RegMask =
20179       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20180   if (IsLP64) {
20181     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20182       .addReg(sizeVReg);
20183     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20184       .addExternalSymbol("__morestack_allocate_stack_space")
20185       .addRegMask(RegMask)
20186       .addReg(X86::RDI, RegState::Implicit)
20187       .addReg(X86::RAX, RegState::ImplicitDefine);
20188   } else if (Is64Bit) {
20189     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20190       .addReg(sizeVReg);
20191     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20192       .addExternalSymbol("__morestack_allocate_stack_space")
20193       .addRegMask(RegMask)
20194       .addReg(X86::EDI, RegState::Implicit)
20195       .addReg(X86::EAX, RegState::ImplicitDefine);
20196   } else {
20197     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20198       .addImm(12);
20199     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20200     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20201       .addExternalSymbol("__morestack_allocate_stack_space")
20202       .addRegMask(RegMask)
20203       .addReg(X86::EAX, RegState::ImplicitDefine);
20204   }
20205
20206   if (!Is64Bit)
20207     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20208       .addImm(16);
20209
20210   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20211     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20212   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20213
20214   // Set up the CFG correctly.
20215   BB->addSuccessor(bumpMBB);
20216   BB->addSuccessor(mallocMBB);
20217   mallocMBB->addSuccessor(continueMBB);
20218   bumpMBB->addSuccessor(continueMBB);
20219
20220   // Take care of the PHI nodes.
20221   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20222           MI->getOperand(0).getReg())
20223     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20224     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20225
20226   // Delete the original pseudo instruction.
20227   MI->eraseFromParent();
20228
20229   // And we're done.
20230   return continueMBB;
20231 }
20232
20233 MachineBasicBlock *
20234 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20235                                         MachineBasicBlock *BB) const {
20236   DebugLoc DL = MI->getDebugLoc();
20237
20238   assert(!Subtarget->isTargetMachO());
20239
20240   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20241                                                     DL);
20242
20243   MI->eraseFromParent();   // The pseudo instruction is gone now.
20244   return BB;
20245 }
20246
20247 MachineBasicBlock *
20248 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20249                                       MachineBasicBlock *BB) const {
20250   // This is pretty easy.  We're taking the value that we received from
20251   // our load from the relocation, sticking it in either RDI (x86-64)
20252   // or EAX and doing an indirect call.  The return value will then
20253   // be in the normal return register.
20254   MachineFunction *F = BB->getParent();
20255   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20256   DebugLoc DL = MI->getDebugLoc();
20257
20258   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20259   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20260
20261   // Get a register mask for the lowered call.
20262   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20263   // proper register mask.
20264   const uint32_t *RegMask =
20265       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20266   if (Subtarget->is64Bit()) {
20267     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20268                                       TII->get(X86::MOV64rm), X86::RDI)
20269     .addReg(X86::RIP)
20270     .addImm(0).addReg(0)
20271     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20272                       MI->getOperand(3).getTargetFlags())
20273     .addReg(0);
20274     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20275     addDirectMem(MIB, X86::RDI);
20276     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20277   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20278     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20279                                       TII->get(X86::MOV32rm), X86::EAX)
20280     .addReg(0)
20281     .addImm(0).addReg(0)
20282     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20283                       MI->getOperand(3).getTargetFlags())
20284     .addReg(0);
20285     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20286     addDirectMem(MIB, X86::EAX);
20287     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20288   } else {
20289     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20290                                       TII->get(X86::MOV32rm), X86::EAX)
20291     .addReg(TII->getGlobalBaseReg(F))
20292     .addImm(0).addReg(0)
20293     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20294                       MI->getOperand(3).getTargetFlags())
20295     .addReg(0);
20296     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20297     addDirectMem(MIB, X86::EAX);
20298     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20299   }
20300
20301   MI->eraseFromParent(); // The pseudo instruction is gone now.
20302   return BB;
20303 }
20304
20305 MachineBasicBlock *
20306 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20307                                     MachineBasicBlock *MBB) const {
20308   DebugLoc DL = MI->getDebugLoc();
20309   MachineFunction *MF = MBB->getParent();
20310   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20311   MachineRegisterInfo &MRI = MF->getRegInfo();
20312
20313   const BasicBlock *BB = MBB->getBasicBlock();
20314   MachineFunction::iterator I = MBB;
20315   ++I;
20316
20317   // Memory Reference
20318   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20319   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20320
20321   unsigned DstReg;
20322   unsigned MemOpndSlot = 0;
20323
20324   unsigned CurOp = 0;
20325
20326   DstReg = MI->getOperand(CurOp++).getReg();
20327   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20328   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20329   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20330   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20331
20332   MemOpndSlot = CurOp;
20333
20334   MVT PVT = getPointerTy(MF->getDataLayout());
20335   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20336          "Invalid Pointer Size!");
20337
20338   // For v = setjmp(buf), we generate
20339   //
20340   // thisMBB:
20341   //  buf[LabelOffset] = restoreMBB
20342   //  SjLjSetup restoreMBB
20343   //
20344   // mainMBB:
20345   //  v_main = 0
20346   //
20347   // sinkMBB:
20348   //  v = phi(main, restore)
20349   //
20350   // restoreMBB:
20351   //  if base pointer being used, load it from frame
20352   //  v_restore = 1
20353
20354   MachineBasicBlock *thisMBB = MBB;
20355   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20356   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20357   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20358   MF->insert(I, mainMBB);
20359   MF->insert(I, sinkMBB);
20360   MF->push_back(restoreMBB);
20361
20362   MachineInstrBuilder MIB;
20363
20364   // Transfer the remainder of BB and its successor edges to sinkMBB.
20365   sinkMBB->splice(sinkMBB->begin(), MBB,
20366                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20367   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20368
20369   // thisMBB:
20370   unsigned PtrStoreOpc = 0;
20371   unsigned LabelReg = 0;
20372   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20373   Reloc::Model RM = MF->getTarget().getRelocationModel();
20374   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20375                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20376
20377   // Prepare IP either in reg or imm.
20378   if (!UseImmLabel) {
20379     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20380     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20381     LabelReg = MRI.createVirtualRegister(PtrRC);
20382     if (Subtarget->is64Bit()) {
20383       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20384               .addReg(X86::RIP)
20385               .addImm(0)
20386               .addReg(0)
20387               .addMBB(restoreMBB)
20388               .addReg(0);
20389     } else {
20390       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20391       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20392               .addReg(XII->getGlobalBaseReg(MF))
20393               .addImm(0)
20394               .addReg(0)
20395               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20396               .addReg(0);
20397     }
20398   } else
20399     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20400   // Store IP
20401   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20402   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20403     if (i == X86::AddrDisp)
20404       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20405     else
20406       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20407   }
20408   if (!UseImmLabel)
20409     MIB.addReg(LabelReg);
20410   else
20411     MIB.addMBB(restoreMBB);
20412   MIB.setMemRefs(MMOBegin, MMOEnd);
20413   // Setup
20414   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20415           .addMBB(restoreMBB);
20416
20417   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20418   MIB.addRegMask(RegInfo->getNoPreservedMask());
20419   thisMBB->addSuccessor(mainMBB);
20420   thisMBB->addSuccessor(restoreMBB);
20421
20422   // mainMBB:
20423   //  EAX = 0
20424   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20425   mainMBB->addSuccessor(sinkMBB);
20426
20427   // sinkMBB:
20428   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20429           TII->get(X86::PHI), DstReg)
20430     .addReg(mainDstReg).addMBB(mainMBB)
20431     .addReg(restoreDstReg).addMBB(restoreMBB);
20432
20433   // restoreMBB:
20434   if (RegInfo->hasBasePointer(*MF)) {
20435     const bool Uses64BitFramePtr =
20436         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20437     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20438     X86FI->setRestoreBasePointer(MF);
20439     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20440     unsigned BasePtr = RegInfo->getBaseRegister();
20441     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20442     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20443                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20444       .setMIFlag(MachineInstr::FrameSetup);
20445   }
20446   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20447   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20448   restoreMBB->addSuccessor(sinkMBB);
20449
20450   MI->eraseFromParent();
20451   return sinkMBB;
20452 }
20453
20454 MachineBasicBlock *
20455 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20456                                      MachineBasicBlock *MBB) const {
20457   DebugLoc DL = MI->getDebugLoc();
20458   MachineFunction *MF = MBB->getParent();
20459   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20460   MachineRegisterInfo &MRI = MF->getRegInfo();
20461
20462   // Memory Reference
20463   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20464   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20465
20466   MVT PVT = getPointerTy(MF->getDataLayout());
20467   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20468          "Invalid Pointer Size!");
20469
20470   const TargetRegisterClass *RC =
20471     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20472   unsigned Tmp = MRI.createVirtualRegister(RC);
20473   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20474   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20475   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20476   unsigned SP = RegInfo->getStackRegister();
20477
20478   MachineInstrBuilder MIB;
20479
20480   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20481   const int64_t SPOffset = 2 * PVT.getStoreSize();
20482
20483   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20484   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20485
20486   // Reload FP
20487   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20488   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20489     MIB.addOperand(MI->getOperand(i));
20490   MIB.setMemRefs(MMOBegin, MMOEnd);
20491   // Reload IP
20492   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20493   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20494     if (i == X86::AddrDisp)
20495       MIB.addDisp(MI->getOperand(i), LabelOffset);
20496     else
20497       MIB.addOperand(MI->getOperand(i));
20498   }
20499   MIB.setMemRefs(MMOBegin, MMOEnd);
20500   // Reload SP
20501   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20502   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20503     if (i == X86::AddrDisp)
20504       MIB.addDisp(MI->getOperand(i), SPOffset);
20505     else
20506       MIB.addOperand(MI->getOperand(i));
20507   }
20508   MIB.setMemRefs(MMOBegin, MMOEnd);
20509   // Jump
20510   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20511
20512   MI->eraseFromParent();
20513   return MBB;
20514 }
20515
20516 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20517 // accumulator loops. Writing back to the accumulator allows the coalescer
20518 // to remove extra copies in the loop.
20519 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20520 MachineBasicBlock *
20521 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20522                                  MachineBasicBlock *MBB) const {
20523   MachineOperand &AddendOp = MI->getOperand(3);
20524
20525   // Bail out early if the addend isn't a register - we can't switch these.
20526   if (!AddendOp.isReg())
20527     return MBB;
20528
20529   MachineFunction &MF = *MBB->getParent();
20530   MachineRegisterInfo &MRI = MF.getRegInfo();
20531
20532   // Check whether the addend is defined by a PHI:
20533   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20534   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20535   if (!AddendDef.isPHI())
20536     return MBB;
20537
20538   // Look for the following pattern:
20539   // loop:
20540   //   %addend = phi [%entry, 0], [%loop, %result]
20541   //   ...
20542   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20543
20544   // Replace with:
20545   //   loop:
20546   //   %addend = phi [%entry, 0], [%loop, %result]
20547   //   ...
20548   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20549
20550   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20551     assert(AddendDef.getOperand(i).isReg());
20552     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20553     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20554     if (&PHISrcInst == MI) {
20555       // Found a matching instruction.
20556       unsigned NewFMAOpc = 0;
20557       switch (MI->getOpcode()) {
20558         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20559         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20560         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20561         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20562         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20563         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20564         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20565         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20566         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20567         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20568         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20569         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20570         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20571         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20572         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20573         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20574         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20575         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20576         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20577         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20578
20579         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20580         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20581         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20582         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20583         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20584         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20585         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20586         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20587         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20588         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20589         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20590         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20591         default: llvm_unreachable("Unrecognized FMA variant.");
20592       }
20593
20594       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20595       MachineInstrBuilder MIB =
20596         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20597         .addOperand(MI->getOperand(0))
20598         .addOperand(MI->getOperand(3))
20599         .addOperand(MI->getOperand(2))
20600         .addOperand(MI->getOperand(1));
20601       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20602       MI->eraseFromParent();
20603     }
20604   }
20605
20606   return MBB;
20607 }
20608
20609 MachineBasicBlock *
20610 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20611                                                MachineBasicBlock *BB) const {
20612   switch (MI->getOpcode()) {
20613   default: llvm_unreachable("Unexpected instr type to insert");
20614   case X86::TAILJMPd64:
20615   case X86::TAILJMPr64:
20616   case X86::TAILJMPm64:
20617   case X86::TAILJMPd64_REX:
20618   case X86::TAILJMPr64_REX:
20619   case X86::TAILJMPm64_REX:
20620     llvm_unreachable("TAILJMP64 would not be touched here.");
20621   case X86::TCRETURNdi64:
20622   case X86::TCRETURNri64:
20623   case X86::TCRETURNmi64:
20624     return BB;
20625   case X86::WIN_ALLOCA:
20626     return EmitLoweredWinAlloca(MI, BB);
20627   case X86::SEG_ALLOCA_32:
20628   case X86::SEG_ALLOCA_64:
20629     return EmitLoweredSegAlloca(MI, BB);
20630   case X86::TLSCall_32:
20631   case X86::TLSCall_64:
20632     return EmitLoweredTLSCall(MI, BB);
20633   case X86::CMOV_GR8:
20634   case X86::CMOV_FR32:
20635   case X86::CMOV_FR64:
20636   case X86::CMOV_V4F32:
20637   case X86::CMOV_V2F64:
20638   case X86::CMOV_V2I64:
20639   case X86::CMOV_V8F32:
20640   case X86::CMOV_V4F64:
20641   case X86::CMOV_V4I64:
20642   case X86::CMOV_V16F32:
20643   case X86::CMOV_V8F64:
20644   case X86::CMOV_V8I64:
20645   case X86::CMOV_GR16:
20646   case X86::CMOV_GR32:
20647   case X86::CMOV_RFP32:
20648   case X86::CMOV_RFP64:
20649   case X86::CMOV_RFP80:
20650   case X86::CMOV_V8I1:
20651   case X86::CMOV_V16I1:
20652   case X86::CMOV_V32I1:
20653   case X86::CMOV_V64I1:
20654     return EmitLoweredSelect(MI, BB);
20655
20656   case X86::FP32_TO_INT16_IN_MEM:
20657   case X86::FP32_TO_INT32_IN_MEM:
20658   case X86::FP32_TO_INT64_IN_MEM:
20659   case X86::FP64_TO_INT16_IN_MEM:
20660   case X86::FP64_TO_INT32_IN_MEM:
20661   case X86::FP64_TO_INT64_IN_MEM:
20662   case X86::FP80_TO_INT16_IN_MEM:
20663   case X86::FP80_TO_INT32_IN_MEM:
20664   case X86::FP80_TO_INT64_IN_MEM: {
20665     MachineFunction *F = BB->getParent();
20666     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20667     DebugLoc DL = MI->getDebugLoc();
20668
20669     // Change the floating point control register to use "round towards zero"
20670     // mode when truncating to an integer value.
20671     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20672     addFrameReference(BuildMI(*BB, MI, DL,
20673                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20674
20675     // Load the old value of the high byte of the control word...
20676     unsigned OldCW =
20677       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20678     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20679                       CWFrameIdx);
20680
20681     // Set the high part to be round to zero...
20682     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20683       .addImm(0xC7F);
20684
20685     // Reload the modified control word now...
20686     addFrameReference(BuildMI(*BB, MI, DL,
20687                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20688
20689     // Restore the memory image of control word to original value
20690     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20691       .addReg(OldCW);
20692
20693     // Get the X86 opcode to use.
20694     unsigned Opc;
20695     switch (MI->getOpcode()) {
20696     default: llvm_unreachable("illegal opcode!");
20697     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20698     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20699     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20700     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20701     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20702     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20703     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20704     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20705     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20706     }
20707
20708     X86AddressMode AM;
20709     MachineOperand &Op = MI->getOperand(0);
20710     if (Op.isReg()) {
20711       AM.BaseType = X86AddressMode::RegBase;
20712       AM.Base.Reg = Op.getReg();
20713     } else {
20714       AM.BaseType = X86AddressMode::FrameIndexBase;
20715       AM.Base.FrameIndex = Op.getIndex();
20716     }
20717     Op = MI->getOperand(1);
20718     if (Op.isImm())
20719       AM.Scale = Op.getImm();
20720     Op = MI->getOperand(2);
20721     if (Op.isImm())
20722       AM.IndexReg = Op.getImm();
20723     Op = MI->getOperand(3);
20724     if (Op.isGlobal()) {
20725       AM.GV = Op.getGlobal();
20726     } else {
20727       AM.Disp = Op.getImm();
20728     }
20729     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20730                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20731
20732     // Reload the original control word now.
20733     addFrameReference(BuildMI(*BB, MI, DL,
20734                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20735
20736     MI->eraseFromParent();   // The pseudo instruction is gone now.
20737     return BB;
20738   }
20739     // String/text processing lowering.
20740   case X86::PCMPISTRM128REG:
20741   case X86::VPCMPISTRM128REG:
20742   case X86::PCMPISTRM128MEM:
20743   case X86::VPCMPISTRM128MEM:
20744   case X86::PCMPESTRM128REG:
20745   case X86::VPCMPESTRM128REG:
20746   case X86::PCMPESTRM128MEM:
20747   case X86::VPCMPESTRM128MEM:
20748     assert(Subtarget->hasSSE42() &&
20749            "Target must have SSE4.2 or AVX features enabled");
20750     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20751
20752   // String/text processing lowering.
20753   case X86::PCMPISTRIREG:
20754   case X86::VPCMPISTRIREG:
20755   case X86::PCMPISTRIMEM:
20756   case X86::VPCMPISTRIMEM:
20757   case X86::PCMPESTRIREG:
20758   case X86::VPCMPESTRIREG:
20759   case X86::PCMPESTRIMEM:
20760   case X86::VPCMPESTRIMEM:
20761     assert(Subtarget->hasSSE42() &&
20762            "Target must have SSE4.2 or AVX features enabled");
20763     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20764
20765   // Thread synchronization.
20766   case X86::MONITOR:
20767     return EmitMonitor(MI, BB, Subtarget);
20768
20769   // xbegin
20770   case X86::XBEGIN:
20771     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20772
20773   case X86::VASTART_SAVE_XMM_REGS:
20774     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20775
20776   case X86::VAARG_64:
20777     return EmitVAARG64WithCustomInserter(MI, BB);
20778
20779   case X86::EH_SjLj_SetJmp32:
20780   case X86::EH_SjLj_SetJmp64:
20781     return emitEHSjLjSetJmp(MI, BB);
20782
20783   case X86::EH_SjLj_LongJmp32:
20784   case X86::EH_SjLj_LongJmp64:
20785     return emitEHSjLjLongJmp(MI, BB);
20786
20787   case TargetOpcode::STATEPOINT:
20788     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20789     // this point in the process.  We diverge later.
20790     return emitPatchPoint(MI, BB);
20791
20792   case TargetOpcode::STACKMAP:
20793   case TargetOpcode::PATCHPOINT:
20794     return emitPatchPoint(MI, BB);
20795
20796   case X86::VFMADDPDr213r:
20797   case X86::VFMADDPSr213r:
20798   case X86::VFMADDSDr213r:
20799   case X86::VFMADDSSr213r:
20800   case X86::VFMSUBPDr213r:
20801   case X86::VFMSUBPSr213r:
20802   case X86::VFMSUBSDr213r:
20803   case X86::VFMSUBSSr213r:
20804   case X86::VFNMADDPDr213r:
20805   case X86::VFNMADDPSr213r:
20806   case X86::VFNMADDSDr213r:
20807   case X86::VFNMADDSSr213r:
20808   case X86::VFNMSUBPDr213r:
20809   case X86::VFNMSUBPSr213r:
20810   case X86::VFNMSUBSDr213r:
20811   case X86::VFNMSUBSSr213r:
20812   case X86::VFMADDSUBPDr213r:
20813   case X86::VFMADDSUBPSr213r:
20814   case X86::VFMSUBADDPDr213r:
20815   case X86::VFMSUBADDPSr213r:
20816   case X86::VFMADDPDr213rY:
20817   case X86::VFMADDPSr213rY:
20818   case X86::VFMSUBPDr213rY:
20819   case X86::VFMSUBPSr213rY:
20820   case X86::VFNMADDPDr213rY:
20821   case X86::VFNMADDPSr213rY:
20822   case X86::VFNMSUBPDr213rY:
20823   case X86::VFNMSUBPSr213rY:
20824   case X86::VFMADDSUBPDr213rY:
20825   case X86::VFMADDSUBPSr213rY:
20826   case X86::VFMSUBADDPDr213rY:
20827   case X86::VFMSUBADDPSr213rY:
20828     return emitFMA3Instr(MI, BB);
20829   }
20830 }
20831
20832 //===----------------------------------------------------------------------===//
20833 //                           X86 Optimization Hooks
20834 //===----------------------------------------------------------------------===//
20835
20836 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20837                                                       APInt &KnownZero,
20838                                                       APInt &KnownOne,
20839                                                       const SelectionDAG &DAG,
20840                                                       unsigned Depth) const {
20841   unsigned BitWidth = KnownZero.getBitWidth();
20842   unsigned Opc = Op.getOpcode();
20843   assert((Opc >= ISD::BUILTIN_OP_END ||
20844           Opc == ISD::INTRINSIC_WO_CHAIN ||
20845           Opc == ISD::INTRINSIC_W_CHAIN ||
20846           Opc == ISD::INTRINSIC_VOID) &&
20847          "Should use MaskedValueIsZero if you don't know whether Op"
20848          " is a target node!");
20849
20850   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20851   switch (Opc) {
20852   default: break;
20853   case X86ISD::ADD:
20854   case X86ISD::SUB:
20855   case X86ISD::ADC:
20856   case X86ISD::SBB:
20857   case X86ISD::SMUL:
20858   case X86ISD::UMUL:
20859   case X86ISD::INC:
20860   case X86ISD::DEC:
20861   case X86ISD::OR:
20862   case X86ISD::XOR:
20863   case X86ISD::AND:
20864     // These nodes' second result is a boolean.
20865     if (Op.getResNo() == 0)
20866       break;
20867     // Fallthrough
20868   case X86ISD::SETCC:
20869     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20870     break;
20871   case ISD::INTRINSIC_WO_CHAIN: {
20872     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20873     unsigned NumLoBits = 0;
20874     switch (IntId) {
20875     default: break;
20876     case Intrinsic::x86_sse_movmsk_ps:
20877     case Intrinsic::x86_avx_movmsk_ps_256:
20878     case Intrinsic::x86_sse2_movmsk_pd:
20879     case Intrinsic::x86_avx_movmsk_pd_256:
20880     case Intrinsic::x86_mmx_pmovmskb:
20881     case Intrinsic::x86_sse2_pmovmskb_128:
20882     case Intrinsic::x86_avx2_pmovmskb: {
20883       // High bits of movmskp{s|d}, pmovmskb are known zero.
20884       switch (IntId) {
20885         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20886         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20887         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20888         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20889         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20890         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20891         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20892         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20893       }
20894       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20895       break;
20896     }
20897     }
20898     break;
20899   }
20900   }
20901 }
20902
20903 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20904   SDValue Op,
20905   const SelectionDAG &,
20906   unsigned Depth) const {
20907   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20908   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20909     return Op.getValueType().getScalarType().getSizeInBits();
20910
20911   // Fallback case.
20912   return 1;
20913 }
20914
20915 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20916 /// node is a GlobalAddress + offset.
20917 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20918                                        const GlobalValue* &GA,
20919                                        int64_t &Offset) const {
20920   if (N->getOpcode() == X86ISD::Wrapper) {
20921     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20922       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20923       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20924       return true;
20925     }
20926   }
20927   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20928 }
20929
20930 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20931 /// same as extracting the high 128-bit part of 256-bit vector and then
20932 /// inserting the result into the low part of a new 256-bit vector
20933 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20934   EVT VT = SVOp->getValueType(0);
20935   unsigned NumElems = VT.getVectorNumElements();
20936
20937   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20938   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20939     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20940         SVOp->getMaskElt(j) >= 0)
20941       return false;
20942
20943   return true;
20944 }
20945
20946 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20947 /// same as extracting the low 128-bit part of 256-bit vector and then
20948 /// inserting the result into the high part of a new 256-bit vector
20949 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20950   EVT VT = SVOp->getValueType(0);
20951   unsigned NumElems = VT.getVectorNumElements();
20952
20953   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20954   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20955     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20956         SVOp->getMaskElt(j) >= 0)
20957       return false;
20958
20959   return true;
20960 }
20961
20962 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20963 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20964                                         TargetLowering::DAGCombinerInfo &DCI,
20965                                         const X86Subtarget* Subtarget) {
20966   SDLoc dl(N);
20967   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20968   SDValue V1 = SVOp->getOperand(0);
20969   SDValue V2 = SVOp->getOperand(1);
20970   EVT VT = SVOp->getValueType(0);
20971   unsigned NumElems = VT.getVectorNumElements();
20972
20973   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20974       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20975     //
20976     //                   0,0,0,...
20977     //                      |
20978     //    V      UNDEF    BUILD_VECTOR    UNDEF
20979     //     \      /           \           /
20980     //  CONCAT_VECTOR         CONCAT_VECTOR
20981     //         \                  /
20982     //          \                /
20983     //          RESULT: V + zero extended
20984     //
20985     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20986         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20987         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20988       return SDValue();
20989
20990     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20991       return SDValue();
20992
20993     // To match the shuffle mask, the first half of the mask should
20994     // be exactly the first vector, and all the rest a splat with the
20995     // first element of the second one.
20996     for (unsigned i = 0; i != NumElems/2; ++i)
20997       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20998           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20999         return SDValue();
21000
21001     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
21002     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
21003       if (Ld->hasNUsesOfValue(1, 0)) {
21004         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
21005         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
21006         SDValue ResNode =
21007           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
21008                                   Ld->getMemoryVT(),
21009                                   Ld->getPointerInfo(),
21010                                   Ld->getAlignment(),
21011                                   false/*isVolatile*/, true/*ReadMem*/,
21012                                   false/*WriteMem*/);
21013
21014         // Make sure the newly-created LOAD is in the same position as Ld in
21015         // terms of dependency. We create a TokenFactor for Ld and ResNode,
21016         // and update uses of Ld's output chain to use the TokenFactor.
21017         if (Ld->hasAnyUseOfValue(1)) {
21018           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
21019                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
21020           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
21021           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
21022                                  SDValue(ResNode.getNode(), 1));
21023         }
21024
21025         return DAG.getBitcast(VT, ResNode);
21026       }
21027     }
21028
21029     // Emit a zeroed vector and insert the desired subvector on its
21030     // first half.
21031     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
21032     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
21033     return DCI.CombineTo(N, InsV);
21034   }
21035
21036   //===--------------------------------------------------------------------===//
21037   // Combine some shuffles into subvector extracts and inserts:
21038   //
21039
21040   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
21041   if (isShuffleHigh128VectorInsertLow(SVOp)) {
21042     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
21043     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
21044     return DCI.CombineTo(N, InsV);
21045   }
21046
21047   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
21048   if (isShuffleLow128VectorInsertHigh(SVOp)) {
21049     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
21050     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
21051     return DCI.CombineTo(N, InsV);
21052   }
21053
21054   return SDValue();
21055 }
21056
21057 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
21058 /// possible.
21059 ///
21060 /// This is the leaf of the recursive combinine below. When we have found some
21061 /// chain of single-use x86 shuffle instructions and accumulated the combined
21062 /// shuffle mask represented by them, this will try to pattern match that mask
21063 /// into either a single instruction if there is a special purpose instruction
21064 /// for this operation, or into a PSHUFB instruction which is a fully general
21065 /// instruction but should only be used to replace chains over a certain depth.
21066 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
21067                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
21068                                    TargetLowering::DAGCombinerInfo &DCI,
21069                                    const X86Subtarget *Subtarget) {
21070   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
21071
21072   // Find the operand that enters the chain. Note that multiple uses are OK
21073   // here, we're not going to remove the operand we find.
21074   SDValue Input = Op.getOperand(0);
21075   while (Input.getOpcode() == ISD::BITCAST)
21076     Input = Input.getOperand(0);
21077
21078   MVT VT = Input.getSimpleValueType();
21079   MVT RootVT = Root.getSimpleValueType();
21080   SDLoc DL(Root);
21081
21082   // Just remove no-op shuffle masks.
21083   if (Mask.size() == 1) {
21084     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
21085                   /*AddTo*/ true);
21086     return true;
21087   }
21088
21089   // Use the float domain if the operand type is a floating point type.
21090   bool FloatDomain = VT.isFloatingPoint();
21091
21092   // For floating point shuffles, we don't have free copies in the shuffle
21093   // instructions or the ability to load as part of the instruction, so
21094   // canonicalize their shuffles to UNPCK or MOV variants.
21095   //
21096   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21097   // vectors because it can have a load folded into it that UNPCK cannot. This
21098   // doesn't preclude something switching to the shorter encoding post-RA.
21099   //
21100   // FIXME: Should teach these routines about AVX vector widths.
21101   if (FloatDomain && VT.getSizeInBits() == 128) {
21102     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21103       bool Lo = Mask.equals({0, 0});
21104       unsigned Shuffle;
21105       MVT ShuffleVT;
21106       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21107       // is no slower than UNPCKLPD but has the option to fold the input operand
21108       // into even an unaligned memory load.
21109       if (Lo && Subtarget->hasSSE3()) {
21110         Shuffle = X86ISD::MOVDDUP;
21111         ShuffleVT = MVT::v2f64;
21112       } else {
21113         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21114         // than the UNPCK variants.
21115         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21116         ShuffleVT = MVT::v4f32;
21117       }
21118       if (Depth == 1 && Root->getOpcode() == Shuffle)
21119         return false; // Nothing to do!
21120       Op = DAG.getBitcast(ShuffleVT, Input);
21121       DCI.AddToWorklist(Op.getNode());
21122       if (Shuffle == X86ISD::MOVDDUP)
21123         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21124       else
21125         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21126       DCI.AddToWorklist(Op.getNode());
21127       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21128                     /*AddTo*/ true);
21129       return true;
21130     }
21131     if (Subtarget->hasSSE3() &&
21132         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21133       bool Lo = Mask.equals({0, 0, 2, 2});
21134       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21135       MVT ShuffleVT = MVT::v4f32;
21136       if (Depth == 1 && Root->getOpcode() == Shuffle)
21137         return false; // Nothing to do!
21138       Op = DAG.getBitcast(ShuffleVT, Input);
21139       DCI.AddToWorklist(Op.getNode());
21140       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21141       DCI.AddToWorklist(Op.getNode());
21142       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21143                     /*AddTo*/ true);
21144       return true;
21145     }
21146     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21147       bool Lo = Mask.equals({0, 0, 1, 1});
21148       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21149       MVT ShuffleVT = MVT::v4f32;
21150       if (Depth == 1 && Root->getOpcode() == Shuffle)
21151         return false; // Nothing to do!
21152       Op = DAG.getBitcast(ShuffleVT, Input);
21153       DCI.AddToWorklist(Op.getNode());
21154       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21155       DCI.AddToWorklist(Op.getNode());
21156       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21157                     /*AddTo*/ true);
21158       return true;
21159     }
21160   }
21161
21162   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21163   // variants as none of these have single-instruction variants that are
21164   // superior to the UNPCK formulation.
21165   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21166       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21167        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21168        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21169        Mask.equals(
21170            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21171     bool Lo = Mask[0] == 0;
21172     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21173     if (Depth == 1 && Root->getOpcode() == Shuffle)
21174       return false; // Nothing to do!
21175     MVT ShuffleVT;
21176     switch (Mask.size()) {
21177     case 8:
21178       ShuffleVT = MVT::v8i16;
21179       break;
21180     case 16:
21181       ShuffleVT = MVT::v16i8;
21182       break;
21183     default:
21184       llvm_unreachable("Impossible mask size!");
21185     };
21186     Op = DAG.getBitcast(ShuffleVT, Input);
21187     DCI.AddToWorklist(Op.getNode());
21188     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21189     DCI.AddToWorklist(Op.getNode());
21190     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21191                   /*AddTo*/ true);
21192     return true;
21193   }
21194
21195   // Don't try to re-form single instruction chains under any circumstances now
21196   // that we've done encoding canonicalization for them.
21197   if (Depth < 2)
21198     return false;
21199
21200   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21201   // can replace them with a single PSHUFB instruction profitably. Intel's
21202   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21203   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21204   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21205     SmallVector<SDValue, 16> PSHUFBMask;
21206     int NumBytes = VT.getSizeInBits() / 8;
21207     int Ratio = NumBytes / Mask.size();
21208     for (int i = 0; i < NumBytes; ++i) {
21209       if (Mask[i / Ratio] == SM_SentinelUndef) {
21210         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21211         continue;
21212       }
21213       int M = Mask[i / Ratio] != SM_SentinelZero
21214                   ? Ratio * Mask[i / Ratio] + i % Ratio
21215                   : 255;
21216       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21217     }
21218     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21219     Op = DAG.getBitcast(ByteVT, Input);
21220     DCI.AddToWorklist(Op.getNode());
21221     SDValue PSHUFBMaskOp =
21222         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21223     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21224     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21225     DCI.AddToWorklist(Op.getNode());
21226     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21227                   /*AddTo*/ true);
21228     return true;
21229   }
21230
21231   // Failed to find any combines.
21232   return false;
21233 }
21234
21235 /// \brief Fully generic combining of x86 shuffle instructions.
21236 ///
21237 /// This should be the last combine run over the x86 shuffle instructions. Once
21238 /// they have been fully optimized, this will recursively consider all chains
21239 /// of single-use shuffle instructions, build a generic model of the cumulative
21240 /// shuffle operation, and check for simpler instructions which implement this
21241 /// operation. We use this primarily for two purposes:
21242 ///
21243 /// 1) Collapse generic shuffles to specialized single instructions when
21244 ///    equivalent. In most cases, this is just an encoding size win, but
21245 ///    sometimes we will collapse multiple generic shuffles into a single
21246 ///    special-purpose shuffle.
21247 /// 2) Look for sequences of shuffle instructions with 3 or more total
21248 ///    instructions, and replace them with the slightly more expensive SSSE3
21249 ///    PSHUFB instruction if available. We do this as the last combining step
21250 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21251 ///    a suitable short sequence of other instructions. The PHUFB will either
21252 ///    use a register or have to read from memory and so is slightly (but only
21253 ///    slightly) more expensive than the other shuffle instructions.
21254 ///
21255 /// Because this is inherently a quadratic operation (for each shuffle in
21256 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21257 /// This should never be an issue in practice as the shuffle lowering doesn't
21258 /// produce sequences of more than 8 instructions.
21259 ///
21260 /// FIXME: We will currently miss some cases where the redundant shuffling
21261 /// would simplify under the threshold for PSHUFB formation because of
21262 /// combine-ordering. To fix this, we should do the redundant instruction
21263 /// combining in this recursive walk.
21264 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21265                                           ArrayRef<int> RootMask,
21266                                           int Depth, bool HasPSHUFB,
21267                                           SelectionDAG &DAG,
21268                                           TargetLowering::DAGCombinerInfo &DCI,
21269                                           const X86Subtarget *Subtarget) {
21270   // Bound the depth of our recursive combine because this is ultimately
21271   // quadratic in nature.
21272   if (Depth > 8)
21273     return false;
21274
21275   // Directly rip through bitcasts to find the underlying operand.
21276   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21277     Op = Op.getOperand(0);
21278
21279   MVT VT = Op.getSimpleValueType();
21280   if (!VT.isVector())
21281     return false; // Bail if we hit a non-vector.
21282
21283   assert(Root.getSimpleValueType().isVector() &&
21284          "Shuffles operate on vector types!");
21285   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21286          "Can only combine shuffles of the same vector register size.");
21287
21288   if (!isTargetShuffle(Op.getOpcode()))
21289     return false;
21290   SmallVector<int, 16> OpMask;
21291   bool IsUnary;
21292   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21293   // We only can combine unary shuffles which we can decode the mask for.
21294   if (!HaveMask || !IsUnary)
21295     return false;
21296
21297   assert(VT.getVectorNumElements() == OpMask.size() &&
21298          "Different mask size from vector size!");
21299   assert(((RootMask.size() > OpMask.size() &&
21300            RootMask.size() % OpMask.size() == 0) ||
21301           (OpMask.size() > RootMask.size() &&
21302            OpMask.size() % RootMask.size() == 0) ||
21303           OpMask.size() == RootMask.size()) &&
21304          "The smaller number of elements must divide the larger.");
21305   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21306   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21307   assert(((RootRatio == 1 && OpRatio == 1) ||
21308           (RootRatio == 1) != (OpRatio == 1)) &&
21309          "Must not have a ratio for both incoming and op masks!");
21310
21311   SmallVector<int, 16> Mask;
21312   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21313
21314   // Merge this shuffle operation's mask into our accumulated mask. Note that
21315   // this shuffle's mask will be the first applied to the input, followed by the
21316   // root mask to get us all the way to the root value arrangement. The reason
21317   // for this order is that we are recursing up the operation chain.
21318   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21319     int RootIdx = i / RootRatio;
21320     if (RootMask[RootIdx] < 0) {
21321       // This is a zero or undef lane, we're done.
21322       Mask.push_back(RootMask[RootIdx]);
21323       continue;
21324     }
21325
21326     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21327     int OpIdx = RootMaskedIdx / OpRatio;
21328     if (OpMask[OpIdx] < 0) {
21329       // The incoming lanes are zero or undef, it doesn't matter which ones we
21330       // are using.
21331       Mask.push_back(OpMask[OpIdx]);
21332       continue;
21333     }
21334
21335     // Ok, we have non-zero lanes, map them through.
21336     Mask.push_back(OpMask[OpIdx] * OpRatio +
21337                    RootMaskedIdx % OpRatio);
21338   }
21339
21340   // See if we can recurse into the operand to combine more things.
21341   switch (Op.getOpcode()) {
21342     case X86ISD::PSHUFB:
21343       HasPSHUFB = true;
21344     case X86ISD::PSHUFD:
21345     case X86ISD::PSHUFHW:
21346     case X86ISD::PSHUFLW:
21347       if (Op.getOperand(0).hasOneUse() &&
21348           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21349                                         HasPSHUFB, DAG, DCI, Subtarget))
21350         return true;
21351       break;
21352
21353     case X86ISD::UNPCKL:
21354     case X86ISD::UNPCKH:
21355       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21356       // We can't check for single use, we have to check that this shuffle is the only user.
21357       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21358           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21359                                         HasPSHUFB, DAG, DCI, Subtarget))
21360           return true;
21361       break;
21362   }
21363
21364   // Minor canonicalization of the accumulated shuffle mask to make it easier
21365   // to match below. All this does is detect masks with squential pairs of
21366   // elements, and shrink them to the half-width mask. It does this in a loop
21367   // so it will reduce the size of the mask to the minimal width mask which
21368   // performs an equivalent shuffle.
21369   SmallVector<int, 16> WidenedMask;
21370   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21371     Mask = std::move(WidenedMask);
21372     WidenedMask.clear();
21373   }
21374
21375   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21376                                 Subtarget);
21377 }
21378
21379 /// \brief Get the PSHUF-style mask from PSHUF node.
21380 ///
21381 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21382 /// PSHUF-style masks that can be reused with such instructions.
21383 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21384   MVT VT = N.getSimpleValueType();
21385   SmallVector<int, 4> Mask;
21386   bool IsUnary;
21387   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21388   (void)HaveMask;
21389   assert(HaveMask);
21390
21391   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21392   // matter. Check that the upper masks are repeats and remove them.
21393   if (VT.getSizeInBits() > 128) {
21394     int LaneElts = 128 / VT.getScalarSizeInBits();
21395 #ifndef NDEBUG
21396     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21397       for (int j = 0; j < LaneElts; ++j)
21398         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21399                "Mask doesn't repeat in high 128-bit lanes!");
21400 #endif
21401     Mask.resize(LaneElts);
21402   }
21403
21404   switch (N.getOpcode()) {
21405   case X86ISD::PSHUFD:
21406     return Mask;
21407   case X86ISD::PSHUFLW:
21408     Mask.resize(4);
21409     return Mask;
21410   case X86ISD::PSHUFHW:
21411     Mask.erase(Mask.begin(), Mask.begin() + 4);
21412     for (int &M : Mask)
21413       M -= 4;
21414     return Mask;
21415   default:
21416     llvm_unreachable("No valid shuffle instruction found!");
21417   }
21418 }
21419
21420 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21421 ///
21422 /// We walk up the chain and look for a combinable shuffle, skipping over
21423 /// shuffles that we could hoist this shuffle's transformation past without
21424 /// altering anything.
21425 static SDValue
21426 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21427                              SelectionDAG &DAG,
21428                              TargetLowering::DAGCombinerInfo &DCI) {
21429   assert(N.getOpcode() == X86ISD::PSHUFD &&
21430          "Called with something other than an x86 128-bit half shuffle!");
21431   SDLoc DL(N);
21432
21433   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21434   // of the shuffles in the chain so that we can form a fresh chain to replace
21435   // this one.
21436   SmallVector<SDValue, 8> Chain;
21437   SDValue V = N.getOperand(0);
21438   for (; V.hasOneUse(); V = V.getOperand(0)) {
21439     switch (V.getOpcode()) {
21440     default:
21441       return SDValue(); // Nothing combined!
21442
21443     case ISD::BITCAST:
21444       // Skip bitcasts as we always know the type for the target specific
21445       // instructions.
21446       continue;
21447
21448     case X86ISD::PSHUFD:
21449       // Found another dword shuffle.
21450       break;
21451
21452     case X86ISD::PSHUFLW:
21453       // Check that the low words (being shuffled) are the identity in the
21454       // dword shuffle, and the high words are self-contained.
21455       if (Mask[0] != 0 || Mask[1] != 1 ||
21456           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21457         return SDValue();
21458
21459       Chain.push_back(V);
21460       continue;
21461
21462     case X86ISD::PSHUFHW:
21463       // Check that the high words (being shuffled) are the identity in the
21464       // dword shuffle, and the low words are self-contained.
21465       if (Mask[2] != 2 || Mask[3] != 3 ||
21466           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21467         return SDValue();
21468
21469       Chain.push_back(V);
21470       continue;
21471
21472     case X86ISD::UNPCKL:
21473     case X86ISD::UNPCKH:
21474       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21475       // shuffle into a preceding word shuffle.
21476       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21477           V.getSimpleValueType().getScalarType() != MVT::i16)
21478         return SDValue();
21479
21480       // Search for a half-shuffle which we can combine with.
21481       unsigned CombineOp =
21482           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21483       if (V.getOperand(0) != V.getOperand(1) ||
21484           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21485         return SDValue();
21486       Chain.push_back(V);
21487       V = V.getOperand(0);
21488       do {
21489         switch (V.getOpcode()) {
21490         default:
21491           return SDValue(); // Nothing to combine.
21492
21493         case X86ISD::PSHUFLW:
21494         case X86ISD::PSHUFHW:
21495           if (V.getOpcode() == CombineOp)
21496             break;
21497
21498           Chain.push_back(V);
21499
21500           // Fallthrough!
21501         case ISD::BITCAST:
21502           V = V.getOperand(0);
21503           continue;
21504         }
21505         break;
21506       } while (V.hasOneUse());
21507       break;
21508     }
21509     // Break out of the loop if we break out of the switch.
21510     break;
21511   }
21512
21513   if (!V.hasOneUse())
21514     // We fell out of the loop without finding a viable combining instruction.
21515     return SDValue();
21516
21517   // Merge this node's mask and our incoming mask.
21518   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21519   for (int &M : Mask)
21520     M = VMask[M];
21521   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21522                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21523
21524   // Rebuild the chain around this new shuffle.
21525   while (!Chain.empty()) {
21526     SDValue W = Chain.pop_back_val();
21527
21528     if (V.getValueType() != W.getOperand(0).getValueType())
21529       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21530
21531     switch (W.getOpcode()) {
21532     default:
21533       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21534
21535     case X86ISD::UNPCKL:
21536     case X86ISD::UNPCKH:
21537       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21538       break;
21539
21540     case X86ISD::PSHUFD:
21541     case X86ISD::PSHUFLW:
21542     case X86ISD::PSHUFHW:
21543       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21544       break;
21545     }
21546   }
21547   if (V.getValueType() != N.getValueType())
21548     V = DAG.getBitcast(N.getValueType(), V);
21549
21550   // Return the new chain to replace N.
21551   return V;
21552 }
21553
21554 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21555 ///
21556 /// We walk up the chain, skipping shuffles of the other half and looking
21557 /// through shuffles which switch halves trying to find a shuffle of the same
21558 /// pair of dwords.
21559 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21560                                         SelectionDAG &DAG,
21561                                         TargetLowering::DAGCombinerInfo &DCI) {
21562   assert(
21563       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21564       "Called with something other than an x86 128-bit half shuffle!");
21565   SDLoc DL(N);
21566   unsigned CombineOpcode = N.getOpcode();
21567
21568   // Walk up a single-use chain looking for a combinable shuffle.
21569   SDValue V = N.getOperand(0);
21570   for (; V.hasOneUse(); V = V.getOperand(0)) {
21571     switch (V.getOpcode()) {
21572     default:
21573       return false; // Nothing combined!
21574
21575     case ISD::BITCAST:
21576       // Skip bitcasts as we always know the type for the target specific
21577       // instructions.
21578       continue;
21579
21580     case X86ISD::PSHUFLW:
21581     case X86ISD::PSHUFHW:
21582       if (V.getOpcode() == CombineOpcode)
21583         break;
21584
21585       // Other-half shuffles are no-ops.
21586       continue;
21587     }
21588     // Break out of the loop if we break out of the switch.
21589     break;
21590   }
21591
21592   if (!V.hasOneUse())
21593     // We fell out of the loop without finding a viable combining instruction.
21594     return false;
21595
21596   // Combine away the bottom node as its shuffle will be accumulated into
21597   // a preceding shuffle.
21598   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21599
21600   // Record the old value.
21601   SDValue Old = V;
21602
21603   // Merge this node's mask and our incoming mask (adjusted to account for all
21604   // the pshufd instructions encountered).
21605   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21606   for (int &M : Mask)
21607     M = VMask[M];
21608   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21609                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21610
21611   // Check that the shuffles didn't cancel each other out. If not, we need to
21612   // combine to the new one.
21613   if (Old != V)
21614     // Replace the combinable shuffle with the combined one, updating all users
21615     // so that we re-evaluate the chain here.
21616     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21617
21618   return true;
21619 }
21620
21621 /// \brief Try to combine x86 target specific shuffles.
21622 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21623                                            TargetLowering::DAGCombinerInfo &DCI,
21624                                            const X86Subtarget *Subtarget) {
21625   SDLoc DL(N);
21626   MVT VT = N.getSimpleValueType();
21627   SmallVector<int, 4> Mask;
21628
21629   switch (N.getOpcode()) {
21630   case X86ISD::PSHUFD:
21631   case X86ISD::PSHUFLW:
21632   case X86ISD::PSHUFHW:
21633     Mask = getPSHUFShuffleMask(N);
21634     assert(Mask.size() == 4);
21635     break;
21636   default:
21637     return SDValue();
21638   }
21639
21640   // Nuke no-op shuffles that show up after combining.
21641   if (isNoopShuffleMask(Mask))
21642     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21643
21644   // Look for simplifications involving one or two shuffle instructions.
21645   SDValue V = N.getOperand(0);
21646   switch (N.getOpcode()) {
21647   default:
21648     break;
21649   case X86ISD::PSHUFLW:
21650   case X86ISD::PSHUFHW:
21651     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21652
21653     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21654       return SDValue(); // We combined away this shuffle, so we're done.
21655
21656     // See if this reduces to a PSHUFD which is no more expensive and can
21657     // combine with more operations. Note that it has to at least flip the
21658     // dwords as otherwise it would have been removed as a no-op.
21659     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21660       int DMask[] = {0, 1, 2, 3};
21661       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21662       DMask[DOffset + 0] = DOffset + 1;
21663       DMask[DOffset + 1] = DOffset + 0;
21664       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21665       V = DAG.getBitcast(DVT, V);
21666       DCI.AddToWorklist(V.getNode());
21667       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21668                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21669       DCI.AddToWorklist(V.getNode());
21670       return DAG.getBitcast(VT, V);
21671     }
21672
21673     // Look for shuffle patterns which can be implemented as a single unpack.
21674     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21675     // only works when we have a PSHUFD followed by two half-shuffles.
21676     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21677         (V.getOpcode() == X86ISD::PSHUFLW ||
21678          V.getOpcode() == X86ISD::PSHUFHW) &&
21679         V.getOpcode() != N.getOpcode() &&
21680         V.hasOneUse()) {
21681       SDValue D = V.getOperand(0);
21682       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21683         D = D.getOperand(0);
21684       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21685         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21686         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21687         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21688         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21689         int WordMask[8];
21690         for (int i = 0; i < 4; ++i) {
21691           WordMask[i + NOffset] = Mask[i] + NOffset;
21692           WordMask[i + VOffset] = VMask[i] + VOffset;
21693         }
21694         // Map the word mask through the DWord mask.
21695         int MappedMask[8];
21696         for (int i = 0; i < 8; ++i)
21697           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21698         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21699             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21700           // We can replace all three shuffles with an unpack.
21701           V = DAG.getBitcast(VT, D.getOperand(0));
21702           DCI.AddToWorklist(V.getNode());
21703           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21704                                                 : X86ISD::UNPCKH,
21705                              DL, VT, V, V);
21706         }
21707       }
21708     }
21709
21710     break;
21711
21712   case X86ISD::PSHUFD:
21713     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21714       return NewN;
21715
21716     break;
21717   }
21718
21719   return SDValue();
21720 }
21721
21722 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21723 ///
21724 /// We combine this directly on the abstract vector shuffle nodes so it is
21725 /// easier to generically match. We also insert dummy vector shuffle nodes for
21726 /// the operands which explicitly discard the lanes which are unused by this
21727 /// operation to try to flow through the rest of the combiner the fact that
21728 /// they're unused.
21729 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21730   SDLoc DL(N);
21731   EVT VT = N->getValueType(0);
21732
21733   // We only handle target-independent shuffles.
21734   // FIXME: It would be easy and harmless to use the target shuffle mask
21735   // extraction tool to support more.
21736   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21737     return SDValue();
21738
21739   auto *SVN = cast<ShuffleVectorSDNode>(N);
21740   ArrayRef<int> Mask = SVN->getMask();
21741   SDValue V1 = N->getOperand(0);
21742   SDValue V2 = N->getOperand(1);
21743
21744   // We require the first shuffle operand to be the SUB node, and the second to
21745   // be the ADD node.
21746   // FIXME: We should support the commuted patterns.
21747   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21748     return SDValue();
21749
21750   // If there are other uses of these operations we can't fold them.
21751   if (!V1->hasOneUse() || !V2->hasOneUse())
21752     return SDValue();
21753
21754   // Ensure that both operations have the same operands. Note that we can
21755   // commute the FADD operands.
21756   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21757   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21758       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21759     return SDValue();
21760
21761   // We're looking for blends between FADD and FSUB nodes. We insist on these
21762   // nodes being lined up in a specific expected pattern.
21763   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21764         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21765         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21766     return SDValue();
21767
21768   // Only specific types are legal at this point, assert so we notice if and
21769   // when these change.
21770   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21771           VT == MVT::v4f64) &&
21772          "Unknown vector type encountered!");
21773
21774   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21775 }
21776
21777 /// PerformShuffleCombine - Performs several different shuffle combines.
21778 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21779                                      TargetLowering::DAGCombinerInfo &DCI,
21780                                      const X86Subtarget *Subtarget) {
21781   SDLoc dl(N);
21782   SDValue N0 = N->getOperand(0);
21783   SDValue N1 = N->getOperand(1);
21784   EVT VT = N->getValueType(0);
21785
21786   // Don't create instructions with illegal types after legalize types has run.
21787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21788   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21789     return SDValue();
21790
21791   // If we have legalized the vector types, look for blends of FADD and FSUB
21792   // nodes that we can fuse into an ADDSUB node.
21793   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21794     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21795       return AddSub;
21796
21797   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21798   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21799       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21800     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21801
21802   // During Type Legalization, when promoting illegal vector types,
21803   // the backend might introduce new shuffle dag nodes and bitcasts.
21804   //
21805   // This code performs the following transformation:
21806   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21807   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21808   //
21809   // We do this only if both the bitcast and the BINOP dag nodes have
21810   // one use. Also, perform this transformation only if the new binary
21811   // operation is legal. This is to avoid introducing dag nodes that
21812   // potentially need to be further expanded (or custom lowered) into a
21813   // less optimal sequence of dag nodes.
21814   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21815       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21816       N0.getOpcode() == ISD::BITCAST) {
21817     SDValue BC0 = N0.getOperand(0);
21818     EVT SVT = BC0.getValueType();
21819     unsigned Opcode = BC0.getOpcode();
21820     unsigned NumElts = VT.getVectorNumElements();
21821
21822     if (BC0.hasOneUse() && SVT.isVector() &&
21823         SVT.getVectorNumElements() * 2 == NumElts &&
21824         TLI.isOperationLegal(Opcode, VT)) {
21825       bool CanFold = false;
21826       switch (Opcode) {
21827       default : break;
21828       case ISD::ADD :
21829       case ISD::FADD :
21830       case ISD::SUB :
21831       case ISD::FSUB :
21832       case ISD::MUL :
21833       case ISD::FMUL :
21834         CanFold = true;
21835       }
21836
21837       unsigned SVTNumElts = SVT.getVectorNumElements();
21838       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21839       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21840         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21841       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21842         CanFold = SVOp->getMaskElt(i) < 0;
21843
21844       if (CanFold) {
21845         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21846         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21847         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21848         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21849       }
21850     }
21851   }
21852
21853   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21854   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21855   // consecutive, non-overlapping, and in the right order.
21856   SmallVector<SDValue, 16> Elts;
21857   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21858     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21859
21860   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21861     return LD;
21862
21863   if (isTargetShuffle(N->getOpcode())) {
21864     SDValue Shuffle =
21865         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21866     if (Shuffle.getNode())
21867       return Shuffle;
21868
21869     // Try recursively combining arbitrary sequences of x86 shuffle
21870     // instructions into higher-order shuffles. We do this after combining
21871     // specific PSHUF instruction sequences into their minimal form so that we
21872     // can evaluate how many specialized shuffle instructions are involved in
21873     // a particular chain.
21874     SmallVector<int, 1> NonceMask; // Just a placeholder.
21875     NonceMask.push_back(0);
21876     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21877                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21878                                       DCI, Subtarget))
21879       return SDValue(); // This routine will use CombineTo to replace N.
21880   }
21881
21882   return SDValue();
21883 }
21884
21885 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21886 /// specific shuffle of a load can be folded into a single element load.
21887 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21888 /// shuffles have been custom lowered so we need to handle those here.
21889 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21890                                          TargetLowering::DAGCombinerInfo &DCI) {
21891   if (DCI.isBeforeLegalizeOps())
21892     return SDValue();
21893
21894   SDValue InVec = N->getOperand(0);
21895   SDValue EltNo = N->getOperand(1);
21896
21897   if (!isa<ConstantSDNode>(EltNo))
21898     return SDValue();
21899
21900   EVT OriginalVT = InVec.getValueType();
21901
21902   if (InVec.getOpcode() == ISD::BITCAST) {
21903     // Don't duplicate a load with other uses.
21904     if (!InVec.hasOneUse())
21905       return SDValue();
21906     EVT BCVT = InVec.getOperand(0).getValueType();
21907     if (!BCVT.isVector() ||
21908         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21909       return SDValue();
21910     InVec = InVec.getOperand(0);
21911   }
21912
21913   EVT CurrentVT = InVec.getValueType();
21914
21915   if (!isTargetShuffle(InVec.getOpcode()))
21916     return SDValue();
21917
21918   // Don't duplicate a load with other uses.
21919   if (!InVec.hasOneUse())
21920     return SDValue();
21921
21922   SmallVector<int, 16> ShuffleMask;
21923   bool UnaryShuffle;
21924   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21925                             ShuffleMask, UnaryShuffle))
21926     return SDValue();
21927
21928   // Select the input vector, guarding against out of range extract vector.
21929   unsigned NumElems = CurrentVT.getVectorNumElements();
21930   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21931   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21932   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21933                                          : InVec.getOperand(1);
21934
21935   // If inputs to shuffle are the same for both ops, then allow 2 uses
21936   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21937                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21938
21939   if (LdNode.getOpcode() == ISD::BITCAST) {
21940     // Don't duplicate a load with other uses.
21941     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21942       return SDValue();
21943
21944     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21945     LdNode = LdNode.getOperand(0);
21946   }
21947
21948   if (!ISD::isNormalLoad(LdNode.getNode()))
21949     return SDValue();
21950
21951   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21952
21953   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21954     return SDValue();
21955
21956   EVT EltVT = N->getValueType(0);
21957   // If there's a bitcast before the shuffle, check if the load type and
21958   // alignment is valid.
21959   unsigned Align = LN0->getAlignment();
21960   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21961   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21962       EltVT.getTypeForEVT(*DAG.getContext()));
21963
21964   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21965     return SDValue();
21966
21967   // All checks match so transform back to vector_shuffle so that DAG combiner
21968   // can finish the job
21969   SDLoc dl(N);
21970
21971   // Create shuffle node taking into account the case that its a unary shuffle
21972   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21973                                    : InVec.getOperand(1);
21974   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21975                                  InVec.getOperand(0), Shuffle,
21976                                  &ShuffleMask[0]);
21977   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21978   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21979                      EltNo);
21980 }
21981
21982 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21983 /// special and don't usually play with other vector types, it's better to
21984 /// handle them early to be sure we emit efficient code by avoiding
21985 /// store-load conversions.
21986 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21987   if (N->getValueType(0) != MVT::x86mmx ||
21988       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21989       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21990     return SDValue();
21991
21992   SDValue V = N->getOperand(0);
21993   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21994   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21995     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21996                        N->getValueType(0), V.getOperand(0));
21997
21998   return SDValue();
21999 }
22000
22001 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
22002 /// generation and convert it from being a bunch of shuffles and extracts
22003 /// into a somewhat faster sequence. For i686, the best sequence is apparently
22004 /// storing the value and loading scalars back, while for x64 we should
22005 /// use 64-bit extracts and shifts.
22006 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
22007                                          TargetLowering::DAGCombinerInfo &DCI) {
22008   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
22009     return NewOp;
22010
22011   SDValue InputVector = N->getOperand(0);
22012   SDLoc dl(InputVector);
22013   // Detect mmx to i32 conversion through a v2i32 elt extract.
22014   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
22015       N->getValueType(0) == MVT::i32 &&
22016       InputVector.getValueType() == MVT::v2i32) {
22017
22018     // The bitcast source is a direct mmx result.
22019     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
22020     if (MMXSrc.getValueType() == MVT::x86mmx)
22021       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22022                          N->getValueType(0),
22023                          InputVector.getNode()->getOperand(0));
22024
22025     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
22026     SDValue MMXSrcOp = MMXSrc.getOperand(0);
22027     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
22028         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
22029         MMXSrcOp.getOpcode() == ISD::BITCAST &&
22030         MMXSrcOp.getValueType() == MVT::v1i64 &&
22031         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
22032       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
22033                          N->getValueType(0),
22034                          MMXSrcOp.getOperand(0));
22035   }
22036
22037   EVT VT = N->getValueType(0);
22038
22039   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
22040       InputVector.getOpcode() == ISD::BITCAST &&
22041       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
22042     uint64_t ExtractedElt =
22043           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
22044     uint64_t InputValue =
22045           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
22046     uint64_t Res = (InputValue >> ExtractedElt) & 1;
22047     return DAG.getConstant(Res, dl, MVT::i1);
22048   }
22049   // Only operate on vectors of 4 elements, where the alternative shuffling
22050   // gets to be more expensive.
22051   if (InputVector.getValueType() != MVT::v4i32)
22052     return SDValue();
22053
22054   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
22055   // single use which is a sign-extend or zero-extend, and all elements are
22056   // used.
22057   SmallVector<SDNode *, 4> Uses;
22058   unsigned ExtractedElements = 0;
22059   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
22060        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
22061     if (UI.getUse().getResNo() != InputVector.getResNo())
22062       return SDValue();
22063
22064     SDNode *Extract = *UI;
22065     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
22066       return SDValue();
22067
22068     if (Extract->getValueType(0) != MVT::i32)
22069       return SDValue();
22070     if (!Extract->hasOneUse())
22071       return SDValue();
22072     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
22073         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
22074       return SDValue();
22075     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
22076       return SDValue();
22077
22078     // Record which element was extracted.
22079     ExtractedElements |=
22080       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
22081
22082     Uses.push_back(Extract);
22083   }
22084
22085   // If not all the elements were used, this may not be worthwhile.
22086   if (ExtractedElements != 15)
22087     return SDValue();
22088
22089   // Ok, we've now decided to do the transformation.
22090   // If 64-bit shifts are legal, use the extract-shift sequence,
22091   // otherwise bounce the vector off the cache.
22092   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22093   SDValue Vals[4];
22094
22095   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22096     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22097     auto &DL = DAG.getDataLayout();
22098     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22099     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22100       DAG.getConstant(0, dl, VecIdxTy));
22101     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22102       DAG.getConstant(1, dl, VecIdxTy));
22103
22104     SDValue ShAmt = DAG.getConstant(
22105         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22106     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22107     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22108       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22109     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22110     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22111       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22112   } else {
22113     // Store the value to a temporary stack slot.
22114     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22115     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22116       MachinePointerInfo(), false, false, 0);
22117
22118     EVT ElementType = InputVector.getValueType().getVectorElementType();
22119     unsigned EltSize = ElementType.getSizeInBits() / 8;
22120
22121     // Replace each use (extract) with a load of the appropriate element.
22122     for (unsigned i = 0; i < 4; ++i) {
22123       uint64_t Offset = EltSize * i;
22124       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22125       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22126
22127       SDValue ScalarAddr =
22128           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22129
22130       // Load the scalar.
22131       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22132                             ScalarAddr, MachinePointerInfo(),
22133                             false, false, false, 0);
22134
22135     }
22136   }
22137
22138   // Replace the extracts
22139   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22140     UE = Uses.end(); UI != UE; ++UI) {
22141     SDNode *Extract = *UI;
22142
22143     SDValue Idx = Extract->getOperand(1);
22144     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22145     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22146   }
22147
22148   // The replacement was made in place; don't return anything.
22149   return SDValue();
22150 }
22151
22152 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22153 static std::pair<unsigned, bool>
22154 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22155                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22156   if (!VT.isVector())
22157     return std::make_pair(0, false);
22158
22159   bool NeedSplit = false;
22160   switch (VT.getSimpleVT().SimpleTy) {
22161   default: return std::make_pair(0, false);
22162   case MVT::v4i64:
22163   case MVT::v2i64:
22164     if (!Subtarget->hasVLX())
22165       return std::make_pair(0, false);
22166     break;
22167   case MVT::v64i8:
22168   case MVT::v32i16:
22169     if (!Subtarget->hasBWI())
22170       return std::make_pair(0, false);
22171     break;
22172   case MVT::v16i32:
22173   case MVT::v8i64:
22174     if (!Subtarget->hasAVX512())
22175       return std::make_pair(0, false);
22176     break;
22177   case MVT::v32i8:
22178   case MVT::v16i16:
22179   case MVT::v8i32:
22180     if (!Subtarget->hasAVX2())
22181       NeedSplit = true;
22182     if (!Subtarget->hasAVX())
22183       return std::make_pair(0, false);
22184     break;
22185   case MVT::v16i8:
22186   case MVT::v8i16:
22187   case MVT::v4i32:
22188     if (!Subtarget->hasSSE2())
22189       return std::make_pair(0, false);
22190   }
22191
22192   // SSE2 has only a small subset of the operations.
22193   bool hasUnsigned = Subtarget->hasSSE41() ||
22194                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22195   bool hasSigned = Subtarget->hasSSE41() ||
22196                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22197
22198   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22199
22200   unsigned Opc = 0;
22201   // Check for x CC y ? x : y.
22202   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22203       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22204     switch (CC) {
22205     default: break;
22206     case ISD::SETULT:
22207     case ISD::SETULE:
22208       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22209     case ISD::SETUGT:
22210     case ISD::SETUGE:
22211       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22212     case ISD::SETLT:
22213     case ISD::SETLE:
22214       Opc = hasSigned ? ISD::SMIN : 0; break;
22215     case ISD::SETGT:
22216     case ISD::SETGE:
22217       Opc = hasSigned ? ISD::SMAX : 0; break;
22218     }
22219   // Check for x CC y ? y : x -- a min/max with reversed arms.
22220   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22221              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22222     switch (CC) {
22223     default: break;
22224     case ISD::SETULT:
22225     case ISD::SETULE:
22226       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22227     case ISD::SETUGT:
22228     case ISD::SETUGE:
22229       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22230     case ISD::SETLT:
22231     case ISD::SETLE:
22232       Opc = hasSigned ? ISD::SMAX : 0; break;
22233     case ISD::SETGT:
22234     case ISD::SETGE:
22235       Opc = hasSigned ? ISD::SMIN : 0; break;
22236     }
22237   }
22238
22239   return std::make_pair(Opc, NeedSplit);
22240 }
22241
22242 static SDValue
22243 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22244                                       const X86Subtarget *Subtarget) {
22245   SDLoc dl(N);
22246   SDValue Cond = N->getOperand(0);
22247   SDValue LHS = N->getOperand(1);
22248   SDValue RHS = N->getOperand(2);
22249
22250   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22251     SDValue CondSrc = Cond->getOperand(0);
22252     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22253       Cond = CondSrc->getOperand(0);
22254   }
22255
22256   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22257     return SDValue();
22258
22259   // A vselect where all conditions and data are constants can be optimized into
22260   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22261   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22262       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22263     return SDValue();
22264
22265   unsigned MaskValue = 0;
22266   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22267     return SDValue();
22268
22269   MVT VT = N->getSimpleValueType(0);
22270   unsigned NumElems = VT.getVectorNumElements();
22271   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22272   for (unsigned i = 0; i < NumElems; ++i) {
22273     // Be sure we emit undef where we can.
22274     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22275       ShuffleMask[i] = -1;
22276     else
22277       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22278   }
22279
22280   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22281   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22282     return SDValue();
22283   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22284 }
22285
22286 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22287 /// nodes.
22288 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22289                                     TargetLowering::DAGCombinerInfo &DCI,
22290                                     const X86Subtarget *Subtarget) {
22291   SDLoc DL(N);
22292   SDValue Cond = N->getOperand(0);
22293   // Get the LHS/RHS of the select.
22294   SDValue LHS = N->getOperand(1);
22295   SDValue RHS = N->getOperand(2);
22296   EVT VT = LHS.getValueType();
22297   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22298
22299   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22300   // instructions match the semantics of the common C idiom x<y?x:y but not
22301   // x<=y?x:y, because of how they handle negative zero (which can be
22302   // ignored in unsafe-math mode).
22303   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22304   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22305       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22306       (Subtarget->hasSSE2() ||
22307        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22308     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22309
22310     unsigned Opcode = 0;
22311     // Check for x CC y ? x : y.
22312     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22313         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22314       switch (CC) {
22315       default: break;
22316       case ISD::SETULT:
22317         // Converting this to a min would handle NaNs incorrectly, and swapping
22318         // the operands would cause it to handle comparisons between positive
22319         // and negative zero incorrectly.
22320         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22321           if (!DAG.getTarget().Options.UnsafeFPMath &&
22322               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22323             break;
22324           std::swap(LHS, RHS);
22325         }
22326         Opcode = X86ISD::FMIN;
22327         break;
22328       case ISD::SETOLE:
22329         // Converting this to a min would handle comparisons between positive
22330         // and negative zero incorrectly.
22331         if (!DAG.getTarget().Options.UnsafeFPMath &&
22332             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22333           break;
22334         Opcode = X86ISD::FMIN;
22335         break;
22336       case ISD::SETULE:
22337         // Converting this to a min would handle both negative zeros and NaNs
22338         // incorrectly, but we can swap the operands to fix both.
22339         std::swap(LHS, RHS);
22340       case ISD::SETOLT:
22341       case ISD::SETLT:
22342       case ISD::SETLE:
22343         Opcode = X86ISD::FMIN;
22344         break;
22345
22346       case ISD::SETOGE:
22347         // Converting this to a max would handle comparisons between positive
22348         // and negative zero incorrectly.
22349         if (!DAG.getTarget().Options.UnsafeFPMath &&
22350             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22351           break;
22352         Opcode = X86ISD::FMAX;
22353         break;
22354       case ISD::SETUGT:
22355         // Converting this to a max would handle NaNs incorrectly, and swapping
22356         // the operands would cause it to handle comparisons between positive
22357         // and negative zero incorrectly.
22358         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22359           if (!DAG.getTarget().Options.UnsafeFPMath &&
22360               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22361             break;
22362           std::swap(LHS, RHS);
22363         }
22364         Opcode = X86ISD::FMAX;
22365         break;
22366       case ISD::SETUGE:
22367         // Converting this to a max would handle both negative zeros and NaNs
22368         // incorrectly, but we can swap the operands to fix both.
22369         std::swap(LHS, RHS);
22370       case ISD::SETOGT:
22371       case ISD::SETGT:
22372       case ISD::SETGE:
22373         Opcode = X86ISD::FMAX;
22374         break;
22375       }
22376     // Check for x CC y ? y : x -- a min/max with reversed arms.
22377     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22378                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22379       switch (CC) {
22380       default: break;
22381       case ISD::SETOGE:
22382         // Converting this to a min would handle comparisons between positive
22383         // and negative zero incorrectly, and swapping the operands would
22384         // cause it to handle NaNs incorrectly.
22385         if (!DAG.getTarget().Options.UnsafeFPMath &&
22386             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22387           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22388             break;
22389           std::swap(LHS, RHS);
22390         }
22391         Opcode = X86ISD::FMIN;
22392         break;
22393       case ISD::SETUGT:
22394         // Converting this to a min would handle NaNs incorrectly.
22395         if (!DAG.getTarget().Options.UnsafeFPMath &&
22396             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22397           break;
22398         Opcode = X86ISD::FMIN;
22399         break;
22400       case ISD::SETUGE:
22401         // Converting this to a min would handle both negative zeros and NaNs
22402         // incorrectly, but we can swap the operands to fix both.
22403         std::swap(LHS, RHS);
22404       case ISD::SETOGT:
22405       case ISD::SETGT:
22406       case ISD::SETGE:
22407         Opcode = X86ISD::FMIN;
22408         break;
22409
22410       case ISD::SETULT:
22411         // Converting this to a max would handle NaNs incorrectly.
22412         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22413           break;
22414         Opcode = X86ISD::FMAX;
22415         break;
22416       case ISD::SETOLE:
22417         // Converting this to a max would handle comparisons between positive
22418         // and negative zero incorrectly, and swapping the operands would
22419         // cause it to handle NaNs incorrectly.
22420         if (!DAG.getTarget().Options.UnsafeFPMath &&
22421             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22422           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22423             break;
22424           std::swap(LHS, RHS);
22425         }
22426         Opcode = X86ISD::FMAX;
22427         break;
22428       case ISD::SETULE:
22429         // Converting this to a max would handle both negative zeros and NaNs
22430         // incorrectly, but we can swap the operands to fix both.
22431         std::swap(LHS, RHS);
22432       case ISD::SETOLT:
22433       case ISD::SETLT:
22434       case ISD::SETLE:
22435         Opcode = X86ISD::FMAX;
22436         break;
22437       }
22438     }
22439
22440     if (Opcode)
22441       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22442   }
22443
22444   EVT CondVT = Cond.getValueType();
22445   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22446       CondVT.getVectorElementType() == MVT::i1) {
22447     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22448     // lowering on KNL. In this case we convert it to
22449     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22450     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22451     // Since SKX these selects have a proper lowering.
22452     EVT OpVT = LHS.getValueType();
22453     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22454         (OpVT.getVectorElementType() == MVT::i8 ||
22455          OpVT.getVectorElementType() == MVT::i16) &&
22456         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22457       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22458       DCI.AddToWorklist(Cond.getNode());
22459       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22460     }
22461   }
22462   // If this is a select between two integer constants, try to do some
22463   // optimizations.
22464   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22465     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22466       // Don't do this for crazy integer types.
22467       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22468         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22469         // so that TrueC (the true value) is larger than FalseC.
22470         bool NeedsCondInvert = false;
22471
22472         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22473             // Efficiently invertible.
22474             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22475              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22476               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22477           NeedsCondInvert = true;
22478           std::swap(TrueC, FalseC);
22479         }
22480
22481         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22482         if (FalseC->getAPIntValue() == 0 &&
22483             TrueC->getAPIntValue().isPowerOf2()) {
22484           if (NeedsCondInvert) // Invert the condition if needed.
22485             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22486                                DAG.getConstant(1, DL, Cond.getValueType()));
22487
22488           // Zero extend the condition if needed.
22489           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22490
22491           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22492           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22493                              DAG.getConstant(ShAmt, DL, MVT::i8));
22494         }
22495
22496         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22497         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22498           if (NeedsCondInvert) // Invert the condition if needed.
22499             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22500                                DAG.getConstant(1, DL, Cond.getValueType()));
22501
22502           // Zero extend the condition if needed.
22503           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22504                              FalseC->getValueType(0), Cond);
22505           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22506                              SDValue(FalseC, 0));
22507         }
22508
22509         // Optimize cases that will turn into an LEA instruction.  This requires
22510         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22511         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22512           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22513           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22514
22515           bool isFastMultiplier = false;
22516           if (Diff < 10) {
22517             switch ((unsigned char)Diff) {
22518               default: break;
22519               case 1:  // result = add base, cond
22520               case 2:  // result = lea base(    , cond*2)
22521               case 3:  // result = lea base(cond, cond*2)
22522               case 4:  // result = lea base(    , cond*4)
22523               case 5:  // result = lea base(cond, cond*4)
22524               case 8:  // result = lea base(    , cond*8)
22525               case 9:  // result = lea base(cond, cond*8)
22526                 isFastMultiplier = true;
22527                 break;
22528             }
22529           }
22530
22531           if (isFastMultiplier) {
22532             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22533             if (NeedsCondInvert) // Invert the condition if needed.
22534               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22535                                  DAG.getConstant(1, DL, Cond.getValueType()));
22536
22537             // Zero extend the condition if needed.
22538             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22539                                Cond);
22540             // Scale the condition by the difference.
22541             if (Diff != 1)
22542               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22543                                  DAG.getConstant(Diff, DL,
22544                                                  Cond.getValueType()));
22545
22546             // Add the base if non-zero.
22547             if (FalseC->getAPIntValue() != 0)
22548               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22549                                  SDValue(FalseC, 0));
22550             return Cond;
22551           }
22552         }
22553       }
22554   }
22555
22556   // Canonicalize max and min:
22557   // (x > y) ? x : y -> (x >= y) ? x : y
22558   // (x < y) ? x : y -> (x <= y) ? x : y
22559   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22560   // the need for an extra compare
22561   // against zero. e.g.
22562   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22563   // subl   %esi, %edi
22564   // testl  %edi, %edi
22565   // movl   $0, %eax
22566   // cmovgl %edi, %eax
22567   // =>
22568   // xorl   %eax, %eax
22569   // subl   %esi, $edi
22570   // cmovsl %eax, %edi
22571   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22572       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22573       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22574     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22575     switch (CC) {
22576     default: break;
22577     case ISD::SETLT:
22578     case ISD::SETGT: {
22579       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22580       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22581                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22582       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22583     }
22584     }
22585   }
22586
22587   // Early exit check
22588   if (!TLI.isTypeLegal(VT))
22589     return SDValue();
22590
22591   // Match VSELECTs into subs with unsigned saturation.
22592   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22593       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22594       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22595        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22596     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22597
22598     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22599     // left side invert the predicate to simplify logic below.
22600     SDValue Other;
22601     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22602       Other = RHS;
22603       CC = ISD::getSetCCInverse(CC, true);
22604     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22605       Other = LHS;
22606     }
22607
22608     if (Other.getNode() && Other->getNumOperands() == 2 &&
22609         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22610       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22611       SDValue CondRHS = Cond->getOperand(1);
22612
22613       // Look for a general sub with unsigned saturation first.
22614       // x >= y ? x-y : 0 --> subus x, y
22615       // x >  y ? x-y : 0 --> subus x, y
22616       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22617           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22618         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22619
22620       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22621         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22622           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22623             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22624               // If the RHS is a constant we have to reverse the const
22625               // canonicalization.
22626               // x > C-1 ? x+-C : 0 --> subus x, C
22627               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22628                   CondRHSConst->getAPIntValue() ==
22629                       (-OpRHSConst->getAPIntValue() - 1))
22630                 return DAG.getNode(
22631                     X86ISD::SUBUS, DL, VT, OpLHS,
22632                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22633
22634           // Another special case: If C was a sign bit, the sub has been
22635           // canonicalized into a xor.
22636           // FIXME: Would it be better to use computeKnownBits to determine
22637           //        whether it's safe to decanonicalize the xor?
22638           // x s< 0 ? x^C : 0 --> subus x, C
22639           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22640               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22641               OpRHSConst->getAPIntValue().isSignBit())
22642             // Note that we have to rebuild the RHS constant here to ensure we
22643             // don't rely on particular values of undef lanes.
22644             return DAG.getNode(
22645                 X86ISD::SUBUS, DL, VT, OpLHS,
22646                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22647         }
22648     }
22649   }
22650
22651   // Try to match a min/max vector operation.
22652   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22653     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22654     unsigned Opc = ret.first;
22655     bool NeedSplit = ret.second;
22656
22657     if (Opc && NeedSplit) {
22658       unsigned NumElems = VT.getVectorNumElements();
22659       // Extract the LHS vectors
22660       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22661       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22662
22663       // Extract the RHS vectors
22664       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22665       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22666
22667       // Create min/max for each subvector
22668       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22669       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22670
22671       // Merge the result
22672       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22673     } else if (Opc)
22674       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22675   }
22676
22677   // Simplify vector selection if condition value type matches vselect
22678   // operand type
22679   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22680     assert(Cond.getValueType().isVector() &&
22681            "vector select expects a vector selector!");
22682
22683     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22684     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22685
22686     // Try invert the condition if true value is not all 1s and false value
22687     // is not all 0s.
22688     if (!TValIsAllOnes && !FValIsAllZeros &&
22689         // Check if the selector will be produced by CMPP*/PCMP*
22690         Cond.getOpcode() == ISD::SETCC &&
22691         // Check if SETCC has already been promoted
22692         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22693             CondVT) {
22694       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22695       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22696
22697       if (TValIsAllZeros || FValIsAllOnes) {
22698         SDValue CC = Cond.getOperand(2);
22699         ISD::CondCode NewCC =
22700           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22701                                Cond.getOperand(0).getValueType().isInteger());
22702         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22703         std::swap(LHS, RHS);
22704         TValIsAllOnes = FValIsAllOnes;
22705         FValIsAllZeros = TValIsAllZeros;
22706       }
22707     }
22708
22709     if (TValIsAllOnes || FValIsAllZeros) {
22710       SDValue Ret;
22711
22712       if (TValIsAllOnes && FValIsAllZeros)
22713         Ret = Cond;
22714       else if (TValIsAllOnes)
22715         Ret =
22716             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22717       else if (FValIsAllZeros)
22718         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22719                           DAG.getBitcast(CondVT, LHS));
22720
22721       return DAG.getBitcast(VT, Ret);
22722     }
22723   }
22724
22725   // We should generate an X86ISD::BLENDI from a vselect if its argument
22726   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22727   // constants. This specific pattern gets generated when we split a
22728   // selector for a 512 bit vector in a machine without AVX512 (but with
22729   // 256-bit vectors), during legalization:
22730   //
22731   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22732   //
22733   // Iff we find this pattern and the build_vectors are built from
22734   // constants, we translate the vselect into a shuffle_vector that we
22735   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22736   if ((N->getOpcode() == ISD::VSELECT ||
22737        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22738       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22739     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22740     if (Shuffle.getNode())
22741       return Shuffle;
22742   }
22743
22744   // If this is a *dynamic* select (non-constant condition) and we can match
22745   // this node with one of the variable blend instructions, restructure the
22746   // condition so that the blends can use the high bit of each element and use
22747   // SimplifyDemandedBits to simplify the condition operand.
22748   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22749       !DCI.isBeforeLegalize() &&
22750       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22751     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22752
22753     // Don't optimize vector selects that map to mask-registers.
22754     if (BitWidth == 1)
22755       return SDValue();
22756
22757     // We can only handle the cases where VSELECT is directly legal on the
22758     // subtarget. We custom lower VSELECT nodes with constant conditions and
22759     // this makes it hard to see whether a dynamic VSELECT will correctly
22760     // lower, so we both check the operation's status and explicitly handle the
22761     // cases where a *dynamic* blend will fail even though a constant-condition
22762     // blend could be custom lowered.
22763     // FIXME: We should find a better way to handle this class of problems.
22764     // Potentially, we should combine constant-condition vselect nodes
22765     // pre-legalization into shuffles and not mark as many types as custom
22766     // lowered.
22767     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22768       return SDValue();
22769     // FIXME: We don't support i16-element blends currently. We could and
22770     // should support them by making *all* the bits in the condition be set
22771     // rather than just the high bit and using an i8-element blend.
22772     if (VT.getScalarType() == MVT::i16)
22773       return SDValue();
22774     // Dynamic blending was only available from SSE4.1 onward.
22775     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22776       return SDValue();
22777     // Byte blends are only available in AVX2
22778     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22779         !Subtarget->hasAVX2())
22780       return SDValue();
22781
22782     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22783     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22784
22785     APInt KnownZero, KnownOne;
22786     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22787                                           DCI.isBeforeLegalizeOps());
22788     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22789         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22790                                  TLO)) {
22791       // If we changed the computation somewhere in the DAG, this change
22792       // will affect all users of Cond.
22793       // Make sure it is fine and update all the nodes so that we do not
22794       // use the generic VSELECT anymore. Otherwise, we may perform
22795       // wrong optimizations as we messed up with the actual expectation
22796       // for the vector boolean values.
22797       if (Cond != TLO.Old) {
22798         // Check all uses of that condition operand to check whether it will be
22799         // consumed by non-BLEND instructions, which may depend on all bits are
22800         // set properly.
22801         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22802              I != E; ++I)
22803           if (I->getOpcode() != ISD::VSELECT)
22804             // TODO: Add other opcodes eventually lowered into BLEND.
22805             return SDValue();
22806
22807         // Update all the users of the condition, before committing the change,
22808         // so that the VSELECT optimizations that expect the correct vector
22809         // boolean value will not be triggered.
22810         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22811              I != E; ++I)
22812           DAG.ReplaceAllUsesOfValueWith(
22813               SDValue(*I, 0),
22814               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22815                           Cond, I->getOperand(1), I->getOperand(2)));
22816         DCI.CommitTargetLoweringOpt(TLO);
22817         return SDValue();
22818       }
22819       // At this point, only Cond is changed. Change the condition
22820       // just for N to keep the opportunity to optimize all other
22821       // users their own way.
22822       DAG.ReplaceAllUsesOfValueWith(
22823           SDValue(N, 0),
22824           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22825                       TLO.New, N->getOperand(1), N->getOperand(2)));
22826       return SDValue();
22827     }
22828   }
22829
22830   return SDValue();
22831 }
22832
22833 // Check whether a boolean test is testing a boolean value generated by
22834 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22835 // code.
22836 //
22837 // Simplify the following patterns:
22838 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22839 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22840 // to (Op EFLAGS Cond)
22841 //
22842 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22843 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22844 // to (Op EFLAGS !Cond)
22845 //
22846 // where Op could be BRCOND or CMOV.
22847 //
22848 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22849   // Quit if not CMP and SUB with its value result used.
22850   if (Cmp.getOpcode() != X86ISD::CMP &&
22851       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22852       return SDValue();
22853
22854   // Quit if not used as a boolean value.
22855   if (CC != X86::COND_E && CC != X86::COND_NE)
22856     return SDValue();
22857
22858   // Check CMP operands. One of them should be 0 or 1 and the other should be
22859   // an SetCC or extended from it.
22860   SDValue Op1 = Cmp.getOperand(0);
22861   SDValue Op2 = Cmp.getOperand(1);
22862
22863   SDValue SetCC;
22864   const ConstantSDNode* C = nullptr;
22865   bool needOppositeCond = (CC == X86::COND_E);
22866   bool checkAgainstTrue = false; // Is it a comparison against 1?
22867
22868   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22869     SetCC = Op2;
22870   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22871     SetCC = Op1;
22872   else // Quit if all operands are not constants.
22873     return SDValue();
22874
22875   if (C->getZExtValue() == 1) {
22876     needOppositeCond = !needOppositeCond;
22877     checkAgainstTrue = true;
22878   } else if (C->getZExtValue() != 0)
22879     // Quit if the constant is neither 0 or 1.
22880     return SDValue();
22881
22882   bool truncatedToBoolWithAnd = false;
22883   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22884   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22885          SetCC.getOpcode() == ISD::TRUNCATE ||
22886          SetCC.getOpcode() == ISD::AND) {
22887     if (SetCC.getOpcode() == ISD::AND) {
22888       int OpIdx = -1;
22889       ConstantSDNode *CS;
22890       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22891           CS->getZExtValue() == 1)
22892         OpIdx = 1;
22893       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22894           CS->getZExtValue() == 1)
22895         OpIdx = 0;
22896       if (OpIdx == -1)
22897         break;
22898       SetCC = SetCC.getOperand(OpIdx);
22899       truncatedToBoolWithAnd = true;
22900     } else
22901       SetCC = SetCC.getOperand(0);
22902   }
22903
22904   switch (SetCC.getOpcode()) {
22905   case X86ISD::SETCC_CARRY:
22906     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22907     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22908     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22909     // truncated to i1 using 'and'.
22910     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22911       break;
22912     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22913            "Invalid use of SETCC_CARRY!");
22914     // FALL THROUGH
22915   case X86ISD::SETCC:
22916     // Set the condition code or opposite one if necessary.
22917     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22918     if (needOppositeCond)
22919       CC = X86::GetOppositeBranchCondition(CC);
22920     return SetCC.getOperand(1);
22921   case X86ISD::CMOV: {
22922     // Check whether false/true value has canonical one, i.e. 0 or 1.
22923     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22924     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22925     // Quit if true value is not a constant.
22926     if (!TVal)
22927       return SDValue();
22928     // Quit if false value is not a constant.
22929     if (!FVal) {
22930       SDValue Op = SetCC.getOperand(0);
22931       // Skip 'zext' or 'trunc' node.
22932       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22933           Op.getOpcode() == ISD::TRUNCATE)
22934         Op = Op.getOperand(0);
22935       // A special case for rdrand/rdseed, where 0 is set if false cond is
22936       // found.
22937       if ((Op.getOpcode() != X86ISD::RDRAND &&
22938            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22939         return SDValue();
22940     }
22941     // Quit if false value is not the constant 0 or 1.
22942     bool FValIsFalse = true;
22943     if (FVal && FVal->getZExtValue() != 0) {
22944       if (FVal->getZExtValue() != 1)
22945         return SDValue();
22946       // If FVal is 1, opposite cond is needed.
22947       needOppositeCond = !needOppositeCond;
22948       FValIsFalse = false;
22949     }
22950     // Quit if TVal is not the constant opposite of FVal.
22951     if (FValIsFalse && TVal->getZExtValue() != 1)
22952       return SDValue();
22953     if (!FValIsFalse && TVal->getZExtValue() != 0)
22954       return SDValue();
22955     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22956     if (needOppositeCond)
22957       CC = X86::GetOppositeBranchCondition(CC);
22958     return SetCC.getOperand(3);
22959   }
22960   }
22961
22962   return SDValue();
22963 }
22964
22965 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22966 /// Match:
22967 ///   (X86or (X86setcc) (X86setcc))
22968 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22969 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22970                                            X86::CondCode &CC1, SDValue &Flags,
22971                                            bool &isAnd) {
22972   if (Cond->getOpcode() == X86ISD::CMP) {
22973     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22974     if (!CondOp1C || !CondOp1C->isNullValue())
22975       return false;
22976
22977     Cond = Cond->getOperand(0);
22978   }
22979
22980   isAnd = false;
22981
22982   SDValue SetCC0, SetCC1;
22983   switch (Cond->getOpcode()) {
22984   default: return false;
22985   case ISD::AND:
22986   case X86ISD::AND:
22987     isAnd = true;
22988     // fallthru
22989   case ISD::OR:
22990   case X86ISD::OR:
22991     SetCC0 = Cond->getOperand(0);
22992     SetCC1 = Cond->getOperand(1);
22993     break;
22994   };
22995
22996   // Make sure we have SETCC nodes, using the same flags value.
22997   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22998       SetCC1.getOpcode() != X86ISD::SETCC ||
22999       SetCC0->getOperand(1) != SetCC1->getOperand(1))
23000     return false;
23001
23002   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
23003   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
23004   Flags = SetCC0->getOperand(1);
23005   return true;
23006 }
23007
23008 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
23009 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
23010                                   TargetLowering::DAGCombinerInfo &DCI,
23011                                   const X86Subtarget *Subtarget) {
23012   SDLoc DL(N);
23013
23014   // If the flag operand isn't dead, don't touch this CMOV.
23015   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
23016     return SDValue();
23017
23018   SDValue FalseOp = N->getOperand(0);
23019   SDValue TrueOp = N->getOperand(1);
23020   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
23021   SDValue Cond = N->getOperand(3);
23022
23023   if (CC == X86::COND_E || CC == X86::COND_NE) {
23024     switch (Cond.getOpcode()) {
23025     default: break;
23026     case X86ISD::BSR:
23027     case X86ISD::BSF:
23028       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
23029       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
23030         return (CC == X86::COND_E) ? FalseOp : TrueOp;
23031     }
23032   }
23033
23034   SDValue Flags;
23035
23036   Flags = checkBoolTestSetCCCombine(Cond, CC);
23037   if (Flags.getNode() &&
23038       // Extra check as FCMOV only supports a subset of X86 cond.
23039       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
23040     SDValue Ops[] = { FalseOp, TrueOp,
23041                       DAG.getConstant(CC, DL, MVT::i8), Flags };
23042     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23043   }
23044
23045   // If this is a select between two integer constants, try to do some
23046   // optimizations.  Note that the operands are ordered the opposite of SELECT
23047   // operands.
23048   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
23049     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
23050       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
23051       // larger than FalseC (the false value).
23052       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
23053         CC = X86::GetOppositeBranchCondition(CC);
23054         std::swap(TrueC, FalseC);
23055         std::swap(TrueOp, FalseOp);
23056       }
23057
23058       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
23059       // This is efficient for any integer data type (including i8/i16) and
23060       // shift amount.
23061       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
23062         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23063                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23064
23065         // Zero extend the condition if needed.
23066         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
23067
23068         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
23069         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
23070                            DAG.getConstant(ShAmt, DL, MVT::i8));
23071         if (N->getNumValues() == 2)  // Dead flag value?
23072           return DCI.CombineTo(N, Cond, SDValue());
23073         return Cond;
23074       }
23075
23076       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
23077       // for any integer data type, including i8/i16.
23078       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
23079         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23080                            DAG.getConstant(CC, DL, MVT::i8), Cond);
23081
23082         // Zero extend the condition if needed.
23083         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
23084                            FalseC->getValueType(0), Cond);
23085         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23086                            SDValue(FalseC, 0));
23087
23088         if (N->getNumValues() == 2)  // Dead flag value?
23089           return DCI.CombineTo(N, Cond, SDValue());
23090         return Cond;
23091       }
23092
23093       // Optimize cases that will turn into an LEA instruction.  This requires
23094       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23095       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23096         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23097         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23098
23099         bool isFastMultiplier = false;
23100         if (Diff < 10) {
23101           switch ((unsigned char)Diff) {
23102           default: break;
23103           case 1:  // result = add base, cond
23104           case 2:  // result = lea base(    , cond*2)
23105           case 3:  // result = lea base(cond, cond*2)
23106           case 4:  // result = lea base(    , cond*4)
23107           case 5:  // result = lea base(cond, cond*4)
23108           case 8:  // result = lea base(    , cond*8)
23109           case 9:  // result = lea base(cond, cond*8)
23110             isFastMultiplier = true;
23111             break;
23112           }
23113         }
23114
23115         if (isFastMultiplier) {
23116           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23117           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23118                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23119           // Zero extend the condition if needed.
23120           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23121                              Cond);
23122           // Scale the condition by the difference.
23123           if (Diff != 1)
23124             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23125                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23126
23127           // Add the base if non-zero.
23128           if (FalseC->getAPIntValue() != 0)
23129             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23130                                SDValue(FalseC, 0));
23131           if (N->getNumValues() == 2)  // Dead flag value?
23132             return DCI.CombineTo(N, Cond, SDValue());
23133           return Cond;
23134         }
23135       }
23136     }
23137   }
23138
23139   // Handle these cases:
23140   //   (select (x != c), e, c) -> select (x != c), e, x),
23141   //   (select (x == c), c, e) -> select (x == c), x, e)
23142   // where the c is an integer constant, and the "select" is the combination
23143   // of CMOV and CMP.
23144   //
23145   // The rationale for this change is that the conditional-move from a constant
23146   // needs two instructions, however, conditional-move from a register needs
23147   // only one instruction.
23148   //
23149   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23150   //  some instruction-combining opportunities. This opt needs to be
23151   //  postponed as late as possible.
23152   //
23153   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23154     // the DCI.xxxx conditions are provided to postpone the optimization as
23155     // late as possible.
23156
23157     ConstantSDNode *CmpAgainst = nullptr;
23158     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23159         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23160         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23161
23162       if (CC == X86::COND_NE &&
23163           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23164         CC = X86::GetOppositeBranchCondition(CC);
23165         std::swap(TrueOp, FalseOp);
23166       }
23167
23168       if (CC == X86::COND_E &&
23169           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23170         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23171                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23172         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23173       }
23174     }
23175   }
23176
23177   // Fold and/or of setcc's to double CMOV:
23178   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23179   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23180   //
23181   // This combine lets us generate:
23182   //   cmovcc1 (jcc1 if we don't have CMOV)
23183   //   cmovcc2 (same)
23184   // instead of:
23185   //   setcc1
23186   //   setcc2
23187   //   and/or
23188   //   cmovne (jne if we don't have CMOV)
23189   // When we can't use the CMOV instruction, it might increase branch
23190   // mispredicts.
23191   // When we can use CMOV, or when there is no mispredict, this improves
23192   // throughput and reduces register pressure.
23193   //
23194   if (CC == X86::COND_NE) {
23195     SDValue Flags;
23196     X86::CondCode CC0, CC1;
23197     bool isAndSetCC;
23198     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23199       if (isAndSetCC) {
23200         std::swap(FalseOp, TrueOp);
23201         CC0 = X86::GetOppositeBranchCondition(CC0);
23202         CC1 = X86::GetOppositeBranchCondition(CC1);
23203       }
23204
23205       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23206         Flags};
23207       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23208       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23209       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23210       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23211       return CMOV;
23212     }
23213   }
23214
23215   return SDValue();
23216 }
23217
23218 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23219                                                 const X86Subtarget *Subtarget) {
23220   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23221   switch (IntNo) {
23222   default: return SDValue();
23223   // SSE/AVX/AVX2 blend intrinsics.
23224   case Intrinsic::x86_avx2_pblendvb:
23225     // Don't try to simplify this intrinsic if we don't have AVX2.
23226     if (!Subtarget->hasAVX2())
23227       return SDValue();
23228     // FALL-THROUGH
23229   case Intrinsic::x86_avx_blendv_pd_256:
23230   case Intrinsic::x86_avx_blendv_ps_256:
23231     // Don't try to simplify this intrinsic if we don't have AVX.
23232     if (!Subtarget->hasAVX())
23233       return SDValue();
23234     // FALL-THROUGH
23235   case Intrinsic::x86_sse41_blendvps:
23236   case Intrinsic::x86_sse41_blendvpd:
23237   case Intrinsic::x86_sse41_pblendvb: {
23238     SDValue Op0 = N->getOperand(1);
23239     SDValue Op1 = N->getOperand(2);
23240     SDValue Mask = N->getOperand(3);
23241
23242     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23243     if (!Subtarget->hasSSE41())
23244       return SDValue();
23245
23246     // fold (blend A, A, Mask) -> A
23247     if (Op0 == Op1)
23248       return Op0;
23249     // fold (blend A, B, allZeros) -> A
23250     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23251       return Op0;
23252     // fold (blend A, B, allOnes) -> B
23253     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23254       return Op1;
23255
23256     // Simplify the case where the mask is a constant i32 value.
23257     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23258       if (C->isNullValue())
23259         return Op0;
23260       if (C->isAllOnesValue())
23261         return Op1;
23262     }
23263
23264     return SDValue();
23265   }
23266
23267   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23268   case Intrinsic::x86_sse2_psrai_w:
23269   case Intrinsic::x86_sse2_psrai_d:
23270   case Intrinsic::x86_avx2_psrai_w:
23271   case Intrinsic::x86_avx2_psrai_d:
23272   case Intrinsic::x86_sse2_psra_w:
23273   case Intrinsic::x86_sse2_psra_d:
23274   case Intrinsic::x86_avx2_psra_w:
23275   case Intrinsic::x86_avx2_psra_d: {
23276     SDValue Op0 = N->getOperand(1);
23277     SDValue Op1 = N->getOperand(2);
23278     EVT VT = Op0.getValueType();
23279     assert(VT.isVector() && "Expected a vector type!");
23280
23281     if (isa<BuildVectorSDNode>(Op1))
23282       Op1 = Op1.getOperand(0);
23283
23284     if (!isa<ConstantSDNode>(Op1))
23285       return SDValue();
23286
23287     EVT SVT = VT.getVectorElementType();
23288     unsigned SVTBits = SVT.getSizeInBits();
23289
23290     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23291     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23292     uint64_t ShAmt = C.getZExtValue();
23293
23294     // Don't try to convert this shift into a ISD::SRA if the shift
23295     // count is bigger than or equal to the element size.
23296     if (ShAmt >= SVTBits)
23297       return SDValue();
23298
23299     // Trivial case: if the shift count is zero, then fold this
23300     // into the first operand.
23301     if (ShAmt == 0)
23302       return Op0;
23303
23304     // Replace this packed shift intrinsic with a target independent
23305     // shift dag node.
23306     SDLoc DL(N);
23307     SDValue Splat = DAG.getConstant(C, DL, VT);
23308     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23309   }
23310   }
23311 }
23312
23313 /// PerformMulCombine - Optimize a single multiply with constant into two
23314 /// in order to implement it with two cheaper instructions, e.g.
23315 /// LEA + SHL, LEA + LEA.
23316 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23317                                  TargetLowering::DAGCombinerInfo &DCI) {
23318   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23319     return SDValue();
23320
23321   EVT VT = N->getValueType(0);
23322   if (VT != MVT::i64 && VT != MVT::i32)
23323     return SDValue();
23324
23325   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23326   if (!C)
23327     return SDValue();
23328   uint64_t MulAmt = C->getZExtValue();
23329   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23330     return SDValue();
23331
23332   uint64_t MulAmt1 = 0;
23333   uint64_t MulAmt2 = 0;
23334   if ((MulAmt % 9) == 0) {
23335     MulAmt1 = 9;
23336     MulAmt2 = MulAmt / 9;
23337   } else if ((MulAmt % 5) == 0) {
23338     MulAmt1 = 5;
23339     MulAmt2 = MulAmt / 5;
23340   } else if ((MulAmt % 3) == 0) {
23341     MulAmt1 = 3;
23342     MulAmt2 = MulAmt / 3;
23343   }
23344   if (MulAmt2 &&
23345       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23346     SDLoc DL(N);
23347
23348     if (isPowerOf2_64(MulAmt2) &&
23349         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23350       // If second multiplifer is pow2, issue it first. We want the multiply by
23351       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23352       // is an add.
23353       std::swap(MulAmt1, MulAmt2);
23354
23355     SDValue NewMul;
23356     if (isPowerOf2_64(MulAmt1))
23357       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23358                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23359     else
23360       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23361                            DAG.getConstant(MulAmt1, DL, VT));
23362
23363     if (isPowerOf2_64(MulAmt2))
23364       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23365                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23366     else
23367       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23368                            DAG.getConstant(MulAmt2, DL, VT));
23369
23370     // Do not add new nodes to DAG combiner worklist.
23371     DCI.CombineTo(N, NewMul, false);
23372   }
23373   return SDValue();
23374 }
23375
23376 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23377   SDValue N0 = N->getOperand(0);
23378   SDValue N1 = N->getOperand(1);
23379   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23380   EVT VT = N0.getValueType();
23381
23382   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23383   // since the result of setcc_c is all zero's or all ones.
23384   if (VT.isInteger() && !VT.isVector() &&
23385       N1C && N0.getOpcode() == ISD::AND &&
23386       N0.getOperand(1).getOpcode() == ISD::Constant) {
23387     SDValue N00 = N0.getOperand(0);
23388     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23389         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23390           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23391          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23392       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23393       APInt ShAmt = N1C->getAPIntValue();
23394       Mask = Mask.shl(ShAmt);
23395       if (Mask != 0) {
23396         SDLoc DL(N);
23397         return DAG.getNode(ISD::AND, DL, VT,
23398                            N00, DAG.getConstant(Mask, DL, VT));
23399       }
23400     }
23401   }
23402
23403   // Hardware support for vector shifts is sparse which makes us scalarize the
23404   // vector operations in many cases. Also, on sandybridge ADD is faster than
23405   // shl.
23406   // (shl V, 1) -> add V,V
23407   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23408     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23409       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23410       // We shift all of the values by one. In many cases we do not have
23411       // hardware support for this operation. This is better expressed as an ADD
23412       // of two values.
23413       if (N1SplatC->getAPIntValue() == 1)
23414         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23415     }
23416
23417   return SDValue();
23418 }
23419
23420 /// \brief Returns a vector of 0s if the node in input is a vector logical
23421 /// shift by a constant amount which is known to be bigger than or equal
23422 /// to the vector element size in bits.
23423 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23424                                       const X86Subtarget *Subtarget) {
23425   EVT VT = N->getValueType(0);
23426
23427   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23428       (!Subtarget->hasInt256() ||
23429        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23430     return SDValue();
23431
23432   SDValue Amt = N->getOperand(1);
23433   SDLoc DL(N);
23434   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23435     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23436       APInt ShiftAmt = AmtSplat->getAPIntValue();
23437       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23438
23439       // SSE2/AVX2 logical shifts always return a vector of 0s
23440       // if the shift amount is bigger than or equal to
23441       // the element size. The constant shift amount will be
23442       // encoded as a 8-bit immediate.
23443       if (ShiftAmt.trunc(8).uge(MaxAmount))
23444         return getZeroVector(VT, Subtarget, DAG, DL);
23445     }
23446
23447   return SDValue();
23448 }
23449
23450 /// PerformShiftCombine - Combine shifts.
23451 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23452                                    TargetLowering::DAGCombinerInfo &DCI,
23453                                    const X86Subtarget *Subtarget) {
23454   if (N->getOpcode() == ISD::SHL)
23455     if (SDValue V = PerformSHLCombine(N, DAG))
23456       return V;
23457
23458   // Try to fold this logical shift into a zero vector.
23459   if (N->getOpcode() != ISD::SRA)
23460     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23461       return V;
23462
23463   return SDValue();
23464 }
23465
23466 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23467 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23468 // and friends.  Likewise for OR -> CMPNEQSS.
23469 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23470                             TargetLowering::DAGCombinerInfo &DCI,
23471                             const X86Subtarget *Subtarget) {
23472   unsigned opcode;
23473
23474   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23475   // we're requiring SSE2 for both.
23476   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23477     SDValue N0 = N->getOperand(0);
23478     SDValue N1 = N->getOperand(1);
23479     SDValue CMP0 = N0->getOperand(1);
23480     SDValue CMP1 = N1->getOperand(1);
23481     SDLoc DL(N);
23482
23483     // The SETCCs should both refer to the same CMP.
23484     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23485       return SDValue();
23486
23487     SDValue CMP00 = CMP0->getOperand(0);
23488     SDValue CMP01 = CMP0->getOperand(1);
23489     EVT     VT    = CMP00.getValueType();
23490
23491     if (VT == MVT::f32 || VT == MVT::f64) {
23492       bool ExpectingFlags = false;
23493       // Check for any users that want flags:
23494       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23495            !ExpectingFlags && UI != UE; ++UI)
23496         switch (UI->getOpcode()) {
23497         default:
23498         case ISD::BR_CC:
23499         case ISD::BRCOND:
23500         case ISD::SELECT:
23501           ExpectingFlags = true;
23502           break;
23503         case ISD::CopyToReg:
23504         case ISD::SIGN_EXTEND:
23505         case ISD::ZERO_EXTEND:
23506         case ISD::ANY_EXTEND:
23507           break;
23508         }
23509
23510       if (!ExpectingFlags) {
23511         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23512         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23513
23514         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23515           X86::CondCode tmp = cc0;
23516           cc0 = cc1;
23517           cc1 = tmp;
23518         }
23519
23520         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23521             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23522           // FIXME: need symbolic constants for these magic numbers.
23523           // See X86ATTInstPrinter.cpp:printSSECC().
23524           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23525           if (Subtarget->hasAVX512()) {
23526             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23527                                          CMP01,
23528                                          DAG.getConstant(x86cc, DL, MVT::i8));
23529             if (N->getValueType(0) != MVT::i1)
23530               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23531                                  FSetCC);
23532             return FSetCC;
23533           }
23534           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23535                                               CMP00.getValueType(), CMP00, CMP01,
23536                                               DAG.getConstant(x86cc, DL,
23537                                                               MVT::i8));
23538
23539           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23540           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23541
23542           if (is64BitFP && !Subtarget->is64Bit()) {
23543             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23544             // 64-bit integer, since that's not a legal type. Since
23545             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23546             // bits, but can do this little dance to extract the lowest 32 bits
23547             // and work with those going forward.
23548             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23549                                            OnesOrZeroesF);
23550             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23551             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23552                                         Vector32, DAG.getIntPtrConstant(0, DL));
23553             IntVT = MVT::i32;
23554           }
23555
23556           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23557           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23558                                       DAG.getConstant(1, DL, IntVT));
23559           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23560                                               ANDed);
23561           return OneBitOfTruth;
23562         }
23563       }
23564     }
23565   }
23566   return SDValue();
23567 }
23568
23569 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23570 /// so it can be folded inside ANDNP.
23571 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23572   EVT VT = N->getValueType(0);
23573
23574   // Match direct AllOnes for 128 and 256-bit vectors
23575   if (ISD::isBuildVectorAllOnes(N))
23576     return true;
23577
23578   // Look through a bit convert.
23579   if (N->getOpcode() == ISD::BITCAST)
23580     N = N->getOperand(0).getNode();
23581
23582   // Sometimes the operand may come from a insert_subvector building a 256-bit
23583   // allones vector
23584   if (VT.is256BitVector() &&
23585       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23586     SDValue V1 = N->getOperand(0);
23587     SDValue V2 = N->getOperand(1);
23588
23589     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23590         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23591         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23592         ISD::isBuildVectorAllOnes(V2.getNode()))
23593       return true;
23594   }
23595
23596   return false;
23597 }
23598
23599 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23600 // register. In most cases we actually compare or select YMM-sized registers
23601 // and mixing the two types creates horrible code. This method optimizes
23602 // some of the transition sequences.
23603 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23604                                  TargetLowering::DAGCombinerInfo &DCI,
23605                                  const X86Subtarget *Subtarget) {
23606   EVT VT = N->getValueType(0);
23607   if (!VT.is256BitVector())
23608     return SDValue();
23609
23610   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23611           N->getOpcode() == ISD::ZERO_EXTEND ||
23612           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23613
23614   SDValue Narrow = N->getOperand(0);
23615   EVT NarrowVT = Narrow->getValueType(0);
23616   if (!NarrowVT.is128BitVector())
23617     return SDValue();
23618
23619   if (Narrow->getOpcode() != ISD::XOR &&
23620       Narrow->getOpcode() != ISD::AND &&
23621       Narrow->getOpcode() != ISD::OR)
23622     return SDValue();
23623
23624   SDValue N0  = Narrow->getOperand(0);
23625   SDValue N1  = Narrow->getOperand(1);
23626   SDLoc DL(Narrow);
23627
23628   // The Left side has to be a trunc.
23629   if (N0.getOpcode() != ISD::TRUNCATE)
23630     return SDValue();
23631
23632   // The type of the truncated inputs.
23633   EVT WideVT = N0->getOperand(0)->getValueType(0);
23634   if (WideVT != VT)
23635     return SDValue();
23636
23637   // The right side has to be a 'trunc' or a constant vector.
23638   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23639   ConstantSDNode *RHSConstSplat = nullptr;
23640   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23641     RHSConstSplat = RHSBV->getConstantSplatNode();
23642   if (!RHSTrunc && !RHSConstSplat)
23643     return SDValue();
23644
23645   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23646
23647   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23648     return SDValue();
23649
23650   // Set N0 and N1 to hold the inputs to the new wide operation.
23651   N0 = N0->getOperand(0);
23652   if (RHSConstSplat) {
23653     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23654                      SDValue(RHSConstSplat, 0));
23655     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23656     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23657   } else if (RHSTrunc) {
23658     N1 = N1->getOperand(0);
23659   }
23660
23661   // Generate the wide operation.
23662   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23663   unsigned Opcode = N->getOpcode();
23664   switch (Opcode) {
23665   case ISD::ANY_EXTEND:
23666     return Op;
23667   case ISD::ZERO_EXTEND: {
23668     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23669     APInt Mask = APInt::getAllOnesValue(InBits);
23670     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23671     return DAG.getNode(ISD::AND, DL, VT,
23672                        Op, DAG.getConstant(Mask, DL, VT));
23673   }
23674   case ISD::SIGN_EXTEND:
23675     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23676                        Op, DAG.getValueType(NarrowVT));
23677   default:
23678     llvm_unreachable("Unexpected opcode");
23679   }
23680 }
23681
23682 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23683                                  TargetLowering::DAGCombinerInfo &DCI,
23684                                  const X86Subtarget *Subtarget) {
23685   SDValue N0 = N->getOperand(0);
23686   SDValue N1 = N->getOperand(1);
23687   SDLoc DL(N);
23688
23689   // A vector zext_in_reg may be represented as a shuffle,
23690   // feeding into a bitcast (this represents anyext) feeding into
23691   // an and with a mask.
23692   // We'd like to try to combine that into a shuffle with zero
23693   // plus a bitcast, removing the and.
23694   if (N0.getOpcode() != ISD::BITCAST ||
23695       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23696     return SDValue();
23697
23698   // The other side of the AND should be a splat of 2^C, where C
23699   // is the number of bits in the source type.
23700   if (N1.getOpcode() == ISD::BITCAST)
23701     N1 = N1.getOperand(0);
23702   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23703     return SDValue();
23704   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23705
23706   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23707   EVT SrcType = Shuffle->getValueType(0);
23708
23709   // We expect a single-source shuffle
23710   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23711     return SDValue();
23712
23713   unsigned SrcSize = SrcType.getScalarSizeInBits();
23714
23715   APInt SplatValue, SplatUndef;
23716   unsigned SplatBitSize;
23717   bool HasAnyUndefs;
23718   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23719                                 SplatBitSize, HasAnyUndefs))
23720     return SDValue();
23721
23722   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23723   // Make sure the splat matches the mask we expect
23724   if (SplatBitSize > ResSize ||
23725       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23726     return SDValue();
23727
23728   // Make sure the input and output size make sense
23729   if (SrcSize >= ResSize || ResSize % SrcSize)
23730     return SDValue();
23731
23732   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23733   // The number of u's between each two values depends on the ratio between
23734   // the source and dest type.
23735   unsigned ZextRatio = ResSize / SrcSize;
23736   bool IsZext = true;
23737   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23738     if (i % ZextRatio) {
23739       if (Shuffle->getMaskElt(i) > 0) {
23740         // Expected undef
23741         IsZext = false;
23742         break;
23743       }
23744     } else {
23745       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23746         // Expected element number
23747         IsZext = false;
23748         break;
23749       }
23750     }
23751   }
23752
23753   if (!IsZext)
23754     return SDValue();
23755
23756   // Ok, perform the transformation - replace the shuffle with
23757   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23758   // (instead of undef) where the k elements come from the zero vector.
23759   SmallVector<int, 8> Mask;
23760   unsigned NumElems = SrcType.getVectorNumElements();
23761   for (unsigned i = 0; i < NumElems; ++i)
23762     if (i % ZextRatio)
23763       Mask.push_back(NumElems);
23764     else
23765       Mask.push_back(i / ZextRatio);
23766
23767   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23768     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23769   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23770 }
23771
23772 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23773                                  TargetLowering::DAGCombinerInfo &DCI,
23774                                  const X86Subtarget *Subtarget) {
23775   if (DCI.isBeforeLegalizeOps())
23776     return SDValue();
23777
23778   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23779     return Zext;
23780
23781   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23782     return R;
23783
23784   EVT VT = N->getValueType(0);
23785   SDValue N0 = N->getOperand(0);
23786   SDValue N1 = N->getOperand(1);
23787   SDLoc DL(N);
23788
23789   // Create BEXTR instructions
23790   // BEXTR is ((X >> imm) & (2**size-1))
23791   if (VT == MVT::i32 || VT == MVT::i64) {
23792     // Check for BEXTR.
23793     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23794         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23795       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23796       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23797       if (MaskNode && ShiftNode) {
23798         uint64_t Mask = MaskNode->getZExtValue();
23799         uint64_t Shift = ShiftNode->getZExtValue();
23800         if (isMask_64(Mask)) {
23801           uint64_t MaskSize = countPopulation(Mask);
23802           if (Shift + MaskSize <= VT.getSizeInBits())
23803             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23804                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23805                                                VT));
23806         }
23807       }
23808     } // BEXTR
23809
23810     return SDValue();
23811   }
23812
23813   // Want to form ANDNP nodes:
23814   // 1) In the hopes of then easily combining them with OR and AND nodes
23815   //    to form PBLEND/PSIGN.
23816   // 2) To match ANDN packed intrinsics
23817   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23818     return SDValue();
23819
23820   // Check LHS for vnot
23821   if (N0.getOpcode() == ISD::XOR &&
23822       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23823       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23824     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23825
23826   // Check RHS for vnot
23827   if (N1.getOpcode() == ISD::XOR &&
23828       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23829       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23830     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23831
23832   return SDValue();
23833 }
23834
23835 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23836                                 TargetLowering::DAGCombinerInfo &DCI,
23837                                 const X86Subtarget *Subtarget) {
23838   if (DCI.isBeforeLegalizeOps())
23839     return SDValue();
23840
23841   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23842     return R;
23843
23844   SDValue N0 = N->getOperand(0);
23845   SDValue N1 = N->getOperand(1);
23846   EVT VT = N->getValueType(0);
23847
23848   // look for psign/blend
23849   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23850     if (!Subtarget->hasSSSE3() ||
23851         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23852       return SDValue();
23853
23854     // Canonicalize pandn to RHS
23855     if (N0.getOpcode() == X86ISD::ANDNP)
23856       std::swap(N0, N1);
23857     // or (and (m, y), (pandn m, x))
23858     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23859       SDValue Mask = N1.getOperand(0);
23860       SDValue X    = N1.getOperand(1);
23861       SDValue Y;
23862       if (N0.getOperand(0) == Mask)
23863         Y = N0.getOperand(1);
23864       if (N0.getOperand(1) == Mask)
23865         Y = N0.getOperand(0);
23866
23867       // Check to see if the mask appeared in both the AND and ANDNP and
23868       if (!Y.getNode())
23869         return SDValue();
23870
23871       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23872       // Look through mask bitcast.
23873       if (Mask.getOpcode() == ISD::BITCAST)
23874         Mask = Mask.getOperand(0);
23875       if (X.getOpcode() == ISD::BITCAST)
23876         X = X.getOperand(0);
23877       if (Y.getOpcode() == ISD::BITCAST)
23878         Y = Y.getOperand(0);
23879
23880       EVT MaskVT = Mask.getValueType();
23881
23882       // Validate that the Mask operand is a vector sra node.
23883       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23884       // there is no psrai.b
23885       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23886       unsigned SraAmt = ~0;
23887       if (Mask.getOpcode() == ISD::SRA) {
23888         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23889           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23890             SraAmt = AmtConst->getZExtValue();
23891       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23892         SDValue SraC = Mask.getOperand(1);
23893         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23894       }
23895       if ((SraAmt + 1) != EltBits)
23896         return SDValue();
23897
23898       SDLoc DL(N);
23899
23900       // Now we know we at least have a plendvb with the mask val.  See if
23901       // we can form a psignb/w/d.
23902       // psign = x.type == y.type == mask.type && y = sub(0, x);
23903       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23904           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23905           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23906         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23907                "Unsupported VT for PSIGN");
23908         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23909         return DAG.getBitcast(VT, Mask);
23910       }
23911       // PBLENDVB only available on SSE 4.1
23912       if (!Subtarget->hasSSE41())
23913         return SDValue();
23914
23915       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23916
23917       X = DAG.getBitcast(BlendVT, X);
23918       Y = DAG.getBitcast(BlendVT, Y);
23919       Mask = DAG.getBitcast(BlendVT, Mask);
23920       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23921       return DAG.getBitcast(VT, Mask);
23922     }
23923   }
23924
23925   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23926     return SDValue();
23927
23928   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23929   MachineFunction &MF = DAG.getMachineFunction();
23930   bool OptForSize =
23931       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23932
23933   // SHLD/SHRD instructions have lower register pressure, but on some
23934   // platforms they have higher latency than the equivalent
23935   // series of shifts/or that would otherwise be generated.
23936   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23937   // have higher latencies and we are not optimizing for size.
23938   if (!OptForSize && Subtarget->isSHLDSlow())
23939     return SDValue();
23940
23941   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23942     std::swap(N0, N1);
23943   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23944     return SDValue();
23945   if (!N0.hasOneUse() || !N1.hasOneUse())
23946     return SDValue();
23947
23948   SDValue ShAmt0 = N0.getOperand(1);
23949   if (ShAmt0.getValueType() != MVT::i8)
23950     return SDValue();
23951   SDValue ShAmt1 = N1.getOperand(1);
23952   if (ShAmt1.getValueType() != MVT::i8)
23953     return SDValue();
23954   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23955     ShAmt0 = ShAmt0.getOperand(0);
23956   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23957     ShAmt1 = ShAmt1.getOperand(0);
23958
23959   SDLoc DL(N);
23960   unsigned Opc = X86ISD::SHLD;
23961   SDValue Op0 = N0.getOperand(0);
23962   SDValue Op1 = N1.getOperand(0);
23963   if (ShAmt0.getOpcode() == ISD::SUB) {
23964     Opc = X86ISD::SHRD;
23965     std::swap(Op0, Op1);
23966     std::swap(ShAmt0, ShAmt1);
23967   }
23968
23969   unsigned Bits = VT.getSizeInBits();
23970   if (ShAmt1.getOpcode() == ISD::SUB) {
23971     SDValue Sum = ShAmt1.getOperand(0);
23972     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23973       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23974       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23975         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23976       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23977         return DAG.getNode(Opc, DL, VT,
23978                            Op0, Op1,
23979                            DAG.getNode(ISD::TRUNCATE, DL,
23980                                        MVT::i8, ShAmt0));
23981     }
23982   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23983     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23984     if (ShAmt0C &&
23985         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23986       return DAG.getNode(Opc, DL, VT,
23987                          N0.getOperand(0), N1.getOperand(0),
23988                          DAG.getNode(ISD::TRUNCATE, DL,
23989                                        MVT::i8, ShAmt0));
23990   }
23991
23992   return SDValue();
23993 }
23994
23995 // Generate NEG and CMOV for integer abs.
23996 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23997   EVT VT = N->getValueType(0);
23998
23999   // Since X86 does not have CMOV for 8-bit integer, we don't convert
24000   // 8-bit integer abs to NEG and CMOV.
24001   if (VT.isInteger() && VT.getSizeInBits() == 8)
24002     return SDValue();
24003
24004   SDValue N0 = N->getOperand(0);
24005   SDValue N1 = N->getOperand(1);
24006   SDLoc DL(N);
24007
24008   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
24009   // and change it to SUB and CMOV.
24010   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
24011       N0.getOpcode() == ISD::ADD &&
24012       N0.getOperand(1) == N1 &&
24013       N1.getOpcode() == ISD::SRA &&
24014       N1.getOperand(0) == N0.getOperand(0))
24015     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
24016       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
24017         // Generate SUB & CMOV.
24018         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
24019                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
24020
24021         SDValue Ops[] = { N0.getOperand(0), Neg,
24022                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
24023                           SDValue(Neg.getNode(), 1) };
24024         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
24025       }
24026   return SDValue();
24027 }
24028
24029 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
24030 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
24031                                  TargetLowering::DAGCombinerInfo &DCI,
24032                                  const X86Subtarget *Subtarget) {
24033   if (DCI.isBeforeLegalizeOps())
24034     return SDValue();
24035
24036   if (Subtarget->hasCMov())
24037     if (SDValue RV = performIntegerAbsCombine(N, DAG))
24038       return RV;
24039
24040   return SDValue();
24041 }
24042
24043 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
24044 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
24045                                   TargetLowering::DAGCombinerInfo &DCI,
24046                                   const X86Subtarget *Subtarget) {
24047   LoadSDNode *Ld = cast<LoadSDNode>(N);
24048   EVT RegVT = Ld->getValueType(0);
24049   EVT MemVT = Ld->getMemoryVT();
24050   SDLoc dl(Ld);
24051   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24052
24053   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
24054   // into two 16-byte operations.
24055   ISD::LoadExtType Ext = Ld->getExtensionType();
24056   unsigned Alignment = Ld->getAlignment();
24057   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
24058   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24059       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
24060     unsigned NumElems = RegVT.getVectorNumElements();
24061     if (NumElems < 2)
24062       return SDValue();
24063
24064     SDValue Ptr = Ld->getBasePtr();
24065     SDValue Increment =
24066         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24067
24068     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
24069                                   NumElems/2);
24070     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24071                                 Ld->getPointerInfo(), Ld->isVolatile(),
24072                                 Ld->isNonTemporal(), Ld->isInvariant(),
24073                                 Alignment);
24074     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24075     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
24076                                 Ld->getPointerInfo(), Ld->isVolatile(),
24077                                 Ld->isNonTemporal(), Ld->isInvariant(),
24078                                 std::min(16U, Alignment));
24079     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
24080                              Load1.getValue(1),
24081                              Load2.getValue(1));
24082
24083     SDValue NewVec = DAG.getUNDEF(RegVT);
24084     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
24085     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
24086     return DCI.CombineTo(N, NewVec, TF, true);
24087   }
24088
24089   return SDValue();
24090 }
24091
24092 /// PerformMLOADCombine - Resolve extending loads
24093 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24094                                    TargetLowering::DAGCombinerInfo &DCI,
24095                                    const X86Subtarget *Subtarget) {
24096   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24097   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24098     return SDValue();
24099
24100   EVT VT = Mld->getValueType(0);
24101   unsigned NumElems = VT.getVectorNumElements();
24102   EVT LdVT = Mld->getMemoryVT();
24103   SDLoc dl(Mld);
24104
24105   assert(LdVT != VT && "Cannot extend to the same type");
24106   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24107   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24108   // From, To sizes and ElemCount must be pow of two
24109   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24110     "Unexpected size for extending masked load");
24111
24112   unsigned SizeRatio  = ToSz / FromSz;
24113   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24114
24115   // Create a type on which we perform the shuffle
24116   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24117           LdVT.getScalarType(), NumElems*SizeRatio);
24118   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24119
24120   // Convert Src0 value
24121   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24122   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24123     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24124     for (unsigned i = 0; i != NumElems; ++i)
24125       ShuffleVec[i] = i * SizeRatio;
24126
24127     // Can't shuffle using an illegal type.
24128     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24129             && "WideVecVT should be legal");
24130     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24131                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24132   }
24133   // Prepare the new mask
24134   SDValue NewMask;
24135   SDValue Mask = Mld->getMask();
24136   if (Mask.getValueType() == VT) {
24137     // Mask and original value have the same type
24138     NewMask = DAG.getBitcast(WideVecVT, Mask);
24139     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24140     for (unsigned i = 0; i != NumElems; ++i)
24141       ShuffleVec[i] = i * SizeRatio;
24142     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24143       ShuffleVec[i] = NumElems*SizeRatio;
24144     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24145                                    DAG.getConstant(0, dl, WideVecVT),
24146                                    &ShuffleVec[0]);
24147   }
24148   else {
24149     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24150     unsigned WidenNumElts = NumElems*SizeRatio;
24151     unsigned MaskNumElts = VT.getVectorNumElements();
24152     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24153                                      WidenNumElts);
24154
24155     unsigned NumConcat = WidenNumElts / MaskNumElts;
24156     SmallVector<SDValue, 16> Ops(NumConcat);
24157     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24158     Ops[0] = Mask;
24159     for (unsigned i = 1; i != NumConcat; ++i)
24160       Ops[i] = ZeroVal;
24161
24162     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24163   }
24164
24165   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24166                                      Mld->getBasePtr(), NewMask, WideSrc0,
24167                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24168                                      ISD::NON_EXTLOAD);
24169   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24170   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24171
24172 }
24173 /// PerformMSTORECombine - Resolve truncating stores
24174 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24175                                     const X86Subtarget *Subtarget) {
24176   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24177   if (!Mst->isTruncatingStore())
24178     return SDValue();
24179
24180   EVT VT = Mst->getValue().getValueType();
24181   unsigned NumElems = VT.getVectorNumElements();
24182   EVT StVT = Mst->getMemoryVT();
24183   SDLoc dl(Mst);
24184
24185   assert(StVT != VT && "Cannot truncate to the same type");
24186   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24187   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24188
24189   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24190
24191   // The truncating store is legal in some cases. For example
24192   // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24193   // are designated for truncate store.
24194   // In this case we don't need any further transformations.
24195   if (TLI.isTruncStoreLegal(VT, StVT))
24196     return SDValue();
24197
24198   // From, To sizes and ElemCount must be pow of two
24199   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24200     "Unexpected size for truncating masked store");
24201   // We are going to use the original vector elt for storing.
24202   // Accumulated smaller vector elements must be a multiple of the store size.
24203   assert (((NumElems * FromSz) % ToSz) == 0 &&
24204           "Unexpected ratio for truncating masked store");
24205
24206   unsigned SizeRatio  = FromSz / ToSz;
24207   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24208
24209   // Create a type on which we perform the shuffle
24210   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24211           StVT.getScalarType(), NumElems*SizeRatio);
24212
24213   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24214
24215   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24216   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24217   for (unsigned i = 0; i != NumElems; ++i)
24218     ShuffleVec[i] = i * SizeRatio;
24219
24220   // Can't shuffle using an illegal type.
24221   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24222           && "WideVecVT should be legal");
24223
24224   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24225                                         DAG.getUNDEF(WideVecVT),
24226                                         &ShuffleVec[0]);
24227
24228   SDValue NewMask;
24229   SDValue Mask = Mst->getMask();
24230   if (Mask.getValueType() == VT) {
24231     // Mask and original value have the same type
24232     NewMask = DAG.getBitcast(WideVecVT, Mask);
24233     for (unsigned i = 0; i != NumElems; ++i)
24234       ShuffleVec[i] = i * SizeRatio;
24235     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24236       ShuffleVec[i] = NumElems*SizeRatio;
24237     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24238                                    DAG.getConstant(0, dl, WideVecVT),
24239                                    &ShuffleVec[0]);
24240   }
24241   else {
24242     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24243     unsigned WidenNumElts = NumElems*SizeRatio;
24244     unsigned MaskNumElts = VT.getVectorNumElements();
24245     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24246                                      WidenNumElts);
24247
24248     unsigned NumConcat = WidenNumElts / MaskNumElts;
24249     SmallVector<SDValue, 16> Ops(NumConcat);
24250     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24251     Ops[0] = Mask;
24252     for (unsigned i = 1; i != NumConcat; ++i)
24253       Ops[i] = ZeroVal;
24254
24255     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24256   }
24257
24258   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24259                             NewMask, StVT, Mst->getMemOperand(), false);
24260 }
24261 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24262 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24263                                    const X86Subtarget *Subtarget) {
24264   StoreSDNode *St = cast<StoreSDNode>(N);
24265   EVT VT = St->getValue().getValueType();
24266   EVT StVT = St->getMemoryVT();
24267   SDLoc dl(St);
24268   SDValue StoredVal = St->getOperand(1);
24269   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24270
24271   // If we are saving a concatenation of two XMM registers and 32-byte stores
24272   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24273   unsigned Alignment = St->getAlignment();
24274   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24275   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24276       StVT == VT && !IsAligned) {
24277     unsigned NumElems = VT.getVectorNumElements();
24278     if (NumElems < 2)
24279       return SDValue();
24280
24281     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24282     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24283
24284     SDValue Stride =
24285         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24286     SDValue Ptr0 = St->getBasePtr();
24287     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24288
24289     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24290                                 St->getPointerInfo(), St->isVolatile(),
24291                                 St->isNonTemporal(), Alignment);
24292     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24293                                 St->getPointerInfo(), St->isVolatile(),
24294                                 St->isNonTemporal(),
24295                                 std::min(16U, Alignment));
24296     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24297   }
24298
24299   // Optimize trunc store (of multiple scalars) to shuffle and store.
24300   // First, pack all of the elements in one place. Next, store to memory
24301   // in fewer chunks.
24302   if (St->isTruncatingStore() && VT.isVector()) {
24303     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24304     unsigned NumElems = VT.getVectorNumElements();
24305     assert(StVT != VT && "Cannot truncate to the same type");
24306     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24307     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24308
24309     // The truncating store is legal in some cases. For example
24310     // vpmovqb, vpmovqw, vpmovqd, vpmovdb, vpmovdw
24311     // are designated for truncate store.
24312     // In this case we don't need any further transformations.
24313     if (TLI.isTruncStoreLegal(VT, StVT))
24314       return SDValue();
24315
24316     // From, To sizes and ElemCount must be pow of two
24317     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24318     // We are going to use the original vector elt for storing.
24319     // Accumulated smaller vector elements must be a multiple of the store size.
24320     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24321
24322     unsigned SizeRatio  = FromSz / ToSz;
24323
24324     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24325
24326     // Create a type on which we perform the shuffle
24327     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24328             StVT.getScalarType(), NumElems*SizeRatio);
24329
24330     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24331
24332     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24333     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24334     for (unsigned i = 0; i != NumElems; ++i)
24335       ShuffleVec[i] = i * SizeRatio;
24336
24337     // Can't shuffle using an illegal type.
24338     if (!TLI.isTypeLegal(WideVecVT))
24339       return SDValue();
24340
24341     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24342                                          DAG.getUNDEF(WideVecVT),
24343                                          &ShuffleVec[0]);
24344     // At this point all of the data is stored at the bottom of the
24345     // register. We now need to save it to mem.
24346
24347     // Find the largest store unit
24348     MVT StoreType = MVT::i8;
24349     for (MVT Tp : MVT::integer_valuetypes()) {
24350       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24351         StoreType = Tp;
24352     }
24353
24354     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24355     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24356         (64 <= NumElems * ToSz))
24357       StoreType = MVT::f64;
24358
24359     // Bitcast the original vector into a vector of store-size units
24360     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24361             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24362     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24363     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24364     SmallVector<SDValue, 8> Chains;
24365     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24366                                         TLI.getPointerTy(DAG.getDataLayout()));
24367     SDValue Ptr = St->getBasePtr();
24368
24369     // Perform one or more big stores into memory.
24370     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24371       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24372                                    StoreType, ShuffWide,
24373                                    DAG.getIntPtrConstant(i, dl));
24374       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24375                                 St->getPointerInfo(), St->isVolatile(),
24376                                 St->isNonTemporal(), St->getAlignment());
24377       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24378       Chains.push_back(Ch);
24379     }
24380
24381     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24382   }
24383
24384   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24385   // the FP state in cases where an emms may be missing.
24386   // A preferable solution to the general problem is to figure out the right
24387   // places to insert EMMS.  This qualifies as a quick hack.
24388
24389   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24390   if (VT.getSizeInBits() != 64)
24391     return SDValue();
24392
24393   const Function *F = DAG.getMachineFunction().getFunction();
24394   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24395   bool F64IsLegal =
24396       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24397   if ((VT.isVector() ||
24398        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24399       isa<LoadSDNode>(St->getValue()) &&
24400       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24401       St->getChain().hasOneUse() && !St->isVolatile()) {
24402     SDNode* LdVal = St->getValue().getNode();
24403     LoadSDNode *Ld = nullptr;
24404     int TokenFactorIndex = -1;
24405     SmallVector<SDValue, 8> Ops;
24406     SDNode* ChainVal = St->getChain().getNode();
24407     // Must be a store of a load.  We currently handle two cases:  the load
24408     // is a direct child, and it's under an intervening TokenFactor.  It is
24409     // possible to dig deeper under nested TokenFactors.
24410     if (ChainVal == LdVal)
24411       Ld = cast<LoadSDNode>(St->getChain());
24412     else if (St->getValue().hasOneUse() &&
24413              ChainVal->getOpcode() == ISD::TokenFactor) {
24414       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24415         if (ChainVal->getOperand(i).getNode() == LdVal) {
24416           TokenFactorIndex = i;
24417           Ld = cast<LoadSDNode>(St->getValue());
24418         } else
24419           Ops.push_back(ChainVal->getOperand(i));
24420       }
24421     }
24422
24423     if (!Ld || !ISD::isNormalLoad(Ld))
24424       return SDValue();
24425
24426     // If this is not the MMX case, i.e. we are just turning i64 load/store
24427     // into f64 load/store, avoid the transformation if there are multiple
24428     // uses of the loaded value.
24429     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24430       return SDValue();
24431
24432     SDLoc LdDL(Ld);
24433     SDLoc StDL(N);
24434     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24435     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24436     // pair instead.
24437     if (Subtarget->is64Bit() || F64IsLegal) {
24438       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24439       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24440                                   Ld->getPointerInfo(), Ld->isVolatile(),
24441                                   Ld->isNonTemporal(), Ld->isInvariant(),
24442                                   Ld->getAlignment());
24443       SDValue NewChain = NewLd.getValue(1);
24444       if (TokenFactorIndex != -1) {
24445         Ops.push_back(NewChain);
24446         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24447       }
24448       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24449                           St->getPointerInfo(),
24450                           St->isVolatile(), St->isNonTemporal(),
24451                           St->getAlignment());
24452     }
24453
24454     // Otherwise, lower to two pairs of 32-bit loads / stores.
24455     SDValue LoAddr = Ld->getBasePtr();
24456     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24457                                  DAG.getConstant(4, LdDL, MVT::i32));
24458
24459     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24460                                Ld->getPointerInfo(),
24461                                Ld->isVolatile(), Ld->isNonTemporal(),
24462                                Ld->isInvariant(), Ld->getAlignment());
24463     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24464                                Ld->getPointerInfo().getWithOffset(4),
24465                                Ld->isVolatile(), Ld->isNonTemporal(),
24466                                Ld->isInvariant(),
24467                                MinAlign(Ld->getAlignment(), 4));
24468
24469     SDValue NewChain = LoLd.getValue(1);
24470     if (TokenFactorIndex != -1) {
24471       Ops.push_back(LoLd);
24472       Ops.push_back(HiLd);
24473       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24474     }
24475
24476     LoAddr = St->getBasePtr();
24477     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24478                          DAG.getConstant(4, StDL, MVT::i32));
24479
24480     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24481                                 St->getPointerInfo(),
24482                                 St->isVolatile(), St->isNonTemporal(),
24483                                 St->getAlignment());
24484     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24485                                 St->getPointerInfo().getWithOffset(4),
24486                                 St->isVolatile(),
24487                                 St->isNonTemporal(),
24488                                 MinAlign(St->getAlignment(), 4));
24489     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24490   }
24491
24492   // This is similar to the above case, but here we handle a scalar 64-bit
24493   // integer store that is extracted from a vector on a 32-bit target.
24494   // If we have SSE2, then we can treat it like a floating-point double
24495   // to get past legalization. The execution dependencies fixup pass will
24496   // choose the optimal machine instruction for the store if this really is
24497   // an integer or v2f32 rather than an f64.
24498   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24499       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24500     SDValue OldExtract = St->getOperand(1);
24501     SDValue ExtOp0 = OldExtract.getOperand(0);
24502     unsigned VecSize = ExtOp0.getValueSizeInBits();
24503     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24504     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24505     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24506                                      BitCast, OldExtract.getOperand(1));
24507     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24508                         St->getPointerInfo(), St->isVolatile(),
24509                         St->isNonTemporal(), St->getAlignment());
24510   }
24511
24512   return SDValue();
24513 }
24514
24515 /// Return 'true' if this vector operation is "horizontal"
24516 /// and return the operands for the horizontal operation in LHS and RHS.  A
24517 /// horizontal operation performs the binary operation on successive elements
24518 /// of its first operand, then on successive elements of its second operand,
24519 /// returning the resulting values in a vector.  For example, if
24520 ///   A = < float a0, float a1, float a2, float a3 >
24521 /// and
24522 ///   B = < float b0, float b1, float b2, float b3 >
24523 /// then the result of doing a horizontal operation on A and B is
24524 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24525 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24526 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24527 /// set to A, RHS to B, and the routine returns 'true'.
24528 /// Note that the binary operation should have the property that if one of the
24529 /// operands is UNDEF then the result is UNDEF.
24530 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24531   // Look for the following pattern: if
24532   //   A = < float a0, float a1, float a2, float a3 >
24533   //   B = < float b0, float b1, float b2, float b3 >
24534   // and
24535   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24536   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24537   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24538   // which is A horizontal-op B.
24539
24540   // At least one of the operands should be a vector shuffle.
24541   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24542       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24543     return false;
24544
24545   MVT VT = LHS.getSimpleValueType();
24546
24547   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24548          "Unsupported vector type for horizontal add/sub");
24549
24550   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24551   // operate independently on 128-bit lanes.
24552   unsigned NumElts = VT.getVectorNumElements();
24553   unsigned NumLanes = VT.getSizeInBits()/128;
24554   unsigned NumLaneElts = NumElts / NumLanes;
24555   assert((NumLaneElts % 2 == 0) &&
24556          "Vector type should have an even number of elements in each lane");
24557   unsigned HalfLaneElts = NumLaneElts/2;
24558
24559   // View LHS in the form
24560   //   LHS = VECTOR_SHUFFLE A, B, LMask
24561   // If LHS is not a shuffle then pretend it is the shuffle
24562   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24563   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24564   // type VT.
24565   SDValue A, B;
24566   SmallVector<int, 16> LMask(NumElts);
24567   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24568     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24569       A = LHS.getOperand(0);
24570     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24571       B = LHS.getOperand(1);
24572     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24573     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24574   } else {
24575     if (LHS.getOpcode() != ISD::UNDEF)
24576       A = LHS;
24577     for (unsigned i = 0; i != NumElts; ++i)
24578       LMask[i] = i;
24579   }
24580
24581   // Likewise, view RHS in the form
24582   //   RHS = VECTOR_SHUFFLE C, D, RMask
24583   SDValue C, D;
24584   SmallVector<int, 16> RMask(NumElts);
24585   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24586     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24587       C = RHS.getOperand(0);
24588     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24589       D = RHS.getOperand(1);
24590     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24591     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24592   } else {
24593     if (RHS.getOpcode() != ISD::UNDEF)
24594       C = RHS;
24595     for (unsigned i = 0; i != NumElts; ++i)
24596       RMask[i] = i;
24597   }
24598
24599   // Check that the shuffles are both shuffling the same vectors.
24600   if (!(A == C && B == D) && !(A == D && B == C))
24601     return false;
24602
24603   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24604   if (!A.getNode() && !B.getNode())
24605     return false;
24606
24607   // If A and B occur in reverse order in RHS, then "swap" them (which means
24608   // rewriting the mask).
24609   if (A != C)
24610     ShuffleVectorSDNode::commuteMask(RMask);
24611
24612   // At this point LHS and RHS are equivalent to
24613   //   LHS = VECTOR_SHUFFLE A, B, LMask
24614   //   RHS = VECTOR_SHUFFLE A, B, RMask
24615   // Check that the masks correspond to performing a horizontal operation.
24616   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24617     for (unsigned i = 0; i != NumLaneElts; ++i) {
24618       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24619
24620       // Ignore any UNDEF components.
24621       if (LIdx < 0 || RIdx < 0 ||
24622           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24623           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24624         continue;
24625
24626       // Check that successive elements are being operated on.  If not, this is
24627       // not a horizontal operation.
24628       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24629       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24630       if (!(LIdx == Index && RIdx == Index + 1) &&
24631           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24632         return false;
24633     }
24634   }
24635
24636   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24637   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24638   return true;
24639 }
24640
24641 /// Do target-specific dag combines on floating point adds.
24642 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24643                                   const X86Subtarget *Subtarget) {
24644   EVT VT = N->getValueType(0);
24645   SDValue LHS = N->getOperand(0);
24646   SDValue RHS = N->getOperand(1);
24647
24648   // Try to synthesize horizontal adds from adds of shuffles.
24649   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24650        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24651       isHorizontalBinOp(LHS, RHS, true))
24652     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24653   return SDValue();
24654 }
24655
24656 /// Do target-specific dag combines on floating point subs.
24657 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24658                                   const X86Subtarget *Subtarget) {
24659   EVT VT = N->getValueType(0);
24660   SDValue LHS = N->getOperand(0);
24661   SDValue RHS = N->getOperand(1);
24662
24663   // Try to synthesize horizontal subs from subs of shuffles.
24664   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24665        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24666       isHorizontalBinOp(LHS, RHS, false))
24667     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24668   return SDValue();
24669 }
24670
24671 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24672 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24673   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24674
24675   // F[X]OR(0.0, x) -> x
24676   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24677     if (C->getValueAPF().isPosZero())
24678       return N->getOperand(1);
24679
24680   // F[X]OR(x, 0.0) -> x
24681   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24682     if (C->getValueAPF().isPosZero())
24683       return N->getOperand(0);
24684   return SDValue();
24685 }
24686
24687 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24688 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24689   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24690
24691   // Only perform optimizations if UnsafeMath is used.
24692   if (!DAG.getTarget().Options.UnsafeFPMath)
24693     return SDValue();
24694
24695   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24696   // into FMINC and FMAXC, which are Commutative operations.
24697   unsigned NewOp = 0;
24698   switch (N->getOpcode()) {
24699     default: llvm_unreachable("unknown opcode");
24700     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24701     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24702   }
24703
24704   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24705                      N->getOperand(0), N->getOperand(1));
24706 }
24707
24708 /// Do target-specific dag combines on X86ISD::FAND nodes.
24709 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24710   // FAND(0.0, x) -> 0.0
24711   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24712     if (C->getValueAPF().isPosZero())
24713       return N->getOperand(0);
24714
24715   // FAND(x, 0.0) -> 0.0
24716   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24717     if (C->getValueAPF().isPosZero())
24718       return N->getOperand(1);
24719
24720   return SDValue();
24721 }
24722
24723 /// Do target-specific dag combines on X86ISD::FANDN nodes
24724 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24725   // FANDN(0.0, x) -> x
24726   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24727     if (C->getValueAPF().isPosZero())
24728       return N->getOperand(1);
24729
24730   // FANDN(x, 0.0) -> 0.0
24731   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24732     if (C->getValueAPF().isPosZero())
24733       return N->getOperand(1);
24734
24735   return SDValue();
24736 }
24737
24738 static SDValue PerformBTCombine(SDNode *N,
24739                                 SelectionDAG &DAG,
24740                                 TargetLowering::DAGCombinerInfo &DCI) {
24741   // BT ignores high bits in the bit index operand.
24742   SDValue Op1 = N->getOperand(1);
24743   if (Op1.hasOneUse()) {
24744     unsigned BitWidth = Op1.getValueSizeInBits();
24745     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24746     APInt KnownZero, KnownOne;
24747     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24748                                           !DCI.isBeforeLegalizeOps());
24749     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24750     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24751         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24752       DCI.CommitTargetLoweringOpt(TLO);
24753   }
24754   return SDValue();
24755 }
24756
24757 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24758   SDValue Op = N->getOperand(0);
24759   if (Op.getOpcode() == ISD::BITCAST)
24760     Op = Op.getOperand(0);
24761   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24762   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24763       VT.getVectorElementType().getSizeInBits() ==
24764       OpVT.getVectorElementType().getSizeInBits()) {
24765     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24766   }
24767   return SDValue();
24768 }
24769
24770 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24771                                                const X86Subtarget *Subtarget) {
24772   EVT VT = N->getValueType(0);
24773   if (!VT.isVector())
24774     return SDValue();
24775
24776   SDValue N0 = N->getOperand(0);
24777   SDValue N1 = N->getOperand(1);
24778   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24779   SDLoc dl(N);
24780
24781   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24782   // both SSE and AVX2 since there is no sign-extended shift right
24783   // operation on a vector with 64-bit elements.
24784   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24785   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24786   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24787       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24788     SDValue N00 = N0.getOperand(0);
24789
24790     // EXTLOAD has a better solution on AVX2,
24791     // it may be replaced with X86ISD::VSEXT node.
24792     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24793       if (!ISD::isNormalLoad(N00.getNode()))
24794         return SDValue();
24795
24796     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24797         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24798                                   N00, N1);
24799       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24800     }
24801   }
24802   return SDValue();
24803 }
24804
24805 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24806                                   TargetLowering::DAGCombinerInfo &DCI,
24807                                   const X86Subtarget *Subtarget) {
24808   SDValue N0 = N->getOperand(0);
24809   EVT VT = N->getValueType(0);
24810   EVT SVT = VT.getScalarType();
24811   EVT InVT = N0.getValueType();
24812   EVT InSVT = InVT.getScalarType();
24813   SDLoc DL(N);
24814
24815   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24816   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24817   // This exposes the sext to the sdivrem lowering, so that it directly extends
24818   // from AH (which we otherwise need to do contortions to access).
24819   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24820       InVT == MVT::i8 && VT == MVT::i32) {
24821     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24822     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24823                             N0.getOperand(0), N0.getOperand(1));
24824     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24825     return R.getValue(1);
24826   }
24827
24828   if (!DCI.isBeforeLegalizeOps()) {
24829     if (InVT == MVT::i1) {
24830       SDValue Zero = DAG.getConstant(0, DL, VT);
24831       SDValue AllOnes =
24832         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24833       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24834     }
24835     return SDValue();
24836   }
24837
24838   if (VT.isVector() && Subtarget->hasSSE2()) {
24839     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24840       EVT InVT = N.getValueType();
24841       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24842                                    Size / InVT.getScalarSizeInBits());
24843       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24844                                     DAG.getUNDEF(InVT));
24845       Opnds[0] = N;
24846       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24847     };
24848
24849     // If target-size is less than 128-bits, extend to a type that would extend
24850     // to 128 bits, extend that and extract the original target vector.
24851     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24852         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24853         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24854       unsigned Scale = 128 / VT.getSizeInBits();
24855       EVT ExVT =
24856           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24857       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24858       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24859       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24860                          DAG.getIntPtrConstant(0, DL));
24861     }
24862
24863     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24864     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24865     if (VT.getSizeInBits() == 128 &&
24866         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24867         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24868       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24869       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24870     }
24871
24872     // On pre-AVX2 targets, split into 128-bit nodes of
24873     // ISD::SIGN_EXTEND_VECTOR_INREG.
24874     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24875         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24876         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24877       unsigned NumVecs = VT.getSizeInBits() / 128;
24878       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24879       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24880       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24881
24882       SmallVector<SDValue, 8> Opnds;
24883       for (unsigned i = 0, Offset = 0; i != NumVecs;
24884            ++i, Offset += NumSubElts) {
24885         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24886                                      DAG.getIntPtrConstant(Offset, DL));
24887         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24888         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24889         Opnds.push_back(SrcVec);
24890       }
24891       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24892     }
24893   }
24894
24895   if (!Subtarget->hasFp256())
24896     return SDValue();
24897
24898   if (VT.isVector() && VT.getSizeInBits() == 256)
24899     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24900       return R;
24901
24902   return SDValue();
24903 }
24904
24905 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24906                                  const X86Subtarget* Subtarget) {
24907   SDLoc dl(N);
24908   EVT VT = N->getValueType(0);
24909
24910   // Let legalize expand this if it isn't a legal type yet.
24911   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24912     return SDValue();
24913
24914   EVT ScalarVT = VT.getScalarType();
24915   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24916       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24917        !Subtarget->hasAVX512()))
24918     return SDValue();
24919
24920   SDValue A = N->getOperand(0);
24921   SDValue B = N->getOperand(1);
24922   SDValue C = N->getOperand(2);
24923
24924   bool NegA = (A.getOpcode() == ISD::FNEG);
24925   bool NegB = (B.getOpcode() == ISD::FNEG);
24926   bool NegC = (C.getOpcode() == ISD::FNEG);
24927
24928   // Negative multiplication when NegA xor NegB
24929   bool NegMul = (NegA != NegB);
24930   if (NegA)
24931     A = A.getOperand(0);
24932   if (NegB)
24933     B = B.getOperand(0);
24934   if (NegC)
24935     C = C.getOperand(0);
24936
24937   unsigned Opcode;
24938   if (!NegMul)
24939     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24940   else
24941     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24942
24943   return DAG.getNode(Opcode, dl, VT, A, B, C);
24944 }
24945
24946 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24947                                   TargetLowering::DAGCombinerInfo &DCI,
24948                                   const X86Subtarget *Subtarget) {
24949   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24950   //           (and (i32 x86isd::setcc_carry), 1)
24951   // This eliminates the zext. This transformation is necessary because
24952   // ISD::SETCC is always legalized to i8.
24953   SDLoc dl(N);
24954   SDValue N0 = N->getOperand(0);
24955   EVT VT = N->getValueType(0);
24956
24957   if (N0.getOpcode() == ISD::AND &&
24958       N0.hasOneUse() &&
24959       N0.getOperand(0).hasOneUse()) {
24960     SDValue N00 = N0.getOperand(0);
24961     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24962       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24963       if (!C || C->getZExtValue() != 1)
24964         return SDValue();
24965       return DAG.getNode(ISD::AND, dl, VT,
24966                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24967                                      N00.getOperand(0), N00.getOperand(1)),
24968                          DAG.getConstant(1, dl, VT));
24969     }
24970   }
24971
24972   if (N0.getOpcode() == ISD::TRUNCATE &&
24973       N0.hasOneUse() &&
24974       N0.getOperand(0).hasOneUse()) {
24975     SDValue N00 = N0.getOperand(0);
24976     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24977       return DAG.getNode(ISD::AND, dl, VT,
24978                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24979                                      N00.getOperand(0), N00.getOperand(1)),
24980                          DAG.getConstant(1, dl, VT));
24981     }
24982   }
24983
24984   if (VT.is256BitVector())
24985     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24986       return R;
24987
24988   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24989   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24990   // This exposes the zext to the udivrem lowering, so that it directly extends
24991   // from AH (which we otherwise need to do contortions to access).
24992   if (N0.getOpcode() == ISD::UDIVREM &&
24993       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24994       (VT == MVT::i32 || VT == MVT::i64)) {
24995     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24996     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24997                             N0.getOperand(0), N0.getOperand(1));
24998     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24999     return R.getValue(1);
25000   }
25001
25002   return SDValue();
25003 }
25004
25005 // Optimize x == -y --> x+y == 0
25006 //          x != -y --> x+y != 0
25007 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
25008                                       const X86Subtarget* Subtarget) {
25009   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
25010   SDValue LHS = N->getOperand(0);
25011   SDValue RHS = N->getOperand(1);
25012   EVT VT = N->getValueType(0);
25013   SDLoc DL(N);
25014
25015   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
25016     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
25017       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
25018         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
25019                                    LHS.getOperand(1));
25020         return DAG.getSetCC(DL, N->getValueType(0), addV,
25021                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25022       }
25023   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
25024     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
25025       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
25026         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
25027                                    RHS.getOperand(1));
25028         return DAG.getSetCC(DL, N->getValueType(0), addV,
25029                             DAG.getConstant(0, DL, addV.getValueType()), CC);
25030       }
25031
25032   if (VT.getScalarType() == MVT::i1 &&
25033       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
25034     bool IsSEXT0 =
25035         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25036         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25037     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25038
25039     if (!IsSEXT0 || !IsVZero1) {
25040       // Swap the operands and update the condition code.
25041       std::swap(LHS, RHS);
25042       CC = ISD::getSetCCSwappedOperands(CC);
25043
25044       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
25045                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
25046       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
25047     }
25048
25049     if (IsSEXT0 && IsVZero1) {
25050       assert(VT == LHS.getOperand(0).getValueType() &&
25051              "Uexpected operand type");
25052       if (CC == ISD::SETGT)
25053         return DAG.getConstant(0, DL, VT);
25054       if (CC == ISD::SETLE)
25055         return DAG.getConstant(1, DL, VT);
25056       if (CC == ISD::SETEQ || CC == ISD::SETGE)
25057         return DAG.getNOT(DL, LHS.getOperand(0), VT);
25058
25059       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
25060              "Unexpected condition code!");
25061       return LHS.getOperand(0);
25062     }
25063   }
25064
25065   return SDValue();
25066 }
25067
25068 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
25069                                          SelectionDAG &DAG) {
25070   SDLoc dl(Load);
25071   MVT VT = Load->getSimpleValueType(0);
25072   MVT EVT = VT.getVectorElementType();
25073   SDValue Addr = Load->getOperand(1);
25074   SDValue NewAddr = DAG.getNode(
25075       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
25076       DAG.getConstant(Index * EVT.getStoreSize(), dl,
25077                       Addr.getSimpleValueType()));
25078
25079   SDValue NewLoad =
25080       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
25081                   DAG.getMachineFunction().getMachineMemOperand(
25082                       Load->getMemOperand(), 0, EVT.getStoreSize()));
25083   return NewLoad;
25084 }
25085
25086 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
25087                                       const X86Subtarget *Subtarget) {
25088   SDLoc dl(N);
25089   MVT VT = N->getOperand(1)->getSimpleValueType(0);
25090   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
25091          "X86insertps is only defined for v4x32");
25092
25093   SDValue Ld = N->getOperand(1);
25094   if (MayFoldLoad(Ld)) {
25095     // Extract the countS bits from the immediate so we can get the proper
25096     // address when narrowing the vector load to a specific element.
25097     // When the second source op is a memory address, insertps doesn't use
25098     // countS and just gets an f32 from that address.
25099     unsigned DestIndex =
25100         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
25101
25102     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
25103
25104     // Create this as a scalar to vector to match the instruction pattern.
25105     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
25106     // countS bits are ignored when loading from memory on insertps, which
25107     // means we don't need to explicitly set them to 0.
25108     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25109                        LoadScalarToVector, N->getOperand(2));
25110   }
25111   return SDValue();
25112 }
25113
25114 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25115   SDValue V0 = N->getOperand(0);
25116   SDValue V1 = N->getOperand(1);
25117   SDLoc DL(N);
25118   EVT VT = N->getValueType(0);
25119
25120   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25121   // operands and changing the mask to 1. This saves us a bunch of
25122   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25123   // x86InstrInfo knows how to commute this back after instruction selection
25124   // if it would help register allocation.
25125
25126   // TODO: If optimizing for size or a processor that doesn't suffer from
25127   // partial register update stalls, this should be transformed into a MOVSD
25128   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25129
25130   if (VT == MVT::v2f64)
25131     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25132       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25133         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25134         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25135       }
25136
25137   return SDValue();
25138 }
25139
25140 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25141 // as "sbb reg,reg", since it can be extended without zext and produces
25142 // an all-ones bit which is more useful than 0/1 in some cases.
25143 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25144                                MVT VT) {
25145   if (VT == MVT::i8)
25146     return DAG.getNode(ISD::AND, DL, VT,
25147                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25148                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25149                                    EFLAGS),
25150                        DAG.getConstant(1, DL, VT));
25151   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25152   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25153                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25154                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25155                                  EFLAGS));
25156 }
25157
25158 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25159 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25160                                    TargetLowering::DAGCombinerInfo &DCI,
25161                                    const X86Subtarget *Subtarget) {
25162   SDLoc DL(N);
25163   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25164   SDValue EFLAGS = N->getOperand(1);
25165
25166   if (CC == X86::COND_A) {
25167     // Try to convert COND_A into COND_B in an attempt to facilitate
25168     // materializing "setb reg".
25169     //
25170     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25171     // cannot take an immediate as its first operand.
25172     //
25173     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25174         EFLAGS.getValueType().isInteger() &&
25175         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25176       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25177                                    EFLAGS.getNode()->getVTList(),
25178                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25179       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25180       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25181     }
25182   }
25183
25184   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25185   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25186   // cases.
25187   if (CC == X86::COND_B)
25188     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25189
25190   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25191     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25192     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25193   }
25194
25195   return SDValue();
25196 }
25197
25198 // Optimize branch condition evaluation.
25199 //
25200 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25201                                     TargetLowering::DAGCombinerInfo &DCI,
25202                                     const X86Subtarget *Subtarget) {
25203   SDLoc DL(N);
25204   SDValue Chain = N->getOperand(0);
25205   SDValue Dest = N->getOperand(1);
25206   SDValue EFLAGS = N->getOperand(3);
25207   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25208
25209   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25210     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25211     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25212                        Flags);
25213   }
25214
25215   return SDValue();
25216 }
25217
25218 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25219                                                          SelectionDAG &DAG) {
25220   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25221   // optimize away operation when it's from a constant.
25222   //
25223   // The general transformation is:
25224   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25225   //       AND(VECTOR_CMP(x,y), constant2)
25226   //    constant2 = UNARYOP(constant)
25227
25228   // Early exit if this isn't a vector operation, the operand of the
25229   // unary operation isn't a bitwise AND, or if the sizes of the operations
25230   // aren't the same.
25231   EVT VT = N->getValueType(0);
25232   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25233       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25234       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25235     return SDValue();
25236
25237   // Now check that the other operand of the AND is a constant. We could
25238   // make the transformation for non-constant splats as well, but it's unclear
25239   // that would be a benefit as it would not eliminate any operations, just
25240   // perform one more step in scalar code before moving to the vector unit.
25241   if (BuildVectorSDNode *BV =
25242           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25243     // Bail out if the vector isn't a constant.
25244     if (!BV->isConstant())
25245       return SDValue();
25246
25247     // Everything checks out. Build up the new and improved node.
25248     SDLoc DL(N);
25249     EVT IntVT = BV->getValueType(0);
25250     // Create a new constant of the appropriate type for the transformed
25251     // DAG.
25252     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25253     // The AND node needs bitcasts to/from an integer vector type around it.
25254     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25255     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25256                                  N->getOperand(0)->getOperand(0), MaskConst);
25257     SDValue Res = DAG.getBitcast(VT, NewAnd);
25258     return Res;
25259   }
25260
25261   return SDValue();
25262 }
25263
25264 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25265                                         const X86Subtarget *Subtarget) {
25266   SDValue Op0 = N->getOperand(0);
25267   EVT VT = N->getValueType(0);
25268   EVT InVT = Op0.getValueType();
25269   EVT InSVT = InVT.getScalarType();
25270   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25271
25272   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25273   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25274   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25275     SDLoc dl(N);
25276     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25277                                  InVT.getVectorNumElements());
25278     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25279
25280     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25281       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25282
25283     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25284   }
25285
25286   return SDValue();
25287 }
25288
25289 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25290                                         const X86Subtarget *Subtarget) {
25291   // First try to optimize away the conversion entirely when it's
25292   // conditionally from a constant. Vectors only.
25293   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25294     return Res;
25295
25296   // Now move on to more general possibilities.
25297   SDValue Op0 = N->getOperand(0);
25298   EVT VT = N->getValueType(0);
25299   EVT InVT = Op0.getValueType();
25300   EVT InSVT = InVT.getScalarType();
25301
25302   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25303   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25304   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25305     SDLoc dl(N);
25306     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25307                                  InVT.getVectorNumElements());
25308     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25309     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25310   }
25311
25312   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25313   // a 32-bit target where SSE doesn't support i64->FP operations.
25314   if (Op0.getOpcode() == ISD::LOAD) {
25315     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25316     EVT LdVT = Ld->getValueType(0);
25317
25318     // This transformation is not supported if the result type is f16
25319     if (VT == MVT::f16)
25320       return SDValue();
25321
25322     if (!Ld->isVolatile() && !VT.isVector() &&
25323         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25324         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25325       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25326           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25327       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25328       return FILDChain;
25329     }
25330   }
25331   return SDValue();
25332 }
25333
25334 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25335 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25336                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25337   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25338   // the result is either zero or one (depending on the input carry bit).
25339   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25340   if (X86::isZeroNode(N->getOperand(0)) &&
25341       X86::isZeroNode(N->getOperand(1)) &&
25342       // We don't have a good way to replace an EFLAGS use, so only do this when
25343       // dead right now.
25344       SDValue(N, 1).use_empty()) {
25345     SDLoc DL(N);
25346     EVT VT = N->getValueType(0);
25347     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25348     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25349                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25350                                            DAG.getConstant(X86::COND_B, DL,
25351                                                            MVT::i8),
25352                                            N->getOperand(2)),
25353                                DAG.getConstant(1, DL, VT));
25354     return DCI.CombineTo(N, Res1, CarryOut);
25355   }
25356
25357   return SDValue();
25358 }
25359
25360 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25361 //      (add Y, (setne X, 0)) -> sbb -1, Y
25362 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25363 //      (sub (setne X, 0), Y) -> adc -1, Y
25364 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25365   SDLoc DL(N);
25366
25367   // Look through ZExts.
25368   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25369   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25370     return SDValue();
25371
25372   SDValue SetCC = Ext.getOperand(0);
25373   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25374     return SDValue();
25375
25376   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25377   if (CC != X86::COND_E && CC != X86::COND_NE)
25378     return SDValue();
25379
25380   SDValue Cmp = SetCC.getOperand(1);
25381   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25382       !X86::isZeroNode(Cmp.getOperand(1)) ||
25383       !Cmp.getOperand(0).getValueType().isInteger())
25384     return SDValue();
25385
25386   SDValue CmpOp0 = Cmp.getOperand(0);
25387   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25388                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25389
25390   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25391   if (CC == X86::COND_NE)
25392     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25393                        DL, OtherVal.getValueType(), OtherVal,
25394                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25395                        NewCmp);
25396   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25397                      DL, OtherVal.getValueType(), OtherVal,
25398                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25399 }
25400
25401 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25402 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25403                                  const X86Subtarget *Subtarget) {
25404   EVT VT = N->getValueType(0);
25405   SDValue Op0 = N->getOperand(0);
25406   SDValue Op1 = N->getOperand(1);
25407
25408   // Try to synthesize horizontal adds from adds of shuffles.
25409   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25410        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25411       isHorizontalBinOp(Op0, Op1, true))
25412     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25413
25414   return OptimizeConditionalInDecrement(N, DAG);
25415 }
25416
25417 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25418                                  const X86Subtarget *Subtarget) {
25419   SDValue Op0 = N->getOperand(0);
25420   SDValue Op1 = N->getOperand(1);
25421
25422   // X86 can't encode an immediate LHS of a sub. See if we can push the
25423   // negation into a preceding instruction.
25424   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25425     // If the RHS of the sub is a XOR with one use and a constant, invert the
25426     // immediate. Then add one to the LHS of the sub so we can turn
25427     // X-Y -> X+~Y+1, saving one register.
25428     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25429         isa<ConstantSDNode>(Op1.getOperand(1))) {
25430       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25431       EVT VT = Op0.getValueType();
25432       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25433                                    Op1.getOperand(0),
25434                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25435       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25436                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25437     }
25438   }
25439
25440   // Try to synthesize horizontal adds from adds of shuffles.
25441   EVT VT = N->getValueType(0);
25442   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25443        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25444       isHorizontalBinOp(Op0, Op1, true))
25445     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25446
25447   return OptimizeConditionalInDecrement(N, DAG);
25448 }
25449
25450 /// performVZEXTCombine - Performs build vector combines
25451 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25452                                    TargetLowering::DAGCombinerInfo &DCI,
25453                                    const X86Subtarget *Subtarget) {
25454   SDLoc DL(N);
25455   MVT VT = N->getSimpleValueType(0);
25456   SDValue Op = N->getOperand(0);
25457   MVT OpVT = Op.getSimpleValueType();
25458   MVT OpEltVT = OpVT.getVectorElementType();
25459   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25460
25461   // (vzext (bitcast (vzext (x)) -> (vzext x)
25462   SDValue V = Op;
25463   while (V.getOpcode() == ISD::BITCAST)
25464     V = V.getOperand(0);
25465
25466   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25467     MVT InnerVT = V.getSimpleValueType();
25468     MVT InnerEltVT = InnerVT.getVectorElementType();
25469
25470     // If the element sizes match exactly, we can just do one larger vzext. This
25471     // is always an exact type match as vzext operates on integer types.
25472     if (OpEltVT == InnerEltVT) {
25473       assert(OpVT == InnerVT && "Types must match for vzext!");
25474       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25475     }
25476
25477     // The only other way we can combine them is if only a single element of the
25478     // inner vzext is used in the input to the outer vzext.
25479     if (InnerEltVT.getSizeInBits() < InputBits)
25480       return SDValue();
25481
25482     // In this case, the inner vzext is completely dead because we're going to
25483     // only look at bits inside of the low element. Just do the outer vzext on
25484     // a bitcast of the input to the inner.
25485     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25486   }
25487
25488   // Check if we can bypass extracting and re-inserting an element of an input
25489   // vector. Essentialy:
25490   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25491   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25492       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25493       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25494     SDValue ExtractedV = V.getOperand(0);
25495     SDValue OrigV = ExtractedV.getOperand(0);
25496     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25497       if (ExtractIdx->getZExtValue() == 0) {
25498         MVT OrigVT = OrigV.getSimpleValueType();
25499         // Extract a subvector if necessary...
25500         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25501           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25502           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25503                                     OrigVT.getVectorNumElements() / Ratio);
25504           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25505                               DAG.getIntPtrConstant(0, DL));
25506         }
25507         Op = DAG.getBitcast(OpVT, OrigV);
25508         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25509       }
25510   }
25511
25512   return SDValue();
25513 }
25514
25515 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25516                                              DAGCombinerInfo &DCI) const {
25517   SelectionDAG &DAG = DCI.DAG;
25518   switch (N->getOpcode()) {
25519   default: break;
25520   case ISD::EXTRACT_VECTOR_ELT:
25521     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25522   case ISD::VSELECT:
25523   case ISD::SELECT:
25524   case X86ISD::SHRUNKBLEND:
25525     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25526   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25527   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25528   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25529   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25530   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25531   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25532   case ISD::SHL:
25533   case ISD::SRA:
25534   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25535   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25536   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25537   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25538   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25539   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25540   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25541   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25542   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25543   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25544   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25545   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25546   case X86ISD::FXOR:
25547   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25548   case X86ISD::FMIN:
25549   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25550   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25551   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25552   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25553   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25554   case ISD::ANY_EXTEND:
25555   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25556   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25557   case ISD::SIGN_EXTEND_INREG:
25558     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25559   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25560   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25561   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25562   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25563   case X86ISD::SHUFP:       // Handle all target specific shuffles
25564   case X86ISD::PALIGNR:
25565   case X86ISD::UNPCKH:
25566   case X86ISD::UNPCKL:
25567   case X86ISD::MOVHLPS:
25568   case X86ISD::MOVLHPS:
25569   case X86ISD::PSHUFB:
25570   case X86ISD::PSHUFD:
25571   case X86ISD::PSHUFHW:
25572   case X86ISD::PSHUFLW:
25573   case X86ISD::MOVSS:
25574   case X86ISD::MOVSD:
25575   case X86ISD::VPERMILPI:
25576   case X86ISD::VPERM2X128:
25577   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25578   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25579   case ISD::INTRINSIC_WO_CHAIN:
25580     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25581   case X86ISD::INSERTPS: {
25582     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25583       return PerformINSERTPSCombine(N, DAG, Subtarget);
25584     break;
25585   }
25586   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25587   }
25588
25589   return SDValue();
25590 }
25591
25592 /// isTypeDesirableForOp - Return true if the target has native support for
25593 /// the specified value type and it is 'desirable' to use the type for the
25594 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25595 /// instruction encodings are longer and some i16 instructions are slow.
25596 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25597   if (!isTypeLegal(VT))
25598     return false;
25599   if (VT != MVT::i16)
25600     return true;
25601
25602   switch (Opc) {
25603   default:
25604     return true;
25605   case ISD::LOAD:
25606   case ISD::SIGN_EXTEND:
25607   case ISD::ZERO_EXTEND:
25608   case ISD::ANY_EXTEND:
25609   case ISD::SHL:
25610   case ISD::SRL:
25611   case ISD::SUB:
25612   case ISD::ADD:
25613   case ISD::MUL:
25614   case ISD::AND:
25615   case ISD::OR:
25616   case ISD::XOR:
25617     return false;
25618   }
25619 }
25620
25621 /// IsDesirableToPromoteOp - This method query the target whether it is
25622 /// beneficial for dag combiner to promote the specified node. If true, it
25623 /// should return the desired promotion type by reference.
25624 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25625   EVT VT = Op.getValueType();
25626   if (VT != MVT::i16)
25627     return false;
25628
25629   bool Promote = false;
25630   bool Commute = false;
25631   switch (Op.getOpcode()) {
25632   default: break;
25633   case ISD::LOAD: {
25634     LoadSDNode *LD = cast<LoadSDNode>(Op);
25635     // If the non-extending load has a single use and it's not live out, then it
25636     // might be folded.
25637     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25638                                                      Op.hasOneUse()*/) {
25639       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25640              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25641         // The only case where we'd want to promote LOAD (rather then it being
25642         // promoted as an operand is when it's only use is liveout.
25643         if (UI->getOpcode() != ISD::CopyToReg)
25644           return false;
25645       }
25646     }
25647     Promote = true;
25648     break;
25649   }
25650   case ISD::SIGN_EXTEND:
25651   case ISD::ZERO_EXTEND:
25652   case ISD::ANY_EXTEND:
25653     Promote = true;
25654     break;
25655   case ISD::SHL:
25656   case ISD::SRL: {
25657     SDValue N0 = Op.getOperand(0);
25658     // Look out for (store (shl (load), x)).
25659     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25660       return false;
25661     Promote = true;
25662     break;
25663   }
25664   case ISD::ADD:
25665   case ISD::MUL:
25666   case ISD::AND:
25667   case ISD::OR:
25668   case ISD::XOR:
25669     Commute = true;
25670     // fallthrough
25671   case ISD::SUB: {
25672     SDValue N0 = Op.getOperand(0);
25673     SDValue N1 = Op.getOperand(1);
25674     if (!Commute && MayFoldLoad(N1))
25675       return false;
25676     // Avoid disabling potential load folding opportunities.
25677     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25678       return false;
25679     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25680       return false;
25681     Promote = true;
25682   }
25683   }
25684
25685   PVT = MVT::i32;
25686   return Promote;
25687 }
25688
25689 //===----------------------------------------------------------------------===//
25690 //                           X86 Inline Assembly Support
25691 //===----------------------------------------------------------------------===//
25692
25693 // Helper to match a string separated by whitespace.
25694 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25695   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25696
25697   for (StringRef Piece : Pieces) {
25698     if (!S.startswith(Piece)) // Check if the piece matches.
25699       return false;
25700
25701     S = S.substr(Piece.size());
25702     StringRef::size_type Pos = S.find_first_not_of(" \t");
25703     if (Pos == 0) // We matched a prefix.
25704       return false;
25705
25706     S = S.substr(Pos);
25707   }
25708
25709   return S.empty();
25710 }
25711
25712 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25713
25714   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25715     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25716         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25717         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25718
25719       if (AsmPieces.size() == 3)
25720         return true;
25721       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25722         return true;
25723     }
25724   }
25725   return false;
25726 }
25727
25728 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25729   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25730
25731   std::string AsmStr = IA->getAsmString();
25732
25733   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25734   if (!Ty || Ty->getBitWidth() % 16 != 0)
25735     return false;
25736
25737   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25738   SmallVector<StringRef, 4> AsmPieces;
25739   SplitString(AsmStr, AsmPieces, ";\n");
25740
25741   switch (AsmPieces.size()) {
25742   default: return false;
25743   case 1:
25744     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25745     // we will turn this bswap into something that will be lowered to logical
25746     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25747     // lower so don't worry about this.
25748     // bswap $0
25749     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25750         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25751         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25752         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25753         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25754         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25755       // No need to check constraints, nothing other than the equivalent of
25756       // "=r,0" would be valid here.
25757       return IntrinsicLowering::LowerToByteSwap(CI);
25758     }
25759
25760     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25761     if (CI->getType()->isIntegerTy(16) &&
25762         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25763         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25764          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25765       AsmPieces.clear();
25766       StringRef ConstraintsStr = IA->getConstraintString();
25767       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25768       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25769       if (clobbersFlagRegisters(AsmPieces))
25770         return IntrinsicLowering::LowerToByteSwap(CI);
25771     }
25772     break;
25773   case 3:
25774     if (CI->getType()->isIntegerTy(32) &&
25775         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25776         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25777         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25778         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25779       AsmPieces.clear();
25780       StringRef ConstraintsStr = IA->getConstraintString();
25781       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25782       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25783       if (clobbersFlagRegisters(AsmPieces))
25784         return IntrinsicLowering::LowerToByteSwap(CI);
25785     }
25786
25787     if (CI->getType()->isIntegerTy(64)) {
25788       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25789       if (Constraints.size() >= 2 &&
25790           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25791           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25792         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25793         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25794             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25795             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25796           return IntrinsicLowering::LowerToByteSwap(CI);
25797       }
25798     }
25799     break;
25800   }
25801   return false;
25802 }
25803
25804 /// getConstraintType - Given a constraint letter, return the type of
25805 /// constraint it is for this target.
25806 X86TargetLowering::ConstraintType
25807 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25808   if (Constraint.size() == 1) {
25809     switch (Constraint[0]) {
25810     case 'R':
25811     case 'q':
25812     case 'Q':
25813     case 'f':
25814     case 't':
25815     case 'u':
25816     case 'y':
25817     case 'x':
25818     case 'Y':
25819     case 'l':
25820       return C_RegisterClass;
25821     case 'a':
25822     case 'b':
25823     case 'c':
25824     case 'd':
25825     case 'S':
25826     case 'D':
25827     case 'A':
25828       return C_Register;
25829     case 'I':
25830     case 'J':
25831     case 'K':
25832     case 'L':
25833     case 'M':
25834     case 'N':
25835     case 'G':
25836     case 'C':
25837     case 'e':
25838     case 'Z':
25839       return C_Other;
25840     default:
25841       break;
25842     }
25843   }
25844   return TargetLowering::getConstraintType(Constraint);
25845 }
25846
25847 /// Examine constraint type and operand type and determine a weight value.
25848 /// This object must already have been set up with the operand type
25849 /// and the current alternative constraint selected.
25850 TargetLowering::ConstraintWeight
25851   X86TargetLowering::getSingleConstraintMatchWeight(
25852     AsmOperandInfo &info, const char *constraint) const {
25853   ConstraintWeight weight = CW_Invalid;
25854   Value *CallOperandVal = info.CallOperandVal;
25855     // If we don't have a value, we can't do a match,
25856     // but allow it at the lowest weight.
25857   if (!CallOperandVal)
25858     return CW_Default;
25859   Type *type = CallOperandVal->getType();
25860   // Look at the constraint type.
25861   switch (*constraint) {
25862   default:
25863     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25864   case 'R':
25865   case 'q':
25866   case 'Q':
25867   case 'a':
25868   case 'b':
25869   case 'c':
25870   case 'd':
25871   case 'S':
25872   case 'D':
25873   case 'A':
25874     if (CallOperandVal->getType()->isIntegerTy())
25875       weight = CW_SpecificReg;
25876     break;
25877   case 'f':
25878   case 't':
25879   case 'u':
25880     if (type->isFloatingPointTy())
25881       weight = CW_SpecificReg;
25882     break;
25883   case 'y':
25884     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25885       weight = CW_SpecificReg;
25886     break;
25887   case 'x':
25888   case 'Y':
25889     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25890         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25891       weight = CW_Register;
25892     break;
25893   case 'I':
25894     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25895       if (C->getZExtValue() <= 31)
25896         weight = CW_Constant;
25897     }
25898     break;
25899   case 'J':
25900     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25901       if (C->getZExtValue() <= 63)
25902         weight = CW_Constant;
25903     }
25904     break;
25905   case 'K':
25906     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25907       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25908         weight = CW_Constant;
25909     }
25910     break;
25911   case 'L':
25912     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25913       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25914         weight = CW_Constant;
25915     }
25916     break;
25917   case 'M':
25918     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25919       if (C->getZExtValue() <= 3)
25920         weight = CW_Constant;
25921     }
25922     break;
25923   case 'N':
25924     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25925       if (C->getZExtValue() <= 0xff)
25926         weight = CW_Constant;
25927     }
25928     break;
25929   case 'G':
25930   case 'C':
25931     if (isa<ConstantFP>(CallOperandVal)) {
25932       weight = CW_Constant;
25933     }
25934     break;
25935   case 'e':
25936     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25937       if ((C->getSExtValue() >= -0x80000000LL) &&
25938           (C->getSExtValue() <= 0x7fffffffLL))
25939         weight = CW_Constant;
25940     }
25941     break;
25942   case 'Z':
25943     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25944       if (C->getZExtValue() <= 0xffffffff)
25945         weight = CW_Constant;
25946     }
25947     break;
25948   }
25949   return weight;
25950 }
25951
25952 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25953 /// with another that has more specific requirements based on the type of the
25954 /// corresponding operand.
25955 const char *X86TargetLowering::
25956 LowerXConstraint(EVT ConstraintVT) const {
25957   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25958   // 'f' like normal targets.
25959   if (ConstraintVT.isFloatingPoint()) {
25960     if (Subtarget->hasSSE2())
25961       return "Y";
25962     if (Subtarget->hasSSE1())
25963       return "x";
25964   }
25965
25966   return TargetLowering::LowerXConstraint(ConstraintVT);
25967 }
25968
25969 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25970 /// vector.  If it is invalid, don't add anything to Ops.
25971 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25972                                                      std::string &Constraint,
25973                                                      std::vector<SDValue>&Ops,
25974                                                      SelectionDAG &DAG) const {
25975   SDValue Result;
25976
25977   // Only support length 1 constraints for now.
25978   if (Constraint.length() > 1) return;
25979
25980   char ConstraintLetter = Constraint[0];
25981   switch (ConstraintLetter) {
25982   default: break;
25983   case 'I':
25984     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25985       if (C->getZExtValue() <= 31) {
25986         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25987                                        Op.getValueType());
25988         break;
25989       }
25990     }
25991     return;
25992   case 'J':
25993     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25994       if (C->getZExtValue() <= 63) {
25995         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25996                                        Op.getValueType());
25997         break;
25998       }
25999     }
26000     return;
26001   case 'K':
26002     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26003       if (isInt<8>(C->getSExtValue())) {
26004         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26005                                        Op.getValueType());
26006         break;
26007       }
26008     }
26009     return;
26010   case 'L':
26011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26012       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
26013           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
26014         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
26015                                        Op.getValueType());
26016         break;
26017       }
26018     }
26019     return;
26020   case 'M':
26021     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26022       if (C->getZExtValue() <= 3) {
26023         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26024                                        Op.getValueType());
26025         break;
26026       }
26027     }
26028     return;
26029   case 'N':
26030     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26031       if (C->getZExtValue() <= 255) {
26032         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26033                                        Op.getValueType());
26034         break;
26035       }
26036     }
26037     return;
26038   case 'O':
26039     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26040       if (C->getZExtValue() <= 127) {
26041         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26042                                        Op.getValueType());
26043         break;
26044       }
26045     }
26046     return;
26047   case 'e': {
26048     // 32-bit signed value
26049     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26050       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26051                                            C->getSExtValue())) {
26052         // Widen to 64 bits here to get it sign extended.
26053         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
26054         break;
26055       }
26056     // FIXME gcc accepts some relocatable values here too, but only in certain
26057     // memory models; it's complicated.
26058     }
26059     return;
26060   }
26061   case 'Z': {
26062     // 32-bit unsigned value
26063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
26064       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
26065                                            C->getZExtValue())) {
26066         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
26067                                        Op.getValueType());
26068         break;
26069       }
26070     }
26071     // FIXME gcc accepts some relocatable values here too, but only in certain
26072     // memory models; it's complicated.
26073     return;
26074   }
26075   case 'i': {
26076     // Literal immediates are always ok.
26077     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
26078       // Widen to 64 bits here to get it sign extended.
26079       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
26080       break;
26081     }
26082
26083     // In any sort of PIC mode addresses need to be computed at runtime by
26084     // adding in a register or some sort of table lookup.  These can't
26085     // be used as immediates.
26086     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
26087       return;
26088
26089     // If we are in non-pic codegen mode, we allow the address of a global (with
26090     // an optional displacement) to be used with 'i'.
26091     GlobalAddressSDNode *GA = nullptr;
26092     int64_t Offset = 0;
26093
26094     // Match either (GA), (GA+C), (GA+C1+C2), etc.
26095     while (1) {
26096       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
26097         Offset += GA->getOffset();
26098         break;
26099       } else if (Op.getOpcode() == ISD::ADD) {
26100         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26101           Offset += C->getZExtValue();
26102           Op = Op.getOperand(0);
26103           continue;
26104         }
26105       } else if (Op.getOpcode() == ISD::SUB) {
26106         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
26107           Offset += -C->getZExtValue();
26108           Op = Op.getOperand(0);
26109           continue;
26110         }
26111       }
26112
26113       // Otherwise, this isn't something we can handle, reject it.
26114       return;
26115     }
26116
26117     const GlobalValue *GV = GA->getGlobal();
26118     // If we require an extra load to get this address, as in PIC mode, we
26119     // can't accept it.
26120     if (isGlobalStubReference(
26121             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26122       return;
26123
26124     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26125                                         GA->getValueType(0), Offset);
26126     break;
26127   }
26128   }
26129
26130   if (Result.getNode()) {
26131     Ops.push_back(Result);
26132     return;
26133   }
26134   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26135 }
26136
26137 std::pair<unsigned, const TargetRegisterClass *>
26138 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26139                                                 StringRef Constraint,
26140                                                 MVT VT) const {
26141   // First, see if this is a constraint that directly corresponds to an LLVM
26142   // register class.
26143   if (Constraint.size() == 1) {
26144     // GCC Constraint Letters
26145     switch (Constraint[0]) {
26146     default: break;
26147       // TODO: Slight differences here in allocation order and leaving
26148       // RIP in the class. Do they matter any more here than they do
26149       // in the normal allocation?
26150     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26151       if (Subtarget->is64Bit()) {
26152         if (VT == MVT::i32 || VT == MVT::f32)
26153           return std::make_pair(0U, &X86::GR32RegClass);
26154         if (VT == MVT::i16)
26155           return std::make_pair(0U, &X86::GR16RegClass);
26156         if (VT == MVT::i8 || VT == MVT::i1)
26157           return std::make_pair(0U, &X86::GR8RegClass);
26158         if (VT == MVT::i64 || VT == MVT::f64)
26159           return std::make_pair(0U, &X86::GR64RegClass);
26160         break;
26161       }
26162       // 32-bit fallthrough
26163     case 'Q':   // Q_REGS
26164       if (VT == MVT::i32 || VT == MVT::f32)
26165         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26166       if (VT == MVT::i16)
26167         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26168       if (VT == MVT::i8 || VT == MVT::i1)
26169         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26170       if (VT == MVT::i64)
26171         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26172       break;
26173     case 'r':   // GENERAL_REGS
26174     case 'l':   // INDEX_REGS
26175       if (VT == MVT::i8 || VT == MVT::i1)
26176         return std::make_pair(0U, &X86::GR8RegClass);
26177       if (VT == MVT::i16)
26178         return std::make_pair(0U, &X86::GR16RegClass);
26179       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26180         return std::make_pair(0U, &X86::GR32RegClass);
26181       return std::make_pair(0U, &X86::GR64RegClass);
26182     case 'R':   // LEGACY_REGS
26183       if (VT == MVT::i8 || VT == MVT::i1)
26184         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26185       if (VT == MVT::i16)
26186         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26187       if (VT == MVT::i32 || !Subtarget->is64Bit())
26188         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26189       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26190     case 'f':  // FP Stack registers.
26191       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26192       // value to the correct fpstack register class.
26193       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26194         return std::make_pair(0U, &X86::RFP32RegClass);
26195       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26196         return std::make_pair(0U, &X86::RFP64RegClass);
26197       return std::make_pair(0U, &X86::RFP80RegClass);
26198     case 'y':   // MMX_REGS if MMX allowed.
26199       if (!Subtarget->hasMMX()) break;
26200       return std::make_pair(0U, &X86::VR64RegClass);
26201     case 'Y':   // SSE_REGS if SSE2 allowed
26202       if (!Subtarget->hasSSE2()) break;
26203       // FALL THROUGH.
26204     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26205       if (!Subtarget->hasSSE1()) break;
26206
26207       switch (VT.SimpleTy) {
26208       default: break;
26209       // Scalar SSE types.
26210       case MVT::f32:
26211       case MVT::i32:
26212         return std::make_pair(0U, &X86::FR32RegClass);
26213       case MVT::f64:
26214       case MVT::i64:
26215         return std::make_pair(0U, &X86::FR64RegClass);
26216       // Vector types.
26217       case MVT::v16i8:
26218       case MVT::v8i16:
26219       case MVT::v4i32:
26220       case MVT::v2i64:
26221       case MVT::v4f32:
26222       case MVT::v2f64:
26223         return std::make_pair(0U, &X86::VR128RegClass);
26224       // AVX types.
26225       case MVT::v32i8:
26226       case MVT::v16i16:
26227       case MVT::v8i32:
26228       case MVT::v4i64:
26229       case MVT::v8f32:
26230       case MVT::v4f64:
26231         return std::make_pair(0U, &X86::VR256RegClass);
26232       case MVT::v8f64:
26233       case MVT::v16f32:
26234       case MVT::v16i32:
26235       case MVT::v8i64:
26236         return std::make_pair(0U, &X86::VR512RegClass);
26237       }
26238       break;
26239     }
26240   }
26241
26242   // Use the default implementation in TargetLowering to convert the register
26243   // constraint into a member of a register class.
26244   std::pair<unsigned, const TargetRegisterClass*> Res;
26245   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26246
26247   // Not found as a standard register?
26248   if (!Res.second) {
26249     // Map st(0) -> st(7) -> ST0
26250     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26251         tolower(Constraint[1]) == 's' &&
26252         tolower(Constraint[2]) == 't' &&
26253         Constraint[3] == '(' &&
26254         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26255         Constraint[5] == ')' &&
26256         Constraint[6] == '}') {
26257
26258       Res.first = X86::FP0+Constraint[4]-'0';
26259       Res.second = &X86::RFP80RegClass;
26260       return Res;
26261     }
26262
26263     // GCC allows "st(0)" to be called just plain "st".
26264     if (StringRef("{st}").equals_lower(Constraint)) {
26265       Res.first = X86::FP0;
26266       Res.second = &X86::RFP80RegClass;
26267       return Res;
26268     }
26269
26270     // flags -> EFLAGS
26271     if (StringRef("{flags}").equals_lower(Constraint)) {
26272       Res.first = X86::EFLAGS;
26273       Res.second = &X86::CCRRegClass;
26274       return Res;
26275     }
26276
26277     // 'A' means EAX + EDX.
26278     if (Constraint == "A") {
26279       Res.first = X86::EAX;
26280       Res.second = &X86::GR32_ADRegClass;
26281       return Res;
26282     }
26283     return Res;
26284   }
26285
26286   // Otherwise, check to see if this is a register class of the wrong value
26287   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26288   // turn into {ax},{dx}.
26289   // MVT::Other is used to specify clobber names.
26290   if (Res.second->hasType(VT) || VT == MVT::Other)
26291     return Res;   // Correct type already, nothing to do.
26292
26293   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26294   // return "eax". This should even work for things like getting 64bit integer
26295   // registers when given an f64 type.
26296   const TargetRegisterClass *Class = Res.second;
26297   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26298       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26299     unsigned Size = VT.getSizeInBits();
26300     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26301                                   : Size == 16 ? MVT::i16
26302                                   : Size == 32 ? MVT::i32
26303                                   : Size == 64 ? MVT::i64
26304                                   : MVT::Other;
26305     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26306     if (DestReg > 0) {
26307       Res.first = DestReg;
26308       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26309                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26310                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26311                  : &X86::GR64RegClass;
26312       assert(Res.second->contains(Res.first) && "Register in register class");
26313     } else {
26314       // No register found/type mismatch.
26315       Res.first = 0;
26316       Res.second = nullptr;
26317     }
26318   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26319              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26320              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26321              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26322              Class == &X86::VR512RegClass) {
26323     // Handle references to XMM physical registers that got mapped into the
26324     // wrong class.  This can happen with constraints like {xmm0} where the
26325     // target independent register mapper will just pick the first match it can
26326     // find, ignoring the required type.
26327
26328     if (VT == MVT::f32 || VT == MVT::i32)
26329       Res.second = &X86::FR32RegClass;
26330     else if (VT == MVT::f64 || VT == MVT::i64)
26331       Res.second = &X86::FR64RegClass;
26332     else if (X86::VR128RegClass.hasType(VT))
26333       Res.second = &X86::VR128RegClass;
26334     else if (X86::VR256RegClass.hasType(VT))
26335       Res.second = &X86::VR256RegClass;
26336     else if (X86::VR512RegClass.hasType(VT))
26337       Res.second = &X86::VR512RegClass;
26338     else {
26339       // Type mismatch and not a clobber: Return an error;
26340       Res.first = 0;
26341       Res.second = nullptr;
26342     }
26343   }
26344
26345   return Res;
26346 }
26347
26348 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26349                                             const AddrMode &AM, Type *Ty,
26350                                             unsigned AS) const {
26351   // Scaling factors are not free at all.
26352   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26353   // will take 2 allocations in the out of order engine instead of 1
26354   // for plain addressing mode, i.e. inst (reg1).
26355   // E.g.,
26356   // vaddps (%rsi,%drx), %ymm0, %ymm1
26357   // Requires two allocations (one for the load, one for the computation)
26358   // whereas:
26359   // vaddps (%rsi), %ymm0, %ymm1
26360   // Requires just 1 allocation, i.e., freeing allocations for other operations
26361   // and having less micro operations to execute.
26362   //
26363   // For some X86 architectures, this is even worse because for instance for
26364   // stores, the complex addressing mode forces the instruction to use the
26365   // "load" ports instead of the dedicated "store" port.
26366   // E.g., on Haswell:
26367   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26368   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26369   if (isLegalAddressingMode(DL, AM, Ty, AS))
26370     // Scale represents reg2 * scale, thus account for 1
26371     // as soon as we use a second register.
26372     return AM.Scale != 0;
26373   return -1;
26374 }
26375
26376 bool X86TargetLowering::isTargetFTOL() const {
26377   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26378 }