[X86][AVX512] add reduce/range/scalef/rndScale
[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   TD = TM.getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1357
1358       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1359       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1360       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1361       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1362       if (Subtarget->hasVLX()) {
1363         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1364         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1365         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1366         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1367         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1368         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1369         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1370         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1371       }
1372     }
1373     if (Subtarget->hasVLX()) {
1374       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1375       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1376       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1377       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1378       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1379       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1380       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1381       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1382     }
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1386     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1387     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1388     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1389     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1393     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1394     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1395     if (Subtarget->hasDQI()) {
1396       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1397       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1398     }
1399     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1400     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1401     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1402     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1403     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1404     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1405     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1406     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1407     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1408     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1409
1410     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1411     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1412     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1413     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1414     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1415
1416     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1417     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1418
1419     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1420
1421     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1422     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1423     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1424     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1425     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1426     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1427     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1428     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1429     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1430     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1431     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1432
1433     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1434     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1435     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1436     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1437     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1438     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1439     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1440     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1441
1442     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1444
1445     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1446     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1447
1448     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1449
1450     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1451     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1452
1453     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1454     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1455
1456     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1457     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1458
1459     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1461     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1463     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1464     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1465
1466     if (Subtarget->hasCDI()) {
1467       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1468       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1469     }
1470     if (Subtarget->hasDQI()) {
1471       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1472       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1473       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1474     }
1475     // Custom lower several nodes.
1476     for (MVT VT : MVT::vector_valuetypes()) {
1477       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1478       if (EltSize == 1) {
1479         setOperationAction(ISD::AND, VT, Legal);
1480         setOperationAction(ISD::OR,  VT, Legal);
1481         setOperationAction(ISD::XOR,  VT, Legal);
1482       }
1483       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1484         setOperationAction(ISD::MGATHER,  VT, Custom);
1485         setOperationAction(ISD::MSCATTER, VT, Custom);
1486       }
1487       // Extract subvector is special because the value type
1488       // (result) is 256/128-bit but the source is 512-bit wide.
1489       if (VT.is128BitVector() || VT.is256BitVector()) {
1490         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1491       }
1492       if (VT.getVectorElementType() == MVT::i1)
1493         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1494
1495       // Do not attempt to custom lower other non-512-bit vectors
1496       if (!VT.is512BitVector())
1497         continue;
1498
1499       if (EltSize >= 32) {
1500         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1501         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1502         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1503         setOperationAction(ISD::VSELECT,             VT, Legal);
1504         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1505         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1506         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1507         setOperationAction(ISD::MLOAD,               VT, Legal);
1508         setOperationAction(ISD::MSTORE,              VT, Legal);
1509       }
1510     }
1511     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1512       MVT VT = (MVT::SimpleValueType)i;
1513
1514       // Do not attempt to promote non-512-bit vectors.
1515       if (!VT.is512BitVector())
1516         continue;
1517
1518       setOperationAction(ISD::SELECT, VT, Promote);
1519       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1520     }
1521   }// has  AVX-512
1522
1523   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1524     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1525     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1526
1527     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1528     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1529
1530     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1531     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1532     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1533     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1534     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1535     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1536     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1537     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1538     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1539     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1540     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1541     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1542     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1543     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1544     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1545     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1546     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1547     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1548     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1549     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1550     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1551     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1552     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1553     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1554     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1555     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1556     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1557     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1558     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1559
1560     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1561     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1562     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1563     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1564     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1565     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1566     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1567     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1568
1569     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1570       const MVT VT = (MVT::SimpleValueType)i;
1571
1572       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1573
1574       // Do not attempt to promote non-512-bit vectors.
1575       if (!VT.is512BitVector())
1576         continue;
1577
1578       if (EltSize < 32) {
1579         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1580         setOperationAction(ISD::VSELECT,             VT, Legal);
1581       }
1582     }
1583   }
1584
1585   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1586     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1587     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1588
1589     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1590     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1591     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1592     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1593     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1594     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1595     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1596     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1597     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1598     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1599
1600     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1601     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1602     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1603     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1604     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1605     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1606     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1607     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1608
1609     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1610     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1611     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1612     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1613     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1614     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1615     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1616     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1617   }
1618
1619   // We want to custom lower some of our intrinsics.
1620   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1621   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1622   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1623   if (!Subtarget->is64Bit())
1624     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1625
1626   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1627   // handle type legalization for these operations here.
1628   //
1629   // FIXME: We really should do custom legalization for addition and
1630   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1631   // than generic legalization for 64-bit multiplication-with-overflow, though.
1632   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1633     // Add/Sub/Mul with overflow operations are custom lowered.
1634     MVT VT = IntVTs[i];
1635     setOperationAction(ISD::SADDO, VT, Custom);
1636     setOperationAction(ISD::UADDO, VT, Custom);
1637     setOperationAction(ISD::SSUBO, VT, Custom);
1638     setOperationAction(ISD::USUBO, VT, Custom);
1639     setOperationAction(ISD::SMULO, VT, Custom);
1640     setOperationAction(ISD::UMULO, VT, Custom);
1641   }
1642
1643
1644   if (!Subtarget->is64Bit()) {
1645     // These libcalls are not available in 32-bit.
1646     setLibcallName(RTLIB::SHL_I128, nullptr);
1647     setLibcallName(RTLIB::SRL_I128, nullptr);
1648     setLibcallName(RTLIB::SRA_I128, nullptr);
1649   }
1650
1651   // Combine sin / cos into one node or libcall if possible.
1652   if (Subtarget->hasSinCos()) {
1653     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1654     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1655     if (Subtarget->isTargetDarwin()) {
1656       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1657       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1658       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1659       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1660     }
1661   }
1662
1663   if (Subtarget->isTargetWin64()) {
1664     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1665     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1666     setOperationAction(ISD::SREM, MVT::i128, Custom);
1667     setOperationAction(ISD::UREM, MVT::i128, Custom);
1668     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1669     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1670   }
1671
1672   // We have target-specific dag combine patterns for the following nodes:
1673   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1674   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1675   setTargetDAGCombine(ISD::BITCAST);
1676   setTargetDAGCombine(ISD::VSELECT);
1677   setTargetDAGCombine(ISD::SELECT);
1678   setTargetDAGCombine(ISD::SHL);
1679   setTargetDAGCombine(ISD::SRA);
1680   setTargetDAGCombine(ISD::SRL);
1681   setTargetDAGCombine(ISD::OR);
1682   setTargetDAGCombine(ISD::AND);
1683   setTargetDAGCombine(ISD::ADD);
1684   setTargetDAGCombine(ISD::FADD);
1685   setTargetDAGCombine(ISD::FSUB);
1686   setTargetDAGCombine(ISD::FMA);
1687   setTargetDAGCombine(ISD::SUB);
1688   setTargetDAGCombine(ISD::LOAD);
1689   setTargetDAGCombine(ISD::MLOAD);
1690   setTargetDAGCombine(ISD::STORE);
1691   setTargetDAGCombine(ISD::MSTORE);
1692   setTargetDAGCombine(ISD::ZERO_EXTEND);
1693   setTargetDAGCombine(ISD::ANY_EXTEND);
1694   setTargetDAGCombine(ISD::SIGN_EXTEND);
1695   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1696   setTargetDAGCombine(ISD::SINT_TO_FP);
1697   setTargetDAGCombine(ISD::UINT_TO_FP);
1698   setTargetDAGCombine(ISD::SETCC);
1699   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1700   setTargetDAGCombine(ISD::BUILD_VECTOR);
1701   setTargetDAGCombine(ISD::MUL);
1702   setTargetDAGCombine(ISD::XOR);
1703
1704   computeRegisterProperties(Subtarget->getRegisterInfo());
1705
1706   // On Darwin, -Os means optimize for size without hurting performance,
1707   // do not reduce the limit.
1708   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1709   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1710   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1711   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1712   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1713   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1714   setPrefLoopAlignment(4); // 2^4 bytes.
1715
1716   // Predictable cmov don't hurt on atom because it's in-order.
1717   PredictableSelectIsExpensive = !Subtarget->isAtom();
1718   EnableExtLdPromotion = true;
1719   setPrefFunctionAlignment(4); // 2^4 bytes.
1720
1721   verifyIntrinsicTables();
1722 }
1723
1724 // This has so far only been implemented for 64-bit MachO.
1725 bool X86TargetLowering::useLoadStackGuardNode() const {
1726   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1727 }
1728
1729 TargetLoweringBase::LegalizeTypeAction
1730 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1731   if (ExperimentalVectorWideningLegalization &&
1732       VT.getVectorNumElements() != 1 &&
1733       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1734     return TypeWidenVector;
1735
1736   return TargetLoweringBase::getPreferredVectorAction(VT);
1737 }
1738
1739 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1740                                           EVT VT) const {
1741   if (!VT.isVector())
1742     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1743
1744   const unsigned NumElts = VT.getVectorNumElements();
1745   const EVT EltVT = VT.getVectorElementType();
1746   if (VT.is512BitVector()) {
1747     if (Subtarget->hasAVX512())
1748       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1749           EltVT == MVT::f32 || EltVT == MVT::f64)
1750         switch(NumElts) {
1751         case  8: return MVT::v8i1;
1752         case 16: return MVT::v16i1;
1753       }
1754     if (Subtarget->hasBWI())
1755       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1756         switch(NumElts) {
1757         case 32: return MVT::v32i1;
1758         case 64: return MVT::v64i1;
1759       }
1760   }
1761
1762   if (VT.is256BitVector() || VT.is128BitVector()) {
1763     if (Subtarget->hasVLX())
1764       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1765           EltVT == MVT::f32 || EltVT == MVT::f64)
1766         switch(NumElts) {
1767         case 2: return MVT::v2i1;
1768         case 4: return MVT::v4i1;
1769         case 8: return MVT::v8i1;
1770       }
1771     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1772       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1773         switch(NumElts) {
1774         case  8: return MVT::v8i1;
1775         case 16: return MVT::v16i1;
1776         case 32: return MVT::v32i1;
1777       }
1778   }
1779
1780   return VT.changeVectorElementTypeToInteger();
1781 }
1782
1783 /// Helper for getByValTypeAlignment to determine
1784 /// the desired ByVal argument alignment.
1785 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1786   if (MaxAlign == 16)
1787     return;
1788   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1789     if (VTy->getBitWidth() == 128)
1790       MaxAlign = 16;
1791   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1792     unsigned EltAlign = 0;
1793     getMaxByValAlign(ATy->getElementType(), EltAlign);
1794     if (EltAlign > MaxAlign)
1795       MaxAlign = EltAlign;
1796   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1797     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1798       unsigned EltAlign = 0;
1799       getMaxByValAlign(STy->getElementType(i), EltAlign);
1800       if (EltAlign > MaxAlign)
1801         MaxAlign = EltAlign;
1802       if (MaxAlign == 16)
1803         break;
1804     }
1805   }
1806 }
1807
1808 /// Return the desired alignment for ByVal aggregate
1809 /// function arguments in the caller parameter area. For X86, aggregates
1810 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1811 /// are at 4-byte boundaries.
1812 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1813                                                   const DataLayout &DL) const {
1814   if (Subtarget->is64Bit()) {
1815     // Max of 8 and alignment of type.
1816     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1817     if (TyAlign > 8)
1818       return TyAlign;
1819     return 8;
1820   }
1821
1822   unsigned Align = 4;
1823   if (Subtarget->hasSSE1())
1824     getMaxByValAlign(Ty, Align);
1825   return Align;
1826 }
1827
1828 /// Returns the target specific optimal type for load
1829 /// and store operations as a result of memset, memcpy, and memmove
1830 /// lowering. If DstAlign is zero that means it's safe to destination
1831 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1832 /// means there isn't a need to check it against alignment requirement,
1833 /// probably because the source does not need to be loaded. If 'IsMemset' is
1834 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1835 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1836 /// source is constant so it does not need to be loaded.
1837 /// It returns EVT::Other if the type should be determined using generic
1838 /// target-independent logic.
1839 EVT
1840 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1841                                        unsigned DstAlign, unsigned SrcAlign,
1842                                        bool IsMemset, bool ZeroMemset,
1843                                        bool MemcpyStrSrc,
1844                                        MachineFunction &MF) const {
1845   const Function *F = MF.getFunction();
1846   if ((!IsMemset || ZeroMemset) &&
1847       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1848     if (Size >= 16 &&
1849         (Subtarget->isUnalignedMemAccessFast() ||
1850          ((DstAlign == 0 || DstAlign >= 16) &&
1851           (SrcAlign == 0 || SrcAlign >= 16)))) {
1852       if (Size >= 32) {
1853         if (Subtarget->hasInt256())
1854           return MVT::v8i32;
1855         if (Subtarget->hasFp256())
1856           return MVT::v8f32;
1857       }
1858       if (Subtarget->hasSSE2())
1859         return MVT::v4i32;
1860       if (Subtarget->hasSSE1())
1861         return MVT::v4f32;
1862     } else if (!MemcpyStrSrc && Size >= 8 &&
1863                !Subtarget->is64Bit() &&
1864                Subtarget->hasSSE2()) {
1865       // Do not use f64 to lower memcpy if source is string constant. It's
1866       // better to use i32 to avoid the loads.
1867       return MVT::f64;
1868     }
1869   }
1870   if (Subtarget->is64Bit() && Size >= 8)
1871     return MVT::i64;
1872   return MVT::i32;
1873 }
1874
1875 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1876   if (VT == MVT::f32)
1877     return X86ScalarSSEf32;
1878   else if (VT == MVT::f64)
1879     return X86ScalarSSEf64;
1880   return true;
1881 }
1882
1883 bool
1884 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1885                                                   unsigned,
1886                                                   unsigned,
1887                                                   bool *Fast) const {
1888   if (Fast)
1889     *Fast = Subtarget->isUnalignedMemAccessFast();
1890   return true;
1891 }
1892
1893 /// Return the entry encoding for a jump table in the
1894 /// current function.  The returned value is a member of the
1895 /// MachineJumpTableInfo::JTEntryKind enum.
1896 unsigned X86TargetLowering::getJumpTableEncoding() const {
1897   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1898   // symbol.
1899   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1900       Subtarget->isPICStyleGOT())
1901     return MachineJumpTableInfo::EK_Custom32;
1902
1903   // Otherwise, use the normal jump table encoding heuristics.
1904   return TargetLowering::getJumpTableEncoding();
1905 }
1906
1907 bool X86TargetLowering::useSoftFloat() const {
1908   return Subtarget->useSoftFloat();
1909 }
1910
1911 const MCExpr *
1912 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1913                                              const MachineBasicBlock *MBB,
1914                                              unsigned uid,MCContext &Ctx) const{
1915   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1916          Subtarget->isPICStyleGOT());
1917   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1918   // entries.
1919   return MCSymbolRefExpr::create(MBB->getSymbol(),
1920                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1921 }
1922
1923 /// Returns relocation base for the given PIC jumptable.
1924 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1925                                                     SelectionDAG &DAG) const {
1926   if (!Subtarget->is64Bit())
1927     // This doesn't have SDLoc associated with it, but is not really the
1928     // same as a Register.
1929     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1930                        getPointerTy(DAG.getDataLayout()));
1931   return Table;
1932 }
1933
1934 /// This returns the relocation base for the given PIC jumptable,
1935 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1936 const MCExpr *X86TargetLowering::
1937 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1938                              MCContext &Ctx) const {
1939   // X86-64 uses RIP relative addressing based on the jump table label.
1940   if (Subtarget->isPICStyleRIPRel())
1941     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1942
1943   // Otherwise, the reference is relative to the PIC base.
1944   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1945 }
1946
1947 std::pair<const TargetRegisterClass *, uint8_t>
1948 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1949                                            MVT VT) const {
1950   const TargetRegisterClass *RRC = nullptr;
1951   uint8_t Cost = 1;
1952   switch (VT.SimpleTy) {
1953   default:
1954     return TargetLowering::findRepresentativeClass(TRI, VT);
1955   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1956     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1957     break;
1958   case MVT::x86mmx:
1959     RRC = &X86::VR64RegClass;
1960     break;
1961   case MVT::f32: case MVT::f64:
1962   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1963   case MVT::v4f32: case MVT::v2f64:
1964   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1965   case MVT::v4f64:
1966     RRC = &X86::VR128RegClass;
1967     break;
1968   }
1969   return std::make_pair(RRC, Cost);
1970 }
1971
1972 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1973                                                unsigned &Offset) const {
1974   if (!Subtarget->isTargetLinux())
1975     return false;
1976
1977   if (Subtarget->is64Bit()) {
1978     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1979     Offset = 0x28;
1980     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1981       AddressSpace = 256;
1982     else
1983       AddressSpace = 257;
1984   } else {
1985     // %gs:0x14 on i386
1986     Offset = 0x14;
1987     AddressSpace = 256;
1988   }
1989   return true;
1990 }
1991
1992 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1993                                             unsigned DestAS) const {
1994   assert(SrcAS != DestAS && "Expected different address spaces!");
1995
1996   return SrcAS < 256 && DestAS < 256;
1997 }
1998
1999 //===----------------------------------------------------------------------===//
2000 //               Return Value Calling Convention Implementation
2001 //===----------------------------------------------------------------------===//
2002
2003 #include "X86GenCallingConv.inc"
2004
2005 bool
2006 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2007                                   MachineFunction &MF, bool isVarArg,
2008                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2009                         LLVMContext &Context) const {
2010   SmallVector<CCValAssign, 16> RVLocs;
2011   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2012   return CCInfo.CheckReturn(Outs, RetCC_X86);
2013 }
2014
2015 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2016   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2017   return ScratchRegs;
2018 }
2019
2020 SDValue
2021 X86TargetLowering::LowerReturn(SDValue Chain,
2022                                CallingConv::ID CallConv, bool isVarArg,
2023                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2024                                const SmallVectorImpl<SDValue> &OutVals,
2025                                SDLoc dl, SelectionDAG &DAG) const {
2026   MachineFunction &MF = DAG.getMachineFunction();
2027   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2028
2029   SmallVector<CCValAssign, 16> RVLocs;
2030   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2031   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2032
2033   SDValue Flag;
2034   SmallVector<SDValue, 6> RetOps;
2035   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2036   // Operand #1 = Bytes To Pop
2037   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2038                    MVT::i16));
2039
2040   // Copy the result values into the output registers.
2041   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2042     CCValAssign &VA = RVLocs[i];
2043     assert(VA.isRegLoc() && "Can only return in registers!");
2044     SDValue ValToCopy = OutVals[i];
2045     EVT ValVT = ValToCopy.getValueType();
2046
2047     // Promote values to the appropriate types.
2048     if (VA.getLocInfo() == CCValAssign::SExt)
2049       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2050     else if (VA.getLocInfo() == CCValAssign::ZExt)
2051       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2052     else if (VA.getLocInfo() == CCValAssign::AExt) {
2053       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2054         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2055       else
2056         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2057     }
2058     else if (VA.getLocInfo() == CCValAssign::BCvt)
2059       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2060
2061     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2062            "Unexpected FP-extend for return value.");
2063
2064     // If this is x86-64, and we disabled SSE, we can't return FP values,
2065     // or SSE or MMX vectors.
2066     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2067          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2068           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2069       report_fatal_error("SSE register return with SSE disabled");
2070     }
2071     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2072     // llvm-gcc has never done it right and no one has noticed, so this
2073     // should be OK for now.
2074     if (ValVT == MVT::f64 &&
2075         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2076       report_fatal_error("SSE2 register return with SSE2 disabled");
2077
2078     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2079     // the RET instruction and handled by the FP Stackifier.
2080     if (VA.getLocReg() == X86::FP0 ||
2081         VA.getLocReg() == X86::FP1) {
2082       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2083       // change the value to the FP stack register class.
2084       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2085         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2086       RetOps.push_back(ValToCopy);
2087       // Don't emit a copytoreg.
2088       continue;
2089     }
2090
2091     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2092     // which is returned in RAX / RDX.
2093     if (Subtarget->is64Bit()) {
2094       if (ValVT == MVT::x86mmx) {
2095         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2096           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2097           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2098                                   ValToCopy);
2099           // If we don't have SSE2 available, convert to v4f32 so the generated
2100           // register is legal.
2101           if (!Subtarget->hasSSE2())
2102             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2103         }
2104       }
2105     }
2106
2107     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2108     Flag = Chain.getValue(1);
2109     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2110   }
2111
2112   // All x86 ABIs require that for returning structs by value we copy
2113   // the sret argument into %rax/%eax (depending on ABI) for the return.
2114   // We saved the argument into a virtual register in the entry block,
2115   // so now we copy the value out and into %rax/%eax.
2116   //
2117   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2118   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2119   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2120   // either case FuncInfo->setSRetReturnReg() will have been called.
2121   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2122     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2123                                      getPointerTy(MF.getDataLayout()));
2124
2125     unsigned RetValReg
2126         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2127           X86::RAX : X86::EAX;
2128     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2129     Flag = Chain.getValue(1);
2130
2131     // RAX/EAX now acts like a return value.
2132     RetOps.push_back(
2133         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2134   }
2135
2136   RetOps[0] = Chain;  // Update chain.
2137
2138   // Add the flag if we have it.
2139   if (Flag.getNode())
2140     RetOps.push_back(Flag);
2141
2142   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2143 }
2144
2145 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2146   if (N->getNumValues() != 1)
2147     return false;
2148   if (!N->hasNUsesOfValue(1, 0))
2149     return false;
2150
2151   SDValue TCChain = Chain;
2152   SDNode *Copy = *N->use_begin();
2153   if (Copy->getOpcode() == ISD::CopyToReg) {
2154     // If the copy has a glue operand, we conservatively assume it isn't safe to
2155     // perform a tail call.
2156     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2157       return false;
2158     TCChain = Copy->getOperand(0);
2159   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2160     return false;
2161
2162   bool HasRet = false;
2163   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2164        UI != UE; ++UI) {
2165     if (UI->getOpcode() != X86ISD::RET_FLAG)
2166       return false;
2167     // If we are returning more than one value, we can definitely
2168     // not make a tail call see PR19530
2169     if (UI->getNumOperands() > 4)
2170       return false;
2171     if (UI->getNumOperands() == 4 &&
2172         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2173       return false;
2174     HasRet = true;
2175   }
2176
2177   if (!HasRet)
2178     return false;
2179
2180   Chain = TCChain;
2181   return true;
2182 }
2183
2184 EVT
2185 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2186                                             ISD::NodeType ExtendKind) const {
2187   MVT ReturnMVT;
2188   // TODO: Is this also valid on 32-bit?
2189   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2190     ReturnMVT = MVT::i8;
2191   else
2192     ReturnMVT = MVT::i32;
2193
2194   EVT MinVT = getRegisterType(Context, ReturnMVT);
2195   return VT.bitsLT(MinVT) ? MinVT : VT;
2196 }
2197
2198 /// Lower the result values of a call into the
2199 /// appropriate copies out of appropriate physical registers.
2200 ///
2201 SDValue
2202 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2203                                    CallingConv::ID CallConv, bool isVarArg,
2204                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2205                                    SDLoc dl, SelectionDAG &DAG,
2206                                    SmallVectorImpl<SDValue> &InVals) const {
2207
2208   // Assign locations to each value returned by this call.
2209   SmallVector<CCValAssign, 16> RVLocs;
2210   bool Is64Bit = Subtarget->is64Bit();
2211   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2212                  *DAG.getContext());
2213   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2214
2215   // Copy all of the result registers out of their specified physreg.
2216   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2217     CCValAssign &VA = RVLocs[i];
2218     EVT CopyVT = VA.getLocVT();
2219
2220     // If this is x86-64, and we disabled SSE, we can't return FP values
2221     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2222         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2223       report_fatal_error("SSE register return with SSE disabled");
2224     }
2225
2226     // If we prefer to use the value in xmm registers, copy it out as f80 and
2227     // use a truncate to move it from fp stack reg to xmm reg.
2228     bool RoundAfterCopy = false;
2229     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2230         isScalarFPTypeInSSEReg(VA.getValVT())) {
2231       CopyVT = MVT::f80;
2232       RoundAfterCopy = (CopyVT != VA.getLocVT());
2233     }
2234
2235     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2236                                CopyVT, InFlag).getValue(1);
2237     SDValue Val = Chain.getValue(0);
2238
2239     if (RoundAfterCopy)
2240       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2241                         // This truncation won't change the value.
2242                         DAG.getIntPtrConstant(1, dl));
2243
2244     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2245       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2246
2247     InFlag = Chain.getValue(2);
2248     InVals.push_back(Val);
2249   }
2250
2251   return Chain;
2252 }
2253
2254 //===----------------------------------------------------------------------===//
2255 //                C & StdCall & Fast Calling Convention implementation
2256 //===----------------------------------------------------------------------===//
2257 //  StdCall calling convention seems to be standard for many Windows' API
2258 //  routines and around. It differs from C calling convention just a little:
2259 //  callee should clean up the stack, not caller. Symbols should be also
2260 //  decorated in some fancy way :) It doesn't support any vector arguments.
2261 //  For info on fast calling convention see Fast Calling Convention (tail call)
2262 //  implementation LowerX86_32FastCCCallTo.
2263
2264 /// CallIsStructReturn - Determines whether a call uses struct return
2265 /// semantics.
2266 enum StructReturnType {
2267   NotStructReturn,
2268   RegStructReturn,
2269   StackStructReturn
2270 };
2271 static StructReturnType
2272 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2273   if (Outs.empty())
2274     return NotStructReturn;
2275
2276   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2277   if (!Flags.isSRet())
2278     return NotStructReturn;
2279   if (Flags.isInReg())
2280     return RegStructReturn;
2281   return StackStructReturn;
2282 }
2283
2284 /// Determines whether a function uses struct return semantics.
2285 static StructReturnType
2286 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2287   if (Ins.empty())
2288     return NotStructReturn;
2289
2290   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2291   if (!Flags.isSRet())
2292     return NotStructReturn;
2293   if (Flags.isInReg())
2294     return RegStructReturn;
2295   return StackStructReturn;
2296 }
2297
2298 /// Make a copy of an aggregate at address specified by "Src" to address
2299 /// "Dst" with size and alignment information specified by the specific
2300 /// parameter attribute. The copy will be passed as a byval function parameter.
2301 static SDValue
2302 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2303                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2304                           SDLoc dl) {
2305   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2306
2307   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2308                        /*isVolatile*/false, /*AlwaysInline=*/true,
2309                        /*isTailCall*/false,
2310                        MachinePointerInfo(), MachinePointerInfo());
2311 }
2312
2313 /// Return true if the calling convention is one that
2314 /// supports tail call optimization.
2315 static bool IsTailCallConvention(CallingConv::ID CC) {
2316   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2317           CC == CallingConv::HiPE);
2318 }
2319
2320 /// \brief Return true if the calling convention is a C calling convention.
2321 static bool IsCCallConvention(CallingConv::ID CC) {
2322   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2323           CC == CallingConv::X86_64_SysV);
2324 }
2325
2326 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2327   auto Attr =
2328       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2329   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2330     return false;
2331
2332   CallSite CS(CI);
2333   CallingConv::ID CalleeCC = CS.getCallingConv();
2334   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2335     return false;
2336
2337   return true;
2338 }
2339
2340 /// Return true if the function is being made into
2341 /// a tailcall target by changing its ABI.
2342 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2343                                    bool GuaranteedTailCallOpt) {
2344   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2345 }
2346
2347 SDValue
2348 X86TargetLowering::LowerMemArgument(SDValue Chain,
2349                                     CallingConv::ID CallConv,
2350                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2351                                     SDLoc dl, SelectionDAG &DAG,
2352                                     const CCValAssign &VA,
2353                                     MachineFrameInfo *MFI,
2354                                     unsigned i) const {
2355   // Create the nodes corresponding to a load from this parameter slot.
2356   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2357   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2358       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2359   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2360   EVT ValVT;
2361
2362   // If value is passed by pointer we have address passed instead of the value
2363   // itself.
2364   bool ExtendedInMem = VA.isExtInLoc() &&
2365     VA.getValVT().getScalarType() == MVT::i1;
2366
2367   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2368     ValVT = VA.getLocVT();
2369   else
2370     ValVT = VA.getValVT();
2371
2372   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2373   // changed with more analysis.
2374   // In case of tail call optimization mark all arguments mutable. Since they
2375   // could be overwritten by lowering of arguments in case of a tail call.
2376   if (Flags.isByVal()) {
2377     unsigned Bytes = Flags.getByValSize();
2378     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2379     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2380     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2381   } else {
2382     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2383                                     VA.getLocMemOffset(), isImmutable);
2384     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2385     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2386                                MachinePointerInfo::getFixedStack(FI),
2387                                false, false, false, 0);
2388     return ExtendedInMem ?
2389       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2390   }
2391 }
2392
2393 // FIXME: Get this from tablegen.
2394 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2395                                                 const X86Subtarget *Subtarget) {
2396   assert(Subtarget->is64Bit());
2397
2398   if (Subtarget->isCallingConvWin64(CallConv)) {
2399     static const MCPhysReg GPR64ArgRegsWin64[] = {
2400       X86::RCX, X86::RDX, X86::R8,  X86::R9
2401     };
2402     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2403   }
2404
2405   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2406     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2407   };
2408   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2409 }
2410
2411 // FIXME: Get this from tablegen.
2412 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2413                                                 CallingConv::ID CallConv,
2414                                                 const X86Subtarget *Subtarget) {
2415   assert(Subtarget->is64Bit());
2416   if (Subtarget->isCallingConvWin64(CallConv)) {
2417     // The XMM registers which might contain var arg parameters are shadowed
2418     // in their paired GPR.  So we only need to save the GPR to their home
2419     // slots.
2420     // TODO: __vectorcall will change this.
2421     return None;
2422   }
2423
2424   const Function *Fn = MF.getFunction();
2425   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2426   bool isSoftFloat = Subtarget->useSoftFloat();
2427   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2428          "SSE register cannot be used when SSE is disabled!");
2429   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2430     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2431     // registers.
2432     return None;
2433
2434   static const MCPhysReg XMMArgRegs64Bit[] = {
2435     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2437   };
2438   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2439 }
2440
2441 SDValue
2442 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2443                                         CallingConv::ID CallConv,
2444                                         bool isVarArg,
2445                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2446                                         SDLoc dl,
2447                                         SelectionDAG &DAG,
2448                                         SmallVectorImpl<SDValue> &InVals)
2449                                           const {
2450   MachineFunction &MF = DAG.getMachineFunction();
2451   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2452   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2453
2454   const Function* Fn = MF.getFunction();
2455   if (Fn->hasExternalLinkage() &&
2456       Subtarget->isTargetCygMing() &&
2457       Fn->getName() == "main")
2458     FuncInfo->setForceFramePointer(true);
2459
2460   MachineFrameInfo *MFI = MF.getFrameInfo();
2461   bool Is64Bit = Subtarget->is64Bit();
2462   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2463
2464   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2465          "Var args not supported with calling convention fastcc, ghc or hipe");
2466
2467   // Assign locations to all of the incoming arguments.
2468   SmallVector<CCValAssign, 16> ArgLocs;
2469   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2470
2471   // Allocate shadow area for Win64
2472   if (IsWin64)
2473     CCInfo.AllocateStack(32, 8);
2474
2475   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2476
2477   unsigned LastVal = ~0U;
2478   SDValue ArgValue;
2479   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2480     CCValAssign &VA = ArgLocs[i];
2481     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2482     // places.
2483     assert(VA.getValNo() != LastVal &&
2484            "Don't support value assigned to multiple locs yet");
2485     (void)LastVal;
2486     LastVal = VA.getValNo();
2487
2488     if (VA.isRegLoc()) {
2489       EVT RegVT = VA.getLocVT();
2490       const TargetRegisterClass *RC;
2491       if (RegVT == MVT::i32)
2492         RC = &X86::GR32RegClass;
2493       else if (Is64Bit && RegVT == MVT::i64)
2494         RC = &X86::GR64RegClass;
2495       else if (RegVT == MVT::f32)
2496         RC = &X86::FR32RegClass;
2497       else if (RegVT == MVT::f64)
2498         RC = &X86::FR64RegClass;
2499       else if (RegVT.is512BitVector())
2500         RC = &X86::VR512RegClass;
2501       else if (RegVT.is256BitVector())
2502         RC = &X86::VR256RegClass;
2503       else if (RegVT.is128BitVector())
2504         RC = &X86::VR128RegClass;
2505       else if (RegVT == MVT::x86mmx)
2506         RC = &X86::VR64RegClass;
2507       else if (RegVT == MVT::i1)
2508         RC = &X86::VK1RegClass;
2509       else if (RegVT == MVT::v8i1)
2510         RC = &X86::VK8RegClass;
2511       else if (RegVT == MVT::v16i1)
2512         RC = &X86::VK16RegClass;
2513       else if (RegVT == MVT::v32i1)
2514         RC = &X86::VK32RegClass;
2515       else if (RegVT == MVT::v64i1)
2516         RC = &X86::VK64RegClass;
2517       else
2518         llvm_unreachable("Unknown argument type!");
2519
2520       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2521       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2522
2523       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2524       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2525       // right size.
2526       if (VA.getLocInfo() == CCValAssign::SExt)
2527         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2528                                DAG.getValueType(VA.getValVT()));
2529       else if (VA.getLocInfo() == CCValAssign::ZExt)
2530         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2531                                DAG.getValueType(VA.getValVT()));
2532       else if (VA.getLocInfo() == CCValAssign::BCvt)
2533         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2534
2535       if (VA.isExtInLoc()) {
2536         // Handle MMX values passed in XMM regs.
2537         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2538           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2539         else
2540           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2541       }
2542     } else {
2543       assert(VA.isMemLoc());
2544       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2545     }
2546
2547     // If value is passed via pointer - do a load.
2548     if (VA.getLocInfo() == CCValAssign::Indirect)
2549       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2550                              MachinePointerInfo(), false, false, false, 0);
2551
2552     InVals.push_back(ArgValue);
2553   }
2554
2555   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2556     // All x86 ABIs require that for returning structs by value we copy the
2557     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2558     // the argument into a virtual register so that we can access it from the
2559     // return points.
2560     if (Ins[i].Flags.isSRet()) {
2561       unsigned Reg = FuncInfo->getSRetReturnReg();
2562       if (!Reg) {
2563         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2564         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2565         FuncInfo->setSRetReturnReg(Reg);
2566       }
2567       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2568       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2569       break;
2570     }
2571   }
2572
2573   unsigned StackSize = CCInfo.getNextStackOffset();
2574   // Align stack specially for tail calls.
2575   if (FuncIsMadeTailCallSafe(CallConv,
2576                              MF.getTarget().Options.GuaranteedTailCallOpt))
2577     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2578
2579   // If the function takes variable number of arguments, make a frame index for
2580   // the start of the first vararg value... for expansion of llvm.va_start. We
2581   // can skip this if there are no va_start calls.
2582   if (MFI->hasVAStart() &&
2583       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2584                    CallConv != CallingConv::X86_ThisCall))) {
2585     FuncInfo->setVarArgsFrameIndex(
2586         MFI->CreateFixedObject(1, StackSize, true));
2587   }
2588
2589   MachineModuleInfo &MMI = MF.getMMI();
2590   const Function *WinEHParent = nullptr;
2591   if (MMI.hasWinEHFuncInfo(Fn))
2592     WinEHParent = MMI.getWinEHParent(Fn);
2593   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2594   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2595
2596   // Figure out if XMM registers are in use.
2597   assert(!(Subtarget->useSoftFloat() &&
2598            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2599          "SSE register cannot be used when SSE is disabled!");
2600
2601   // 64-bit calling conventions support varargs and register parameters, so we
2602   // have to do extra work to spill them in the prologue.
2603   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2604     // Find the first unallocated argument registers.
2605     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2606     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2607     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2608     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2609     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2610            "SSE register cannot be used when SSE is disabled!");
2611
2612     // Gather all the live in physical registers.
2613     SmallVector<SDValue, 6> LiveGPRs;
2614     SmallVector<SDValue, 8> LiveXMMRegs;
2615     SDValue ALVal;
2616     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2617       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2618       LiveGPRs.push_back(
2619           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2620     }
2621     if (!ArgXMMs.empty()) {
2622       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2623       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2624       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2625         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2626         LiveXMMRegs.push_back(
2627             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2628       }
2629     }
2630
2631     if (IsWin64) {
2632       // Get to the caller-allocated home save location.  Add 8 to account
2633       // for the return address.
2634       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2635       FuncInfo->setRegSaveFrameIndex(
2636           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2637       // Fixup to set vararg frame on shadow area (4 x i64).
2638       if (NumIntRegs < 4)
2639         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2640     } else {
2641       // For X86-64, if there are vararg parameters that are passed via
2642       // registers, then we must store them to their spots on the stack so
2643       // they may be loaded by deferencing the result of va_next.
2644       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2645       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2646       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2647           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2648     }
2649
2650     // Store the integer parameter registers.
2651     SmallVector<SDValue, 8> MemOps;
2652     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2653                                       getPointerTy(DAG.getDataLayout()));
2654     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2655     for (SDValue Val : LiveGPRs) {
2656       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2657                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2658       SDValue Store =
2659         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2660                      MachinePointerInfo::getFixedStack(
2661                        FuncInfo->getRegSaveFrameIndex(), Offset),
2662                      false, false, 0);
2663       MemOps.push_back(Store);
2664       Offset += 8;
2665     }
2666
2667     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2668       // Now store the XMM (fp + vector) parameter registers.
2669       SmallVector<SDValue, 12> SaveXMMOps;
2670       SaveXMMOps.push_back(Chain);
2671       SaveXMMOps.push_back(ALVal);
2672       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2673                              FuncInfo->getRegSaveFrameIndex(), dl));
2674       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2675                              FuncInfo->getVarArgsFPOffset(), dl));
2676       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2677                         LiveXMMRegs.end());
2678       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2679                                    MVT::Other, SaveXMMOps));
2680     }
2681
2682     if (!MemOps.empty())
2683       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2684   } else if (IsWin64 && IsWinEHOutlined) {
2685     // Get to the caller-allocated home save location.  Add 8 to account
2686     // for the return address.
2687     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2688     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2689         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2690
2691     MMI.getWinEHFuncInfo(Fn)
2692         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2693         FuncInfo->getRegSaveFrameIndex();
2694
2695     // Store the second integer parameter (rdx) into rsp+16 relative to the
2696     // stack pointer at the entry of the function.
2697     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2698                                       getPointerTy(DAG.getDataLayout()));
2699     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2700     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2701     Chain = DAG.getStore(
2702         Val.getValue(1), dl, Val, RSFIN,
2703         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2704         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2705   }
2706
2707   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2708     // Find the largest legal vector type.
2709     MVT VecVT = MVT::Other;
2710     // FIXME: Only some x86_32 calling conventions support AVX512.
2711     if (Subtarget->hasAVX512() &&
2712         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2713                      CallConv == CallingConv::Intel_OCL_BI)))
2714       VecVT = MVT::v16f32;
2715     else if (Subtarget->hasAVX())
2716       VecVT = MVT::v8f32;
2717     else if (Subtarget->hasSSE2())
2718       VecVT = MVT::v4f32;
2719
2720     // We forward some GPRs and some vector types.
2721     SmallVector<MVT, 2> RegParmTypes;
2722     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2723     RegParmTypes.push_back(IntVT);
2724     if (VecVT != MVT::Other)
2725       RegParmTypes.push_back(VecVT);
2726
2727     // Compute the set of forwarded registers. The rest are scratch.
2728     SmallVectorImpl<ForwardedRegister> &Forwards =
2729         FuncInfo->getForwardedMustTailRegParms();
2730     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2731
2732     // Conservatively forward AL on x86_64, since it might be used for varargs.
2733     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2734       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2735       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2736     }
2737
2738     // Copy all forwards from physical to virtual registers.
2739     for (ForwardedRegister &F : Forwards) {
2740       // FIXME: Can we use a less constrained schedule?
2741       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2742       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2743       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2744     }
2745   }
2746
2747   // Some CCs need callee pop.
2748   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2749                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2750     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2751   } else {
2752     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2753     // If this is an sret function, the return should pop the hidden pointer.
2754     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2755         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2756         argsAreStructReturn(Ins) == StackStructReturn)
2757       FuncInfo->setBytesToPopOnReturn(4);
2758   }
2759
2760   if (!Is64Bit) {
2761     // RegSaveFrameIndex is X86-64 only.
2762     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2763     if (CallConv == CallingConv::X86_FastCall ||
2764         CallConv == CallingConv::X86_ThisCall)
2765       // fastcc functions can't have varargs.
2766       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2767   }
2768
2769   FuncInfo->setArgumentStackSize(StackSize);
2770
2771   if (IsWinEHParent) {
2772     if (Is64Bit) {
2773       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2774       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2775       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2776       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2777       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2778                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2779                            /*isVolatile=*/true,
2780                            /*isNonTemporal=*/false, /*Alignment=*/0);
2781     } else {
2782       // Functions using Win32 EH are considered to have opaque SP adjustments
2783       // to force local variables to be addressed from the frame or base
2784       // pointers.
2785       MFI->setHasOpaqueSPAdjustment(true);
2786     }
2787   }
2788
2789   return Chain;
2790 }
2791
2792 SDValue
2793 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2794                                     SDValue StackPtr, SDValue Arg,
2795                                     SDLoc dl, SelectionDAG &DAG,
2796                                     const CCValAssign &VA,
2797                                     ISD::ArgFlagsTy Flags) const {
2798   unsigned LocMemOffset = VA.getLocMemOffset();
2799   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2800   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2801                        StackPtr, PtrOff);
2802   if (Flags.isByVal())
2803     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2804
2805   return DAG.getStore(Chain, dl, Arg, PtrOff,
2806                       MachinePointerInfo::getStack(LocMemOffset),
2807                       false, false, 0);
2808 }
2809
2810 /// Emit a load of return address if tail call
2811 /// optimization is performed and it is required.
2812 SDValue
2813 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2814                                            SDValue &OutRetAddr, SDValue Chain,
2815                                            bool IsTailCall, bool Is64Bit,
2816                                            int FPDiff, SDLoc dl) const {
2817   // Adjust the Return address stack slot.
2818   EVT VT = getPointerTy(DAG.getDataLayout());
2819   OutRetAddr = getReturnAddressFrameIndex(DAG);
2820
2821   // Load the "old" Return address.
2822   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2823                            false, false, false, 0);
2824   return SDValue(OutRetAddr.getNode(), 1);
2825 }
2826
2827 /// Emit a store of the return address if tail call
2828 /// optimization is performed and it is required (FPDiff!=0).
2829 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2830                                         SDValue Chain, SDValue RetAddrFrIdx,
2831                                         EVT PtrVT, unsigned SlotSize,
2832                                         int FPDiff, SDLoc dl) {
2833   // Store the return address to the appropriate stack slot.
2834   if (!FPDiff) return Chain;
2835   // Calculate the new stack slot for the return address.
2836   int NewReturnAddrFI =
2837     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2838                                          false);
2839   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2840   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2841                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2842                        false, false, 0);
2843   return Chain;
2844 }
2845
2846 SDValue
2847 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2848                              SmallVectorImpl<SDValue> &InVals) const {
2849   SelectionDAG &DAG                     = CLI.DAG;
2850   SDLoc &dl                             = CLI.DL;
2851   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2852   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2853   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2854   SDValue Chain                         = CLI.Chain;
2855   SDValue Callee                        = CLI.Callee;
2856   CallingConv::ID CallConv              = CLI.CallConv;
2857   bool &isTailCall                      = CLI.IsTailCall;
2858   bool isVarArg                         = CLI.IsVarArg;
2859
2860   MachineFunction &MF = DAG.getMachineFunction();
2861   bool Is64Bit        = Subtarget->is64Bit();
2862   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2863   StructReturnType SR = callIsStructReturn(Outs);
2864   bool IsSibcall      = false;
2865   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2866   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2867
2868   if (Attr.getValueAsString() == "true")
2869     isTailCall = false;
2870
2871   if (Subtarget->isPICStyleGOT() &&
2872       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2873     // If we are using a GOT, disable tail calls to external symbols with
2874     // default visibility. Tail calling such a symbol requires using a GOT
2875     // relocation, which forces early binding of the symbol. This breaks code
2876     // that require lazy function symbol resolution. Using musttail or
2877     // GuaranteedTailCallOpt will override this.
2878     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2879     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2880                G->getGlobal()->hasDefaultVisibility()))
2881       isTailCall = false;
2882   }
2883
2884   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2885   if (IsMustTail) {
2886     // Force this to be a tail call.  The verifier rules are enough to ensure
2887     // that we can lower this successfully without moving the return address
2888     // around.
2889     isTailCall = true;
2890   } else if (isTailCall) {
2891     // Check if it's really possible to do a tail call.
2892     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2893                     isVarArg, SR != NotStructReturn,
2894                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2895                     Outs, OutVals, Ins, DAG);
2896
2897     // Sibcalls are automatically detected tailcalls which do not require
2898     // ABI changes.
2899     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2900       IsSibcall = true;
2901
2902     if (isTailCall)
2903       ++NumTailCalls;
2904   }
2905
2906   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2907          "Var args not supported with calling convention fastcc, ghc or hipe");
2908
2909   // Analyze operands of the call, assigning locations to each operand.
2910   SmallVector<CCValAssign, 16> ArgLocs;
2911   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2912
2913   // Allocate shadow area for Win64
2914   if (IsWin64)
2915     CCInfo.AllocateStack(32, 8);
2916
2917   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2918
2919   // Get a count of how many bytes are to be pushed on the stack.
2920   unsigned NumBytes = CCInfo.getNextStackOffset();
2921   if (IsSibcall)
2922     // This is a sibcall. The memory operands are available in caller's
2923     // own caller's stack.
2924     NumBytes = 0;
2925   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2926            IsTailCallConvention(CallConv))
2927     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2928
2929   int FPDiff = 0;
2930   if (isTailCall && !IsSibcall && !IsMustTail) {
2931     // Lower arguments at fp - stackoffset + fpdiff.
2932     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2933
2934     FPDiff = NumBytesCallerPushed - NumBytes;
2935
2936     // Set the delta of movement of the returnaddr stackslot.
2937     // But only set if delta is greater than previous delta.
2938     if (FPDiff < X86Info->getTCReturnAddrDelta())
2939       X86Info->setTCReturnAddrDelta(FPDiff);
2940   }
2941
2942   unsigned NumBytesToPush = NumBytes;
2943   unsigned NumBytesToPop = NumBytes;
2944
2945   // If we have an inalloca argument, all stack space has already been allocated
2946   // for us and be right at the top of the stack.  We don't support multiple
2947   // arguments passed in memory when using inalloca.
2948   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2949     NumBytesToPush = 0;
2950     if (!ArgLocs.back().isMemLoc())
2951       report_fatal_error("cannot use inalloca attribute on a register "
2952                          "parameter");
2953     if (ArgLocs.back().getLocMemOffset() != 0)
2954       report_fatal_error("any parameter with the inalloca attribute must be "
2955                          "the only memory argument");
2956   }
2957
2958   if (!IsSibcall)
2959     Chain = DAG.getCALLSEQ_START(
2960         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2961
2962   SDValue RetAddrFrIdx;
2963   // Load return address for tail calls.
2964   if (isTailCall && FPDiff)
2965     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2966                                     Is64Bit, FPDiff, dl);
2967
2968   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2969   SmallVector<SDValue, 8> MemOpChains;
2970   SDValue StackPtr;
2971
2972   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2973   // of tail call optimization arguments are handle later.
2974   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2975   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2976     // Skip inalloca arguments, they have already been written.
2977     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2978     if (Flags.isInAlloca())
2979       continue;
2980
2981     CCValAssign &VA = ArgLocs[i];
2982     EVT RegVT = VA.getLocVT();
2983     SDValue Arg = OutVals[i];
2984     bool isByVal = Flags.isByVal();
2985
2986     // Promote the value if needed.
2987     switch (VA.getLocInfo()) {
2988     default: llvm_unreachable("Unknown loc info!");
2989     case CCValAssign::Full: break;
2990     case CCValAssign::SExt:
2991       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2992       break;
2993     case CCValAssign::ZExt:
2994       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2995       break;
2996     case CCValAssign::AExt:
2997       if (Arg.getValueType().isVector() &&
2998           Arg.getValueType().getScalarType() == MVT::i1)
2999         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3000       else if (RegVT.is128BitVector()) {
3001         // Special case: passing MMX values in XMM registers.
3002         Arg = DAG.getBitcast(MVT::i64, Arg);
3003         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3004         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3005       } else
3006         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3007       break;
3008     case CCValAssign::BCvt:
3009       Arg = DAG.getBitcast(RegVT, Arg);
3010       break;
3011     case CCValAssign::Indirect: {
3012       // Store the argument.
3013       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3014       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3015       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3016                            MachinePointerInfo::getFixedStack(FI),
3017                            false, false, 0);
3018       Arg = SpillSlot;
3019       break;
3020     }
3021     }
3022
3023     if (VA.isRegLoc()) {
3024       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3025       if (isVarArg && IsWin64) {
3026         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3027         // shadow reg if callee is a varargs function.
3028         unsigned ShadowReg = 0;
3029         switch (VA.getLocReg()) {
3030         case X86::XMM0: ShadowReg = X86::RCX; break;
3031         case X86::XMM1: ShadowReg = X86::RDX; break;
3032         case X86::XMM2: ShadowReg = X86::R8; break;
3033         case X86::XMM3: ShadowReg = X86::R9; break;
3034         }
3035         if (ShadowReg)
3036           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3037       }
3038     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3039       assert(VA.isMemLoc());
3040       if (!StackPtr.getNode())
3041         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3042                                       getPointerTy(DAG.getDataLayout()));
3043       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3044                                              dl, DAG, VA, Flags));
3045     }
3046   }
3047
3048   if (!MemOpChains.empty())
3049     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3050
3051   if (Subtarget->isPICStyleGOT()) {
3052     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3053     // GOT pointer.
3054     if (!isTailCall) {
3055       RegsToPass.push_back(std::make_pair(
3056           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3057                                           getPointerTy(DAG.getDataLayout()))));
3058     } else {
3059       // If we are tail calling and generating PIC/GOT style code load the
3060       // address of the callee into ECX. The value in ecx is used as target of
3061       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3062       // for tail calls on PIC/GOT architectures. Normally we would just put the
3063       // address of GOT into ebx and then call target@PLT. But for tail calls
3064       // ebx would be restored (since ebx is callee saved) before jumping to the
3065       // target@PLT.
3066
3067       // Note: The actual moving to ECX is done further down.
3068       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3069       if (G && !G->getGlobal()->hasLocalLinkage() &&
3070           G->getGlobal()->hasDefaultVisibility())
3071         Callee = LowerGlobalAddress(Callee, DAG);
3072       else if (isa<ExternalSymbolSDNode>(Callee))
3073         Callee = LowerExternalSymbol(Callee, DAG);
3074     }
3075   }
3076
3077   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3078     // From AMD64 ABI document:
3079     // For calls that may call functions that use varargs or stdargs
3080     // (prototype-less calls or calls to functions containing ellipsis (...) in
3081     // the declaration) %al is used as hidden argument to specify the number
3082     // of SSE registers used. The contents of %al do not need to match exactly
3083     // the number of registers, but must be an ubound on the number of SSE
3084     // registers used and is in the range 0 - 8 inclusive.
3085
3086     // Count the number of XMM registers allocated.
3087     static const MCPhysReg XMMArgRegs[] = {
3088       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3089       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3090     };
3091     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3092     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3093            && "SSE registers cannot be used when SSE is disabled");
3094
3095     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3096                                         DAG.getConstant(NumXMMRegs, dl,
3097                                                         MVT::i8)));
3098   }
3099
3100   if (isVarArg && IsMustTail) {
3101     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3102     for (const auto &F : Forwards) {
3103       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3104       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3105     }
3106   }
3107
3108   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3109   // don't need this because the eligibility check rejects calls that require
3110   // shuffling arguments passed in memory.
3111   if (!IsSibcall && isTailCall) {
3112     // Force all the incoming stack arguments to be loaded from the stack
3113     // before any new outgoing arguments are stored to the stack, because the
3114     // outgoing stack slots may alias the incoming argument stack slots, and
3115     // the alias isn't otherwise explicit. This is slightly more conservative
3116     // than necessary, because it means that each store effectively depends
3117     // on every argument instead of just those arguments it would clobber.
3118     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3119
3120     SmallVector<SDValue, 8> MemOpChains2;
3121     SDValue FIN;
3122     int FI = 0;
3123     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3124       CCValAssign &VA = ArgLocs[i];
3125       if (VA.isRegLoc())
3126         continue;
3127       assert(VA.isMemLoc());
3128       SDValue Arg = OutVals[i];
3129       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3130       // Skip inalloca arguments.  They don't require any work.
3131       if (Flags.isInAlloca())
3132         continue;
3133       // Create frame index.
3134       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3135       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3136       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3137       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3138
3139       if (Flags.isByVal()) {
3140         // Copy relative to framepointer.
3141         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3142         if (!StackPtr.getNode())
3143           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3144                                         getPointerTy(DAG.getDataLayout()));
3145         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3146                              StackPtr, Source);
3147
3148         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3149                                                          ArgChain,
3150                                                          Flags, DAG, dl));
3151       } else {
3152         // Store relative to framepointer.
3153         MemOpChains2.push_back(
3154           DAG.getStore(ArgChain, dl, Arg, FIN,
3155                        MachinePointerInfo::getFixedStack(FI),
3156                        false, false, 0));
3157       }
3158     }
3159
3160     if (!MemOpChains2.empty())
3161       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3162
3163     // Store the return address to the appropriate stack slot.
3164     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3165                                      getPointerTy(DAG.getDataLayout()),
3166                                      RegInfo->getSlotSize(), FPDiff, dl);
3167   }
3168
3169   // Build a sequence of copy-to-reg nodes chained together with token chain
3170   // and flag operands which copy the outgoing args into registers.
3171   SDValue InFlag;
3172   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3173     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3174                              RegsToPass[i].second, InFlag);
3175     InFlag = Chain.getValue(1);
3176   }
3177
3178   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3179     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3180     // In the 64-bit large code model, we have to make all calls
3181     // through a register, since the call instruction's 32-bit
3182     // pc-relative offset may not be large enough to hold the whole
3183     // address.
3184   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3185     // If the callee is a GlobalAddress node (quite common, every direct call
3186     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3187     // it.
3188     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3189
3190     // We should use extra load for direct calls to dllimported functions in
3191     // non-JIT mode.
3192     const GlobalValue *GV = G->getGlobal();
3193     if (!GV->hasDLLImportStorageClass()) {
3194       unsigned char OpFlags = 0;
3195       bool ExtraLoad = false;
3196       unsigned WrapperKind = ISD::DELETED_NODE;
3197
3198       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3199       // external symbols most go through the PLT in PIC mode.  If the symbol
3200       // has hidden or protected visibility, or if it is static or local, then
3201       // we don't need to use the PLT - we can directly call it.
3202       if (Subtarget->isTargetELF() &&
3203           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3204           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3205         OpFlags = X86II::MO_PLT;
3206       } else if (Subtarget->isPICStyleStubAny() &&
3207                  !GV->isStrongDefinitionForLinker() &&
3208                  (!Subtarget->getTargetTriple().isMacOSX() ||
3209                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3210         // PC-relative references to external symbols should go through $stub,
3211         // unless we're building with the leopard linker or later, which
3212         // automatically synthesizes these stubs.
3213         OpFlags = X86II::MO_DARWIN_STUB;
3214       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3215                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3216         // If the function is marked as non-lazy, generate an indirect call
3217         // which loads from the GOT directly. This avoids runtime overhead
3218         // at the cost of eager binding (and one extra byte of encoding).
3219         OpFlags = X86II::MO_GOTPCREL;
3220         WrapperKind = X86ISD::WrapperRIP;
3221         ExtraLoad = true;
3222       }
3223
3224       Callee = DAG.getTargetGlobalAddress(
3225           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3226
3227       // Add a wrapper if needed.
3228       if (WrapperKind != ISD::DELETED_NODE)
3229         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3230                              getPointerTy(DAG.getDataLayout()), Callee);
3231       // Add extra indirection if needed.
3232       if (ExtraLoad)
3233         Callee = DAG.getLoad(
3234             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3235             MachinePointerInfo::getGOT(), false, false, false, 0);
3236     }
3237   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3238     unsigned char OpFlags = 0;
3239
3240     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3241     // external symbols should go through the PLT.
3242     if (Subtarget->isTargetELF() &&
3243         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3244       OpFlags = X86II::MO_PLT;
3245     } else if (Subtarget->isPICStyleStubAny() &&
3246                (!Subtarget->getTargetTriple().isMacOSX() ||
3247                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3248       // PC-relative references to external symbols should go through $stub,
3249       // unless we're building with the leopard linker or later, which
3250       // automatically synthesizes these stubs.
3251       OpFlags = X86II::MO_DARWIN_STUB;
3252     }
3253
3254     Callee = DAG.getTargetExternalSymbol(
3255         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3256   } else if (Subtarget->isTarget64BitILP32() &&
3257              Callee->getValueType(0) == MVT::i32) {
3258     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3259     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3260   }
3261
3262   // Returns a chain & a flag for retval copy to use.
3263   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3264   SmallVector<SDValue, 8> Ops;
3265
3266   if (!IsSibcall && isTailCall) {
3267     Chain = DAG.getCALLSEQ_END(Chain,
3268                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3269                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3270     InFlag = Chain.getValue(1);
3271   }
3272
3273   Ops.push_back(Chain);
3274   Ops.push_back(Callee);
3275
3276   if (isTailCall)
3277     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3278
3279   // Add argument registers to the end of the list so that they are known live
3280   // into the call.
3281   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3282     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3283                                   RegsToPass[i].second.getValueType()));
3284
3285   // Add a register mask operand representing the call-preserved registers.
3286   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3287   assert(Mask && "Missing call preserved mask for calling convention");
3288
3289   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3290   // the function clobbers all registers. If an exception is thrown, the runtime
3291   // will not restore CSRs.
3292   // FIXME: Model this more precisely so that we can register allocate across
3293   // the normal edge and spill and fill across the exceptional edge.
3294   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3295     const Function *CallerFn = MF.getFunction();
3296     EHPersonality Pers =
3297         CallerFn->hasPersonalityFn()
3298             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3299             : EHPersonality::Unknown;
3300     if (isMSVCEHPersonality(Pers))
3301       Mask = RegInfo->getNoPreservedMask();
3302   }
3303
3304   Ops.push_back(DAG.getRegisterMask(Mask));
3305
3306   if (InFlag.getNode())
3307     Ops.push_back(InFlag);
3308
3309   if (isTailCall) {
3310     // We used to do:
3311     //// If this is the first return lowered for this function, add the regs
3312     //// to the liveout set for the function.
3313     // This isn't right, although it's probably harmless on x86; liveouts
3314     // should be computed from returns not tail calls.  Consider a void
3315     // function making a tail call to a function returning int.
3316     MF.getFrameInfo()->setHasTailCall();
3317     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3318   }
3319
3320   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3321   InFlag = Chain.getValue(1);
3322
3323   // Create the CALLSEQ_END node.
3324   unsigned NumBytesForCalleeToPop;
3325   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3326                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3327     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3328   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3329            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3330            SR == StackStructReturn)
3331     // If this is a call to a struct-return function, the callee
3332     // pops the hidden struct pointer, so we have to push it back.
3333     // This is common for Darwin/X86, Linux & Mingw32 targets.
3334     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3335     NumBytesForCalleeToPop = 4;
3336   else
3337     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3338
3339   // Returns a flag for retval copy to use.
3340   if (!IsSibcall) {
3341     Chain = DAG.getCALLSEQ_END(Chain,
3342                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3343                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3344                                                      true),
3345                                InFlag, dl);
3346     InFlag = Chain.getValue(1);
3347   }
3348
3349   // Handle result values, copying them out of physregs into vregs that we
3350   // return.
3351   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3352                          Ins, dl, DAG, InVals);
3353 }
3354
3355 //===----------------------------------------------------------------------===//
3356 //                Fast Calling Convention (tail call) implementation
3357 //===----------------------------------------------------------------------===//
3358
3359 //  Like std call, callee cleans arguments, convention except that ECX is
3360 //  reserved for storing the tail called function address. Only 2 registers are
3361 //  free for argument passing (inreg). Tail call optimization is performed
3362 //  provided:
3363 //                * tailcallopt is enabled
3364 //                * caller/callee are fastcc
3365 //  On X86_64 architecture with GOT-style position independent code only local
3366 //  (within module) calls are supported at the moment.
3367 //  To keep the stack aligned according to platform abi the function
3368 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3369 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3370 //  If a tail called function callee has more arguments than the caller the
3371 //  caller needs to make sure that there is room to move the RETADDR to. This is
3372 //  achieved by reserving an area the size of the argument delta right after the
3373 //  original RETADDR, but before the saved framepointer or the spilled registers
3374 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3375 //  stack layout:
3376 //    arg1
3377 //    arg2
3378 //    RETADDR
3379 //    [ new RETADDR
3380 //      move area ]
3381 //    (possible EBP)
3382 //    ESI
3383 //    EDI
3384 //    local1 ..
3385
3386 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3387 /// for a 16 byte align requirement.
3388 unsigned
3389 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3390                                                SelectionDAG& DAG) const {
3391   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3392   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3393   unsigned StackAlignment = TFI.getStackAlignment();
3394   uint64_t AlignMask = StackAlignment - 1;
3395   int64_t Offset = StackSize;
3396   unsigned SlotSize = RegInfo->getSlotSize();
3397   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3398     // Number smaller than 12 so just add the difference.
3399     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3400   } else {
3401     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3402     Offset = ((~AlignMask) & Offset) + StackAlignment +
3403       (StackAlignment-SlotSize);
3404   }
3405   return Offset;
3406 }
3407
3408 /// MatchingStackOffset - Return true if the given stack call argument is
3409 /// already available in the same position (relatively) of the caller's
3410 /// incoming argument stack.
3411 static
3412 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3413                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3414                          const X86InstrInfo *TII) {
3415   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3416   int FI = INT_MAX;
3417   if (Arg.getOpcode() == ISD::CopyFromReg) {
3418     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3419     if (!TargetRegisterInfo::isVirtualRegister(VR))
3420       return false;
3421     MachineInstr *Def = MRI->getVRegDef(VR);
3422     if (!Def)
3423       return false;
3424     if (!Flags.isByVal()) {
3425       if (!TII->isLoadFromStackSlot(Def, FI))
3426         return false;
3427     } else {
3428       unsigned Opcode = Def->getOpcode();
3429       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3430            Opcode == X86::LEA64_32r) &&
3431           Def->getOperand(1).isFI()) {
3432         FI = Def->getOperand(1).getIndex();
3433         Bytes = Flags.getByValSize();
3434       } else
3435         return false;
3436     }
3437   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3438     if (Flags.isByVal())
3439       // ByVal argument is passed in as a pointer but it's now being
3440       // dereferenced. e.g.
3441       // define @foo(%struct.X* %A) {
3442       //   tail call @bar(%struct.X* byval %A)
3443       // }
3444       return false;
3445     SDValue Ptr = Ld->getBasePtr();
3446     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3447     if (!FINode)
3448       return false;
3449     FI = FINode->getIndex();
3450   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3451     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3452     FI = FINode->getIndex();
3453     Bytes = Flags.getByValSize();
3454   } else
3455     return false;
3456
3457   assert(FI != INT_MAX);
3458   if (!MFI->isFixedObjectIndex(FI))
3459     return false;
3460   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3461 }
3462
3463 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3464 /// for tail call optimization. Targets which want to do tail call
3465 /// optimization should implement this function.
3466 bool
3467 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3468                                                      CallingConv::ID CalleeCC,
3469                                                      bool isVarArg,
3470                                                      bool isCalleeStructRet,
3471                                                      bool isCallerStructRet,
3472                                                      Type *RetTy,
3473                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3474                                     const SmallVectorImpl<SDValue> &OutVals,
3475                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3476                                                      SelectionDAG &DAG) const {
3477   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3478     return false;
3479
3480   // If -tailcallopt is specified, make fastcc functions tail-callable.
3481   const MachineFunction &MF = DAG.getMachineFunction();
3482   const Function *CallerF = MF.getFunction();
3483
3484   // If the function return type is x86_fp80 and the callee return type is not,
3485   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3486   // perform a tailcall optimization here.
3487   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3488     return false;
3489
3490   CallingConv::ID CallerCC = CallerF->getCallingConv();
3491   bool CCMatch = CallerCC == CalleeCC;
3492   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3493   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3494
3495   // Win64 functions have extra shadow space for argument homing. Don't do the
3496   // sibcall if the caller and callee have mismatched expectations for this
3497   // space.
3498   if (IsCalleeWin64 != IsCallerWin64)
3499     return false;
3500
3501   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3502     if (IsTailCallConvention(CalleeCC) && CCMatch)
3503       return true;
3504     return false;
3505   }
3506
3507   // Look for obvious safe cases to perform tail call optimization that do not
3508   // require ABI changes. This is what gcc calls sibcall.
3509
3510   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3511   // emit a special epilogue.
3512   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3513   if (RegInfo->needsStackRealignment(MF))
3514     return false;
3515
3516   // Also avoid sibcall optimization if either caller or callee uses struct
3517   // return semantics.
3518   if (isCalleeStructRet || isCallerStructRet)
3519     return false;
3520
3521   // An stdcall/thiscall caller is expected to clean up its arguments; the
3522   // callee isn't going to do that.
3523   // FIXME: this is more restrictive than needed. We could produce a tailcall
3524   // when the stack adjustment matches. For example, with a thiscall that takes
3525   // only one argument.
3526   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3527                    CallerCC == CallingConv::X86_ThisCall))
3528     return false;
3529
3530   // Do not sibcall optimize vararg calls unless all arguments are passed via
3531   // registers.
3532   if (isVarArg && !Outs.empty()) {
3533
3534     // Optimizing for varargs on Win64 is unlikely to be safe without
3535     // additional testing.
3536     if (IsCalleeWin64 || IsCallerWin64)
3537       return false;
3538
3539     SmallVector<CCValAssign, 16> ArgLocs;
3540     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3541                    *DAG.getContext());
3542
3543     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3544     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3545       if (!ArgLocs[i].isRegLoc())
3546         return false;
3547   }
3548
3549   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3550   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3551   // this into a sibcall.
3552   bool Unused = false;
3553   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3554     if (!Ins[i].Used) {
3555       Unused = true;
3556       break;
3557     }
3558   }
3559   if (Unused) {
3560     SmallVector<CCValAssign, 16> RVLocs;
3561     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3562                    *DAG.getContext());
3563     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3564     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3565       CCValAssign &VA = RVLocs[i];
3566       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3567         return false;
3568     }
3569   }
3570
3571   // If the calling conventions do not match, then we'd better make sure the
3572   // results are returned in the same way as what the caller expects.
3573   if (!CCMatch) {
3574     SmallVector<CCValAssign, 16> RVLocs1;
3575     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3576                     *DAG.getContext());
3577     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3578
3579     SmallVector<CCValAssign, 16> RVLocs2;
3580     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3581                     *DAG.getContext());
3582     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3583
3584     if (RVLocs1.size() != RVLocs2.size())
3585       return false;
3586     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3587       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3588         return false;
3589       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3590         return false;
3591       if (RVLocs1[i].isRegLoc()) {
3592         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3593           return false;
3594       } else {
3595         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3596           return false;
3597       }
3598     }
3599   }
3600
3601   // If the callee takes no arguments then go on to check the results of the
3602   // call.
3603   if (!Outs.empty()) {
3604     // Check if stack adjustment is needed. For now, do not do this if any
3605     // argument is passed on the stack.
3606     SmallVector<CCValAssign, 16> ArgLocs;
3607     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3608                    *DAG.getContext());
3609
3610     // Allocate shadow area for Win64
3611     if (IsCalleeWin64)
3612       CCInfo.AllocateStack(32, 8);
3613
3614     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3615     if (CCInfo.getNextStackOffset()) {
3616       MachineFunction &MF = DAG.getMachineFunction();
3617       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3618         return false;
3619
3620       // Check if the arguments are already laid out in the right way as
3621       // the caller's fixed stack objects.
3622       MachineFrameInfo *MFI = MF.getFrameInfo();
3623       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3624       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3625       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3626         CCValAssign &VA = ArgLocs[i];
3627         SDValue Arg = OutVals[i];
3628         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3629         if (VA.getLocInfo() == CCValAssign::Indirect)
3630           return false;
3631         if (!VA.isRegLoc()) {
3632           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3633                                    MFI, MRI, TII))
3634             return false;
3635         }
3636       }
3637     }
3638
3639     // If the tailcall address may be in a register, then make sure it's
3640     // possible to register allocate for it. In 32-bit, the call address can
3641     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3642     // callee-saved registers are restored. These happen to be the same
3643     // registers used to pass 'inreg' arguments so watch out for those.
3644     if (!Subtarget->is64Bit() &&
3645         ((!isa<GlobalAddressSDNode>(Callee) &&
3646           !isa<ExternalSymbolSDNode>(Callee)) ||
3647          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3648       unsigned NumInRegs = 0;
3649       // In PIC we need an extra register to formulate the address computation
3650       // for the callee.
3651       unsigned MaxInRegs =
3652         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3653
3654       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3655         CCValAssign &VA = ArgLocs[i];
3656         if (!VA.isRegLoc())
3657           continue;
3658         unsigned Reg = VA.getLocReg();
3659         switch (Reg) {
3660         default: break;
3661         case X86::EAX: case X86::EDX: case X86::ECX:
3662           if (++NumInRegs == MaxInRegs)
3663             return false;
3664           break;
3665         }
3666       }
3667     }
3668   }
3669
3670   return true;
3671 }
3672
3673 FastISel *
3674 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3675                                   const TargetLibraryInfo *libInfo) const {
3676   return X86::createFastISel(funcInfo, libInfo);
3677 }
3678
3679 //===----------------------------------------------------------------------===//
3680 //                           Other Lowering Hooks
3681 //===----------------------------------------------------------------------===//
3682
3683 static bool MayFoldLoad(SDValue Op) {
3684   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3685 }
3686
3687 static bool MayFoldIntoStore(SDValue Op) {
3688   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3689 }
3690
3691 static bool isTargetShuffle(unsigned Opcode) {
3692   switch(Opcode) {
3693   default: return false;
3694   case X86ISD::BLENDI:
3695   case X86ISD::PSHUFB:
3696   case X86ISD::PSHUFD:
3697   case X86ISD::PSHUFHW:
3698   case X86ISD::PSHUFLW:
3699   case X86ISD::SHUFP:
3700   case X86ISD::PALIGNR:
3701   case X86ISD::MOVLHPS:
3702   case X86ISD::MOVLHPD:
3703   case X86ISD::MOVHLPS:
3704   case X86ISD::MOVLPS:
3705   case X86ISD::MOVLPD:
3706   case X86ISD::MOVSHDUP:
3707   case X86ISD::MOVSLDUP:
3708   case X86ISD::MOVDDUP:
3709   case X86ISD::MOVSS:
3710   case X86ISD::MOVSD:
3711   case X86ISD::UNPCKL:
3712   case X86ISD::UNPCKH:
3713   case X86ISD::VPERMILPI:
3714   case X86ISD::VPERM2X128:
3715   case X86ISD::VPERMI:
3716     return true;
3717   }
3718 }
3719
3720 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3721                                     SDValue V1, unsigned TargetMask,
3722                                     SelectionDAG &DAG) {
3723   switch(Opc) {
3724   default: llvm_unreachable("Unknown x86 shuffle node");
3725   case X86ISD::PSHUFD:
3726   case X86ISD::PSHUFHW:
3727   case X86ISD::PSHUFLW:
3728   case X86ISD::VPERMILPI:
3729   case X86ISD::VPERMI:
3730     return DAG.getNode(Opc, dl, VT, V1,
3731                        DAG.getConstant(TargetMask, dl, MVT::i8));
3732   }
3733 }
3734
3735 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3736                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3737   switch(Opc) {
3738   default: llvm_unreachable("Unknown x86 shuffle node");
3739   case X86ISD::MOVLHPS:
3740   case X86ISD::MOVLHPD:
3741   case X86ISD::MOVHLPS:
3742   case X86ISD::MOVLPS:
3743   case X86ISD::MOVLPD:
3744   case X86ISD::MOVSS:
3745   case X86ISD::MOVSD:
3746   case X86ISD::UNPCKL:
3747   case X86ISD::UNPCKH:
3748     return DAG.getNode(Opc, dl, VT, V1, V2);
3749   }
3750 }
3751
3752 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3753   MachineFunction &MF = DAG.getMachineFunction();
3754   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3755   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3756   int ReturnAddrIndex = FuncInfo->getRAIndex();
3757
3758   if (ReturnAddrIndex == 0) {
3759     // Set up a frame object for the return address.
3760     unsigned SlotSize = RegInfo->getSlotSize();
3761     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3762                                                            -(int64_t)SlotSize,
3763                                                            false);
3764     FuncInfo->setRAIndex(ReturnAddrIndex);
3765   }
3766
3767   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3768 }
3769
3770 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3771                                        bool hasSymbolicDisplacement) {
3772   // Offset should fit into 32 bit immediate field.
3773   if (!isInt<32>(Offset))
3774     return false;
3775
3776   // If we don't have a symbolic displacement - we don't have any extra
3777   // restrictions.
3778   if (!hasSymbolicDisplacement)
3779     return true;
3780
3781   // FIXME: Some tweaks might be needed for medium code model.
3782   if (M != CodeModel::Small && M != CodeModel::Kernel)
3783     return false;
3784
3785   // For small code model we assume that latest object is 16MB before end of 31
3786   // bits boundary. We may also accept pretty large negative constants knowing
3787   // that all objects are in the positive half of address space.
3788   if (M == CodeModel::Small && Offset < 16*1024*1024)
3789     return true;
3790
3791   // For kernel code model we know that all object resist in the negative half
3792   // of 32bits address space. We may not accept negative offsets, since they may
3793   // be just off and we may accept pretty large positive ones.
3794   if (M == CodeModel::Kernel && Offset >= 0)
3795     return true;
3796
3797   return false;
3798 }
3799
3800 /// isCalleePop - Determines whether the callee is required to pop its
3801 /// own arguments. Callee pop is necessary to support tail calls.
3802 bool X86::isCalleePop(CallingConv::ID CallingConv,
3803                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3804   switch (CallingConv) {
3805   default:
3806     return false;
3807   case CallingConv::X86_StdCall:
3808   case CallingConv::X86_FastCall:
3809   case CallingConv::X86_ThisCall:
3810     return !is64Bit;
3811   case CallingConv::Fast:
3812   case CallingConv::GHC:
3813   case CallingConv::HiPE:
3814     if (IsVarArg)
3815       return false;
3816     return TailCallOpt;
3817   }
3818 }
3819
3820 /// \brief Return true if the condition is an unsigned comparison operation.
3821 static bool isX86CCUnsigned(unsigned X86CC) {
3822   switch (X86CC) {
3823   default: llvm_unreachable("Invalid integer condition!");
3824   case X86::COND_E:     return true;
3825   case X86::COND_G:     return false;
3826   case X86::COND_GE:    return false;
3827   case X86::COND_L:     return false;
3828   case X86::COND_LE:    return false;
3829   case X86::COND_NE:    return true;
3830   case X86::COND_B:     return true;
3831   case X86::COND_A:     return true;
3832   case X86::COND_BE:    return true;
3833   case X86::COND_AE:    return true;
3834   }
3835   llvm_unreachable("covered switch fell through?!");
3836 }
3837
3838 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3839 /// specific condition code, returning the condition code and the LHS/RHS of the
3840 /// comparison to make.
3841 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3842                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3843   if (!isFP) {
3844     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3845       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3846         // X > -1   -> X == 0, jump !sign.
3847         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3848         return X86::COND_NS;
3849       }
3850       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3851         // X < 0   -> X == 0, jump on sign.
3852         return X86::COND_S;
3853       }
3854       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3855         // X < 1   -> X <= 0
3856         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3857         return X86::COND_LE;
3858       }
3859     }
3860
3861     switch (SetCCOpcode) {
3862     default: llvm_unreachable("Invalid integer condition!");
3863     case ISD::SETEQ:  return X86::COND_E;
3864     case ISD::SETGT:  return X86::COND_G;
3865     case ISD::SETGE:  return X86::COND_GE;
3866     case ISD::SETLT:  return X86::COND_L;
3867     case ISD::SETLE:  return X86::COND_LE;
3868     case ISD::SETNE:  return X86::COND_NE;
3869     case ISD::SETULT: return X86::COND_B;
3870     case ISD::SETUGT: return X86::COND_A;
3871     case ISD::SETULE: return X86::COND_BE;
3872     case ISD::SETUGE: return X86::COND_AE;
3873     }
3874   }
3875
3876   // First determine if it is required or is profitable to flip the operands.
3877
3878   // If LHS is a foldable load, but RHS is not, flip the condition.
3879   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3880       !ISD::isNON_EXTLoad(RHS.getNode())) {
3881     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3882     std::swap(LHS, RHS);
3883   }
3884
3885   switch (SetCCOpcode) {
3886   default: break;
3887   case ISD::SETOLT:
3888   case ISD::SETOLE:
3889   case ISD::SETUGT:
3890   case ISD::SETUGE:
3891     std::swap(LHS, RHS);
3892     break;
3893   }
3894
3895   // On a floating point condition, the flags are set as follows:
3896   // ZF  PF  CF   op
3897   //  0 | 0 | 0 | X > Y
3898   //  0 | 0 | 1 | X < Y
3899   //  1 | 0 | 0 | X == Y
3900   //  1 | 1 | 1 | unordered
3901   switch (SetCCOpcode) {
3902   default: llvm_unreachable("Condcode should be pre-legalized away");
3903   case ISD::SETUEQ:
3904   case ISD::SETEQ:   return X86::COND_E;
3905   case ISD::SETOLT:              // flipped
3906   case ISD::SETOGT:
3907   case ISD::SETGT:   return X86::COND_A;
3908   case ISD::SETOLE:              // flipped
3909   case ISD::SETOGE:
3910   case ISD::SETGE:   return X86::COND_AE;
3911   case ISD::SETUGT:              // flipped
3912   case ISD::SETULT:
3913   case ISD::SETLT:   return X86::COND_B;
3914   case ISD::SETUGE:              // flipped
3915   case ISD::SETULE:
3916   case ISD::SETLE:   return X86::COND_BE;
3917   case ISD::SETONE:
3918   case ISD::SETNE:   return X86::COND_NE;
3919   case ISD::SETUO:   return X86::COND_P;
3920   case ISD::SETO:    return X86::COND_NP;
3921   case ISD::SETOEQ:
3922   case ISD::SETUNE:  return X86::COND_INVALID;
3923   }
3924 }
3925
3926 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3927 /// code. Current x86 isa includes the following FP cmov instructions:
3928 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3929 static bool hasFPCMov(unsigned X86CC) {
3930   switch (X86CC) {
3931   default:
3932     return false;
3933   case X86::COND_B:
3934   case X86::COND_BE:
3935   case X86::COND_E:
3936   case X86::COND_P:
3937   case X86::COND_A:
3938   case X86::COND_AE:
3939   case X86::COND_NE:
3940   case X86::COND_NP:
3941     return true;
3942   }
3943 }
3944
3945 /// isFPImmLegal - Returns true if the target can instruction select the
3946 /// specified FP immediate natively. If false, the legalizer will
3947 /// materialize the FP immediate as a load from a constant pool.
3948 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3949   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3950     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3951       return true;
3952   }
3953   return false;
3954 }
3955
3956 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3957                                               ISD::LoadExtType ExtTy,
3958                                               EVT NewVT) const {
3959   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3960   // relocation target a movq or addq instruction: don't let the load shrink.
3961   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3962   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3963     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3964       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3965   return true;
3966 }
3967
3968 /// \brief Returns true if it is beneficial to convert a load of a constant
3969 /// to just the constant itself.
3970 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3971                                                           Type *Ty) const {
3972   assert(Ty->isIntegerTy());
3973
3974   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3975   if (BitSize == 0 || BitSize > 64)
3976     return false;
3977   return true;
3978 }
3979
3980 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3981                                                 unsigned Index) const {
3982   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3983     return false;
3984
3985   return (Index == 0 || Index == ResVT.getVectorNumElements());
3986 }
3987
3988 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3989   // Speculate cttz only if we can directly use TZCNT.
3990   return Subtarget->hasBMI();
3991 }
3992
3993 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3994   // Speculate ctlz only if we can directly use LZCNT.
3995   return Subtarget->hasLZCNT();
3996 }
3997
3998 /// isUndefInRange - Return true if every element in Mask, beginning
3999 /// from position Pos and ending in Pos+Size is undef.
4000 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4001   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4002     if (0 <= Mask[i])
4003       return false;
4004   return true;
4005 }
4006
4007 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
4008 /// the specified range (L, H].
4009 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4010   return (Val < 0) || (Val >= Low && Val < Hi);
4011 }
4012
4013 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
4014 /// specified value.
4015 static bool isUndefOrEqual(int Val, int CmpVal) {
4016   return (Val < 0 || Val == CmpVal);
4017 }
4018
4019 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
4020 /// from position Pos and ending in Pos+Size, falls within the specified
4021 /// sequential range (Low, Low+Size]. or is undef.
4022 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4023                                        unsigned Pos, unsigned Size, int Low) {
4024   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4025     if (!isUndefOrEqual(Mask[i], Low))
4026       return false;
4027   return true;
4028 }
4029
4030 /// isVEXTRACTIndex - Return true if the specified
4031 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4032 /// suitable for instruction that extract 128 or 256 bit vectors
4033 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4034   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4035   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4036     return false;
4037
4038   // The index should be aligned on a vecWidth-bit boundary.
4039   uint64_t Index =
4040     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4041
4042   MVT VT = N->getSimpleValueType(0);
4043   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4044   bool Result = (Index * ElSize) % vecWidth == 0;
4045
4046   return Result;
4047 }
4048
4049 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4050 /// operand specifies a subvector insert that is suitable for input to
4051 /// insertion of 128 or 256-bit subvectors
4052 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4053   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4054   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4055     return false;
4056   // The index should be aligned on a vecWidth-bit boundary.
4057   uint64_t Index =
4058     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4059
4060   MVT VT = N->getSimpleValueType(0);
4061   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4062   bool Result = (Index * ElSize) % vecWidth == 0;
4063
4064   return Result;
4065 }
4066
4067 bool X86::isVINSERT128Index(SDNode *N) {
4068   return isVINSERTIndex(N, 128);
4069 }
4070
4071 bool X86::isVINSERT256Index(SDNode *N) {
4072   return isVINSERTIndex(N, 256);
4073 }
4074
4075 bool X86::isVEXTRACT128Index(SDNode *N) {
4076   return isVEXTRACTIndex(N, 128);
4077 }
4078
4079 bool X86::isVEXTRACT256Index(SDNode *N) {
4080   return isVEXTRACTIndex(N, 256);
4081 }
4082
4083 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4084   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4085   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4086     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4087
4088   uint64_t Index =
4089     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4090
4091   MVT VecVT = N->getOperand(0).getSimpleValueType();
4092   MVT ElVT = VecVT.getVectorElementType();
4093
4094   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4095   return Index / NumElemsPerChunk;
4096 }
4097
4098 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4099   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4100   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101     llvm_unreachable("Illegal insert subvector for VINSERT");
4102
4103   uint64_t Index =
4104     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106   MVT VecVT = N->getSimpleValueType(0);
4107   MVT ElVT = VecVT.getVectorElementType();
4108
4109   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4110   return Index / NumElemsPerChunk;
4111 }
4112
4113 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4114 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4115 /// and VINSERTI128 instructions.
4116 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4117   return getExtractVEXTRACTImmediate(N, 128);
4118 }
4119
4120 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4121 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4122 /// and VINSERTI64x4 instructions.
4123 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4124   return getExtractVEXTRACTImmediate(N, 256);
4125 }
4126
4127 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4128 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4129 /// and VINSERTI128 instructions.
4130 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4131   return getInsertVINSERTImmediate(N, 128);
4132 }
4133
4134 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4135 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4136 /// and VINSERTI64x4 instructions.
4137 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4138   return getInsertVINSERTImmediate(N, 256);
4139 }
4140
4141 /// isZero - Returns true if Elt is a constant integer zero
4142 static bool isZero(SDValue V) {
4143   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4144   return C && C->isNullValue();
4145 }
4146
4147 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4148 /// constant +0.0.
4149 bool X86::isZeroNode(SDValue Elt) {
4150   if (isZero(Elt))
4151     return true;
4152   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4153     return CFP->getValueAPF().isPosZero();
4154   return false;
4155 }
4156
4157 /// getZeroVector - Returns a vector of specified type with all zero elements.
4158 ///
4159 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4160                              SelectionDAG &DAG, SDLoc dl) {
4161   assert(VT.isVector() && "Expected a vector type");
4162
4163   // Always build SSE zero vectors as <4 x i32> bitcasted
4164   // to their dest type. This ensures they get CSE'd.
4165   SDValue Vec;
4166   if (VT.is128BitVector()) {  // SSE
4167     if (Subtarget->hasSSE2()) {  // SSE2
4168       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4169       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4170     } else { // SSE1
4171       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4172       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4173     }
4174   } else if (VT.is256BitVector()) { // AVX
4175     if (Subtarget->hasInt256()) { // AVX2
4176       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4177       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4178       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4179     } else {
4180       // 256-bit logic and arithmetic instructions in AVX are all
4181       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4182       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4183       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4184       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4185     }
4186   } else if (VT.is512BitVector()) { // AVX-512
4187       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4188       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4189                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4190       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4191   } else if (VT.getScalarType() == MVT::i1) {
4192
4193     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4194             && "Unexpected vector type");
4195     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4196             && "Unexpected vector type");
4197     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4198     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4199     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4200   } else
4201     llvm_unreachable("Unexpected vector type");
4202
4203   return DAG.getBitcast(VT, Vec);
4204 }
4205
4206 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4207                                 SelectionDAG &DAG, SDLoc dl,
4208                                 unsigned vectorWidth) {
4209   assert((vectorWidth == 128 || vectorWidth == 256) &&
4210          "Unsupported vector width");
4211   EVT VT = Vec.getValueType();
4212   EVT ElVT = VT.getVectorElementType();
4213   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4214   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4215                                   VT.getVectorNumElements()/Factor);
4216
4217   // Extract from UNDEF is UNDEF.
4218   if (Vec.getOpcode() == ISD::UNDEF)
4219     return DAG.getUNDEF(ResultVT);
4220
4221   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4222   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4223
4224   // This is the index of the first element of the vectorWidth-bit chunk
4225   // we want.
4226   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4227                                * ElemsPerChunk);
4228
4229   // If the input is a buildvector just emit a smaller one.
4230   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4231     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4232                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4233                                     ElemsPerChunk));
4234
4235   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4236   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4237 }
4238
4239 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4240 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4241 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4242 /// instructions or a simple subregister reference. Idx is an index in the
4243 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4244 /// lowering EXTRACT_VECTOR_ELT operations easier.
4245 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4246                                    SelectionDAG &DAG, SDLoc dl) {
4247   assert((Vec.getValueType().is256BitVector() ||
4248           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4249   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4250 }
4251
4252 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4253 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4254                                    SelectionDAG &DAG, SDLoc dl) {
4255   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4256   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4257 }
4258
4259 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4260                                unsigned IdxVal, SelectionDAG &DAG,
4261                                SDLoc dl, unsigned vectorWidth) {
4262   assert((vectorWidth == 128 || vectorWidth == 256) &&
4263          "Unsupported vector width");
4264   // Inserting UNDEF is Result
4265   if (Vec.getOpcode() == ISD::UNDEF)
4266     return Result;
4267   EVT VT = Vec.getValueType();
4268   EVT ElVT = VT.getVectorElementType();
4269   EVT ResultVT = Result.getValueType();
4270
4271   // Insert the relevant vectorWidth bits.
4272   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4273
4274   // This is the index of the first element of the vectorWidth-bit chunk
4275   // we want.
4276   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4277                                * ElemsPerChunk);
4278
4279   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4280   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4281 }
4282
4283 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4284 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4285 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4286 /// simple superregister reference.  Idx is an index in the 128 bits
4287 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4288 /// lowering INSERT_VECTOR_ELT operations easier.
4289 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4290                                   SelectionDAG &DAG, SDLoc dl) {
4291   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4292
4293   // For insertion into the zero index (low half) of a 256-bit vector, it is
4294   // more efficient to generate a blend with immediate instead of an insert*128.
4295   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4296   // extend the subvector to the size of the result vector. Make sure that
4297   // we are not recursing on that node by checking for undef here.
4298   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4299       Result.getOpcode() != ISD::UNDEF) {
4300     EVT ResultVT = Result.getValueType();
4301     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4302     SDValue Undef = DAG.getUNDEF(ResultVT);
4303     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4304                                  Vec, ZeroIndex);
4305
4306     // The blend instruction, and therefore its mask, depend on the data type.
4307     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4308     if (ScalarType.isFloatingPoint()) {
4309       // Choose either vblendps (float) or vblendpd (double).
4310       unsigned ScalarSize = ScalarType.getSizeInBits();
4311       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4312       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4313       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4314       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4315     }
4316
4317     const X86Subtarget &Subtarget =
4318     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4319
4320     // AVX2 is needed for 256-bit integer blend support.
4321     // Integers must be cast to 32-bit because there is only vpblendd;
4322     // vpblendw can't be used for this because it has a handicapped mask.
4323
4324     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4325     // is still more efficient than using the wrong domain vinsertf128 that
4326     // will be created by InsertSubVector().
4327     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4328
4329     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4330     Vec256 = DAG.getBitcast(CastVT, Vec256);
4331     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4332     return DAG.getBitcast(ResultVT, Vec256);
4333   }
4334
4335   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4336 }
4337
4338 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4339                                   SelectionDAG &DAG, SDLoc dl) {
4340   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4341   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4342 }
4343
4344 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4345 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4346 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4347 /// large BUILD_VECTORS.
4348 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4349                                    unsigned NumElems, SelectionDAG &DAG,
4350                                    SDLoc dl) {
4351   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4352   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4353 }
4354
4355 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4356                                    unsigned NumElems, SelectionDAG &DAG,
4357                                    SDLoc dl) {
4358   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4359   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4360 }
4361
4362 /// getOnesVector - Returns a vector of specified type with all bits set.
4363 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4364 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4365 /// Then bitcast to their original type, ensuring they get CSE'd.
4366 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4367                              SDLoc dl) {
4368   assert(VT.isVector() && "Expected a vector type");
4369
4370   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4371   SDValue Vec;
4372   if (VT.is256BitVector()) {
4373     if (HasInt256) { // AVX2
4374       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4375       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4376     } else { // AVX
4377       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4378       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4379     }
4380   } else if (VT.is128BitVector()) {
4381     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4382   } else
4383     llvm_unreachable("Unexpected vector type");
4384
4385   return DAG.getBitcast(VT, Vec);
4386 }
4387
4388 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4389 /// operation of specified width.
4390 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4391                        SDValue V2) {
4392   unsigned NumElems = VT.getVectorNumElements();
4393   SmallVector<int, 8> Mask;
4394   Mask.push_back(NumElems);
4395   for (unsigned i = 1; i != NumElems; ++i)
4396     Mask.push_back(i);
4397   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4398 }
4399
4400 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4401 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4402                           SDValue V2) {
4403   unsigned NumElems = VT.getVectorNumElements();
4404   SmallVector<int, 8> Mask;
4405   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4406     Mask.push_back(i);
4407     Mask.push_back(i + NumElems);
4408   }
4409   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4410 }
4411
4412 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4413 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4414                           SDValue V2) {
4415   unsigned NumElems = VT.getVectorNumElements();
4416   SmallVector<int, 8> Mask;
4417   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4418     Mask.push_back(i + Half);
4419     Mask.push_back(i + NumElems + Half);
4420   }
4421   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4422 }
4423
4424 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4425 /// vector of zero or undef vector.  This produces a shuffle where the low
4426 /// element of V2 is swizzled into the zero/undef vector, landing at element
4427 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4428 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4429                                            bool IsZero,
4430                                            const X86Subtarget *Subtarget,
4431                                            SelectionDAG &DAG) {
4432   MVT VT = V2.getSimpleValueType();
4433   SDValue V1 = IsZero
4434     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4435   unsigned NumElems = VT.getVectorNumElements();
4436   SmallVector<int, 16> MaskVec;
4437   for (unsigned i = 0; i != NumElems; ++i)
4438     // If this is the insertion idx, put the low elt of V2 here.
4439     MaskVec.push_back(i == Idx ? NumElems : i);
4440   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4441 }
4442
4443 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4444 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4445 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4446 /// shuffles which use a single input multiple times, and in those cases it will
4447 /// adjust the mask to only have indices within that single input.
4448 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4449 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4450                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4451   unsigned NumElems = VT.getVectorNumElements();
4452   SDValue ImmN;
4453
4454   IsUnary = false;
4455   bool IsFakeUnary = false;
4456   switch(N->getOpcode()) {
4457   case X86ISD::BLENDI:
4458     ImmN = N->getOperand(N->getNumOperands()-1);
4459     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4460     break;
4461   case X86ISD::SHUFP:
4462     ImmN = N->getOperand(N->getNumOperands()-1);
4463     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4464     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4465     break;
4466   case X86ISD::UNPCKH:
4467     DecodeUNPCKHMask(VT, Mask);
4468     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4469     break;
4470   case X86ISD::UNPCKL:
4471     DecodeUNPCKLMask(VT, Mask);
4472     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4473     break;
4474   case X86ISD::MOVHLPS:
4475     DecodeMOVHLPSMask(NumElems, Mask);
4476     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4477     break;
4478   case X86ISD::MOVLHPS:
4479     DecodeMOVLHPSMask(NumElems, Mask);
4480     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4481     break;
4482   case X86ISD::PALIGNR:
4483     ImmN = N->getOperand(N->getNumOperands()-1);
4484     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4485     break;
4486   case X86ISD::PSHUFD:
4487   case X86ISD::VPERMILPI:
4488     ImmN = N->getOperand(N->getNumOperands()-1);
4489     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4490     IsUnary = true;
4491     break;
4492   case X86ISD::PSHUFHW:
4493     ImmN = N->getOperand(N->getNumOperands()-1);
4494     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4495     IsUnary = true;
4496     break;
4497   case X86ISD::PSHUFLW:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     IsUnary = true;
4501     break;
4502   case X86ISD::PSHUFB: {
4503     IsUnary = true;
4504     SDValue MaskNode = N->getOperand(1);
4505     while (MaskNode->getOpcode() == ISD::BITCAST)
4506       MaskNode = MaskNode->getOperand(0);
4507
4508     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4509       // If we have a build-vector, then things are easy.
4510       EVT VT = MaskNode.getValueType();
4511       assert(VT.isVector() &&
4512              "Can't produce a non-vector with a build_vector!");
4513       if (!VT.isInteger())
4514         return false;
4515
4516       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4517
4518       SmallVector<uint64_t, 32> RawMask;
4519       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4520         SDValue Op = MaskNode->getOperand(i);
4521         if (Op->getOpcode() == ISD::UNDEF) {
4522           RawMask.push_back((uint64_t)SM_SentinelUndef);
4523           continue;
4524         }
4525         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4526         if (!CN)
4527           return false;
4528         APInt MaskElement = CN->getAPIntValue();
4529
4530         // We now have to decode the element which could be any integer size and
4531         // extract each byte of it.
4532         for (int j = 0; j < NumBytesPerElement; ++j) {
4533           // Note that this is x86 and so always little endian: the low byte is
4534           // the first byte of the mask.
4535           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4536           MaskElement = MaskElement.lshr(8);
4537         }
4538       }
4539       DecodePSHUFBMask(RawMask, Mask);
4540       break;
4541     }
4542
4543     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4544     if (!MaskLoad)
4545       return false;
4546
4547     SDValue Ptr = MaskLoad->getBasePtr();
4548     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4549         Ptr->getOpcode() == X86ISD::WrapperRIP)
4550       Ptr = Ptr->getOperand(0);
4551
4552     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4553     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4554       return false;
4555
4556     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4557       DecodePSHUFBMask(C, Mask);
4558       if (Mask.empty())
4559         return false;
4560       break;
4561     }
4562
4563     return false;
4564   }
4565   case X86ISD::VPERMI:
4566     ImmN = N->getOperand(N->getNumOperands()-1);
4567     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568     IsUnary = true;
4569     break;
4570   case X86ISD::MOVSS:
4571   case X86ISD::MOVSD:
4572     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4573     break;
4574   case X86ISD::VPERM2X128:
4575     ImmN = N->getOperand(N->getNumOperands()-1);
4576     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577     if (Mask.empty()) return false;
4578     // Mask only contains negative index if an element is zero.
4579     if (std::any_of(Mask.begin(), Mask.end(),
4580                     [](int M){ return M == SM_SentinelZero; }))
4581       return false;
4582     break;
4583   case X86ISD::MOVSLDUP:
4584     DecodeMOVSLDUPMask(VT, Mask);
4585     IsUnary = true;
4586     break;
4587   case X86ISD::MOVSHDUP:
4588     DecodeMOVSHDUPMask(VT, Mask);
4589     IsUnary = true;
4590     break;
4591   case X86ISD::MOVDDUP:
4592     DecodeMOVDDUPMask(VT, Mask);
4593     IsUnary = true;
4594     break;
4595   case X86ISD::MOVLHPD:
4596   case X86ISD::MOVLPD:
4597   case X86ISD::MOVLPS:
4598     // Not yet implemented
4599     return false;
4600   default: llvm_unreachable("unknown target shuffle node");
4601   }
4602
4603   // If we have a fake unary shuffle, the shuffle mask is spread across two
4604   // inputs that are actually the same node. Re-map the mask to always point
4605   // into the first input.
4606   if (IsFakeUnary)
4607     for (int &M : Mask)
4608       if (M >= (int)Mask.size())
4609         M -= Mask.size();
4610
4611   return true;
4612 }
4613
4614 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4615 /// element of the result of the vector shuffle.
4616 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4617                                    unsigned Depth) {
4618   if (Depth == 6)
4619     return SDValue();  // Limit search depth.
4620
4621   SDValue V = SDValue(N, 0);
4622   EVT VT = V.getValueType();
4623   unsigned Opcode = V.getOpcode();
4624
4625   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4626   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4627     int Elt = SV->getMaskElt(Index);
4628
4629     if (Elt < 0)
4630       return DAG.getUNDEF(VT.getVectorElementType());
4631
4632     unsigned NumElems = VT.getVectorNumElements();
4633     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4634                                          : SV->getOperand(1);
4635     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4636   }
4637
4638   // Recurse into target specific vector shuffles to find scalars.
4639   if (isTargetShuffle(Opcode)) {
4640     MVT ShufVT = V.getSimpleValueType();
4641     unsigned NumElems = ShufVT.getVectorNumElements();
4642     SmallVector<int, 16> ShuffleMask;
4643     bool IsUnary;
4644
4645     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4646       return SDValue();
4647
4648     int Elt = ShuffleMask[Index];
4649     if (Elt < 0)
4650       return DAG.getUNDEF(ShufVT.getVectorElementType());
4651
4652     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4653                                          : N->getOperand(1);
4654     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4655                                Depth+1);
4656   }
4657
4658   // Actual nodes that may contain scalar elements
4659   if (Opcode == ISD::BITCAST) {
4660     V = V.getOperand(0);
4661     EVT SrcVT = V.getValueType();
4662     unsigned NumElems = VT.getVectorNumElements();
4663
4664     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4665       return SDValue();
4666   }
4667
4668   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4669     return (Index == 0) ? V.getOperand(0)
4670                         : DAG.getUNDEF(VT.getVectorElementType());
4671
4672   if (V.getOpcode() == ISD::BUILD_VECTOR)
4673     return V.getOperand(Index);
4674
4675   return SDValue();
4676 }
4677
4678 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4679 ///
4680 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4681                                        unsigned NumNonZero, unsigned NumZero,
4682                                        SelectionDAG &DAG,
4683                                        const X86Subtarget* Subtarget,
4684                                        const TargetLowering &TLI) {
4685   if (NumNonZero > 8)
4686     return SDValue();
4687
4688   SDLoc dl(Op);
4689   SDValue V;
4690   bool First = true;
4691
4692   // SSE4.1 - use PINSRB to insert each byte directly.
4693   if (Subtarget->hasSSE41()) {
4694     for (unsigned i = 0; i < 16; ++i) {
4695       bool isNonZero = (NonZeros & (1 << i)) != 0;
4696       if (isNonZero) {
4697         if (First) {
4698           if (NumZero)
4699             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4700           else
4701             V = DAG.getUNDEF(MVT::v16i8);
4702           First = false;
4703         }
4704         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4705                         MVT::v16i8, V, Op.getOperand(i),
4706                         DAG.getIntPtrConstant(i, dl));
4707       }
4708     }
4709
4710     return V;
4711   }
4712
4713   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4714   for (unsigned i = 0; i < 16; ++i) {
4715     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4716     if (ThisIsNonZero && First) {
4717       if (NumZero)
4718         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4719       else
4720         V = DAG.getUNDEF(MVT::v8i16);
4721       First = false;
4722     }
4723
4724     if ((i & 1) != 0) {
4725       SDValue ThisElt, LastElt;
4726       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4727       if (LastIsNonZero) {
4728         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4729                               MVT::i16, Op.getOperand(i-1));
4730       }
4731       if (ThisIsNonZero) {
4732         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4733         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4734                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4735         if (LastIsNonZero)
4736           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4737       } else
4738         ThisElt = LastElt;
4739
4740       if (ThisElt.getNode())
4741         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4742                         DAG.getIntPtrConstant(i/2, dl));
4743     }
4744   }
4745
4746   return DAG.getBitcast(MVT::v16i8, V);
4747 }
4748
4749 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4750 ///
4751 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4752                                      unsigned NumNonZero, unsigned NumZero,
4753                                      SelectionDAG &DAG,
4754                                      const X86Subtarget* Subtarget,
4755                                      const TargetLowering &TLI) {
4756   if (NumNonZero > 4)
4757     return SDValue();
4758
4759   SDLoc dl(Op);
4760   SDValue V;
4761   bool First = true;
4762   for (unsigned i = 0; i < 8; ++i) {
4763     bool isNonZero = (NonZeros & (1 << i)) != 0;
4764     if (isNonZero) {
4765       if (First) {
4766         if (NumZero)
4767           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4768         else
4769           V = DAG.getUNDEF(MVT::v8i16);
4770         First = false;
4771       }
4772       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4773                       MVT::v8i16, V, Op.getOperand(i),
4774                       DAG.getIntPtrConstant(i, dl));
4775     }
4776   }
4777
4778   return V;
4779 }
4780
4781 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4782 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4783                                      const X86Subtarget *Subtarget,
4784                                      const TargetLowering &TLI) {
4785   // Find all zeroable elements.
4786   std::bitset<4> Zeroable;
4787   for (int i=0; i < 4; ++i) {
4788     SDValue Elt = Op->getOperand(i);
4789     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4790   }
4791   assert(Zeroable.size() - Zeroable.count() > 1 &&
4792          "We expect at least two non-zero elements!");
4793
4794   // We only know how to deal with build_vector nodes where elements are either
4795   // zeroable or extract_vector_elt with constant index.
4796   SDValue FirstNonZero;
4797   unsigned FirstNonZeroIdx;
4798   for (unsigned i=0; i < 4; ++i) {
4799     if (Zeroable[i])
4800       continue;
4801     SDValue Elt = Op->getOperand(i);
4802     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4803         !isa<ConstantSDNode>(Elt.getOperand(1)))
4804       return SDValue();
4805     // Make sure that this node is extracting from a 128-bit vector.
4806     MVT VT = Elt.getOperand(0).getSimpleValueType();
4807     if (!VT.is128BitVector())
4808       return SDValue();
4809     if (!FirstNonZero.getNode()) {
4810       FirstNonZero = Elt;
4811       FirstNonZeroIdx = i;
4812     }
4813   }
4814
4815   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4816   SDValue V1 = FirstNonZero.getOperand(0);
4817   MVT VT = V1.getSimpleValueType();
4818
4819   // See if this build_vector can be lowered as a blend with zero.
4820   SDValue Elt;
4821   unsigned EltMaskIdx, EltIdx;
4822   int Mask[4];
4823   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4824     if (Zeroable[EltIdx]) {
4825       // The zero vector will be on the right hand side.
4826       Mask[EltIdx] = EltIdx+4;
4827       continue;
4828     }
4829
4830     Elt = Op->getOperand(EltIdx);
4831     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4832     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4833     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4834       break;
4835     Mask[EltIdx] = EltIdx;
4836   }
4837
4838   if (EltIdx == 4) {
4839     // Let the shuffle legalizer deal with blend operations.
4840     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4841     if (V1.getSimpleValueType() != VT)
4842       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4843     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4844   }
4845
4846   // See if we can lower this build_vector to a INSERTPS.
4847   if (!Subtarget->hasSSE41())
4848     return SDValue();
4849
4850   SDValue V2 = Elt.getOperand(0);
4851   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4852     V1 = SDValue();
4853
4854   bool CanFold = true;
4855   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4856     if (Zeroable[i])
4857       continue;
4858
4859     SDValue Current = Op->getOperand(i);
4860     SDValue SrcVector = Current->getOperand(0);
4861     if (!V1.getNode())
4862       V1 = SrcVector;
4863     CanFold = SrcVector == V1 &&
4864       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4865   }
4866
4867   if (!CanFold)
4868     return SDValue();
4869
4870   assert(V1.getNode() && "Expected at least two non-zero elements!");
4871   if (V1.getSimpleValueType() != MVT::v4f32)
4872     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4873   if (V2.getSimpleValueType() != MVT::v4f32)
4874     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4875
4876   // Ok, we can emit an INSERTPS instruction.
4877   unsigned ZMask = Zeroable.to_ulong();
4878
4879   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4880   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4881   SDLoc DL(Op);
4882   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4883                                DAG.getIntPtrConstant(InsertPSMask, DL));
4884   return DAG.getBitcast(VT, Result);
4885 }
4886
4887 /// Return a vector logical shift node.
4888 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4889                          unsigned NumBits, SelectionDAG &DAG,
4890                          const TargetLowering &TLI, SDLoc dl) {
4891   assert(VT.is128BitVector() && "Unknown type for VShift");
4892   MVT ShVT = MVT::v2i64;
4893   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4894   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4895   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4896   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4897   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4898   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4899 }
4900
4901 static SDValue
4902 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4903
4904   // Check if the scalar load can be widened into a vector load. And if
4905   // the address is "base + cst" see if the cst can be "absorbed" into
4906   // the shuffle mask.
4907   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4908     SDValue Ptr = LD->getBasePtr();
4909     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4910       return SDValue();
4911     EVT PVT = LD->getValueType(0);
4912     if (PVT != MVT::i32 && PVT != MVT::f32)
4913       return SDValue();
4914
4915     int FI = -1;
4916     int64_t Offset = 0;
4917     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4918       FI = FINode->getIndex();
4919       Offset = 0;
4920     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4921                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4922       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4923       Offset = Ptr.getConstantOperandVal(1);
4924       Ptr = Ptr.getOperand(0);
4925     } else {
4926       return SDValue();
4927     }
4928
4929     // FIXME: 256-bit vector instructions don't require a strict alignment,
4930     // improve this code to support it better.
4931     unsigned RequiredAlign = VT.getSizeInBits()/8;
4932     SDValue Chain = LD->getChain();
4933     // Make sure the stack object alignment is at least 16 or 32.
4934     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4935     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4936       if (MFI->isFixedObjectIndex(FI)) {
4937         // Can't change the alignment. FIXME: It's possible to compute
4938         // the exact stack offset and reference FI + adjust offset instead.
4939         // If someone *really* cares about this. That's the way to implement it.
4940         return SDValue();
4941       } else {
4942         MFI->setObjectAlignment(FI, RequiredAlign);
4943       }
4944     }
4945
4946     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4947     // Ptr + (Offset & ~15).
4948     if (Offset < 0)
4949       return SDValue();
4950     if ((Offset % RequiredAlign) & 3)
4951       return SDValue();
4952     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4953     if (StartOffset) {
4954       SDLoc DL(Ptr);
4955       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4956                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4957     }
4958
4959     int EltNo = (Offset - StartOffset) >> 2;
4960     unsigned NumElems = VT.getVectorNumElements();
4961
4962     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4963     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4964                              LD->getPointerInfo().getWithOffset(StartOffset),
4965                              false, false, false, 0);
4966
4967     SmallVector<int, 8> Mask(NumElems, EltNo);
4968
4969     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4970   }
4971
4972   return SDValue();
4973 }
4974
4975 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4976 /// elements can be replaced by a single large load which has the same value as
4977 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4978 ///
4979 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4980 ///
4981 /// FIXME: we'd also like to handle the case where the last elements are zero
4982 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4983 /// There's even a handy isZeroNode for that purpose.
4984 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4985                                         SDLoc &DL, SelectionDAG &DAG,
4986                                         bool isAfterLegalize) {
4987   unsigned NumElems = Elts.size();
4988
4989   LoadSDNode *LDBase = nullptr;
4990   unsigned LastLoadedElt = -1U;
4991
4992   // For each element in the initializer, see if we've found a load or an undef.
4993   // If we don't find an initial load element, or later load elements are
4994   // non-consecutive, bail out.
4995   for (unsigned i = 0; i < NumElems; ++i) {
4996     SDValue Elt = Elts[i];
4997     // Look through a bitcast.
4998     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4999       Elt = Elt.getOperand(0);
5000     if (!Elt.getNode() ||
5001         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5002       return SDValue();
5003     if (!LDBase) {
5004       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5005         return SDValue();
5006       LDBase = cast<LoadSDNode>(Elt.getNode());
5007       LastLoadedElt = i;
5008       continue;
5009     }
5010     if (Elt.getOpcode() == ISD::UNDEF)
5011       continue;
5012
5013     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5014     EVT LdVT = Elt.getValueType();
5015     // Each loaded element must be the correct fractional portion of the
5016     // requested vector load.
5017     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5018       return SDValue();
5019     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5020       return SDValue();
5021     LastLoadedElt = i;
5022   }
5023
5024   // If we have found an entire vector of loads and undefs, then return a large
5025   // load of the entire vector width starting at the base pointer.  If we found
5026   // consecutive loads for the low half, generate a vzext_load node.
5027   if (LastLoadedElt == NumElems - 1) {
5028     assert(LDBase && "Did not find base load for merging consecutive loads");
5029     EVT EltVT = LDBase->getValueType(0);
5030     // Ensure that the input vector size for the merged loads matches the
5031     // cumulative size of the input elements.
5032     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5033       return SDValue();
5034
5035     if (isAfterLegalize &&
5036         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5037       return SDValue();
5038
5039     SDValue NewLd = SDValue();
5040
5041     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5042                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5043                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5044                         LDBase->getAlignment());
5045
5046     if (LDBase->hasAnyUseOfValue(1)) {
5047       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5048                                      SDValue(LDBase, 1),
5049                                      SDValue(NewLd.getNode(), 1));
5050       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5051       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5052                              SDValue(NewLd.getNode(), 1));
5053     }
5054
5055     return NewLd;
5056   }
5057
5058   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5059   //of a v4i32 / v4f32. It's probably worth generalizing.
5060   EVT EltVT = VT.getVectorElementType();
5061   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5062       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5063     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5064     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5065     SDValue ResNode =
5066         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5067                                 LDBase->getPointerInfo(),
5068                                 LDBase->getAlignment(),
5069                                 false/*isVolatile*/, true/*ReadMem*/,
5070                                 false/*WriteMem*/);
5071
5072     // Make sure the newly-created LOAD is in the same position as LDBase in
5073     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5074     // update uses of LDBase's output chain to use the TokenFactor.
5075     if (LDBase->hasAnyUseOfValue(1)) {
5076       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5077                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5078       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5079       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5080                              SDValue(ResNode.getNode(), 1));
5081     }
5082
5083     return DAG.getBitcast(VT, ResNode);
5084   }
5085   return SDValue();
5086 }
5087
5088 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5089 /// to generate a splat value for the following cases:
5090 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5091 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5092 /// a scalar load, or a constant.
5093 /// The VBROADCAST node is returned when a pattern is found,
5094 /// or SDValue() otherwise.
5095 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5096                                     SelectionDAG &DAG) {
5097   // VBROADCAST requires AVX.
5098   // TODO: Splats could be generated for non-AVX CPUs using SSE
5099   // instructions, but there's less potential gain for only 128-bit vectors.
5100   if (!Subtarget->hasAVX())
5101     return SDValue();
5102
5103   MVT VT = Op.getSimpleValueType();
5104   SDLoc dl(Op);
5105
5106   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5107          "Unsupported vector type for broadcast.");
5108
5109   SDValue Ld;
5110   bool ConstSplatVal;
5111
5112   switch (Op.getOpcode()) {
5113     default:
5114       // Unknown pattern found.
5115       return SDValue();
5116
5117     case ISD::BUILD_VECTOR: {
5118       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5119       BitVector UndefElements;
5120       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5121
5122       // We need a splat of a single value to use broadcast, and it doesn't
5123       // make any sense if the value is only in one element of the vector.
5124       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5125         return SDValue();
5126
5127       Ld = Splat;
5128       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5129                        Ld.getOpcode() == ISD::ConstantFP);
5130
5131       // Make sure that all of the users of a non-constant load are from the
5132       // BUILD_VECTOR node.
5133       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5134         return SDValue();
5135       break;
5136     }
5137
5138     case ISD::VECTOR_SHUFFLE: {
5139       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5140
5141       // Shuffles must have a splat mask where the first element is
5142       // broadcasted.
5143       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5144         return SDValue();
5145
5146       SDValue Sc = Op.getOperand(0);
5147       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5148           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5149
5150         if (!Subtarget->hasInt256())
5151           return SDValue();
5152
5153         // Use the register form of the broadcast instruction available on AVX2.
5154         if (VT.getSizeInBits() >= 256)
5155           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5156         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5157       }
5158
5159       Ld = Sc.getOperand(0);
5160       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5161                        Ld.getOpcode() == ISD::ConstantFP);
5162
5163       // The scalar_to_vector node and the suspected
5164       // load node must have exactly one user.
5165       // Constants may have multiple users.
5166
5167       // AVX-512 has register version of the broadcast
5168       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5169         Ld.getValueType().getSizeInBits() >= 32;
5170       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5171           !hasRegVer))
5172         return SDValue();
5173       break;
5174     }
5175   }
5176
5177   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5178   bool IsGE256 = (VT.getSizeInBits() >= 256);
5179
5180   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5181   // instruction to save 8 or more bytes of constant pool data.
5182   // TODO: If multiple splats are generated to load the same constant,
5183   // it may be detrimental to overall size. There needs to be a way to detect
5184   // that condition to know if this is truly a size win.
5185   const Function *F = DAG.getMachineFunction().getFunction();
5186   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5187
5188   // Handle broadcasting a single constant scalar from the constant pool
5189   // into a vector.
5190   // On Sandybridge (no AVX2), it is still better to load a constant vector
5191   // from the constant pool and not to broadcast it from a scalar.
5192   // But override that restriction when optimizing for size.
5193   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5194   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5195     EVT CVT = Ld.getValueType();
5196     assert(!CVT.isVector() && "Must not broadcast a vector type");
5197
5198     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5199     // For size optimization, also splat v2f64 and v2i64, and for size opt
5200     // with AVX2, also splat i8 and i16.
5201     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5202     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5203         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5204       const Constant *C = nullptr;
5205       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5206         C = CI->getConstantIntValue();
5207       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5208         C = CF->getConstantFPValue();
5209
5210       assert(C && "Invalid constant type");
5211
5212       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5213       SDValue CP =
5214           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5215       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5216       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5217                        MachinePointerInfo::getConstantPool(),
5218                        false, false, false, Alignment);
5219
5220       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5221     }
5222   }
5223
5224   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5225
5226   // Handle AVX2 in-register broadcasts.
5227   if (!IsLoad && Subtarget->hasInt256() &&
5228       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5229     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5230
5231   // The scalar source must be a normal load.
5232   if (!IsLoad)
5233     return SDValue();
5234
5235   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5236       (Subtarget->hasVLX() && ScalarSize == 64))
5237     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238
5239   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5240   // double since there is no vbroadcastsd xmm
5241   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5242     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5243       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5244   }
5245
5246   // Unsupported broadcast.
5247   return SDValue();
5248 }
5249
5250 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5251 /// underlying vector and index.
5252 ///
5253 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5254 /// index.
5255 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5256                                          SDValue ExtIdx) {
5257   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5258   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5259     return Idx;
5260
5261   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5262   // lowered this:
5263   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5264   // to:
5265   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5266   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5267   //                           undef)
5268   //                       Constant<0>)
5269   // In this case the vector is the extract_subvector expression and the index
5270   // is 2, as specified by the shuffle.
5271   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5272   SDValue ShuffleVec = SVOp->getOperand(0);
5273   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5274   assert(ShuffleVecVT.getVectorElementType() ==
5275          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5276
5277   int ShuffleIdx = SVOp->getMaskElt(Idx);
5278   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5279     ExtractedFromVec = ShuffleVec;
5280     return ShuffleIdx;
5281   }
5282   return Idx;
5283 }
5284
5285 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5286   MVT VT = Op.getSimpleValueType();
5287
5288   // Skip if insert_vec_elt is not supported.
5289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5290   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5291     return SDValue();
5292
5293   SDLoc DL(Op);
5294   unsigned NumElems = Op.getNumOperands();
5295
5296   SDValue VecIn1;
5297   SDValue VecIn2;
5298   SmallVector<unsigned, 4> InsertIndices;
5299   SmallVector<int, 8> Mask(NumElems, -1);
5300
5301   for (unsigned i = 0; i != NumElems; ++i) {
5302     unsigned Opc = Op.getOperand(i).getOpcode();
5303
5304     if (Opc == ISD::UNDEF)
5305       continue;
5306
5307     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5308       // Quit if more than 1 elements need inserting.
5309       if (InsertIndices.size() > 1)
5310         return SDValue();
5311
5312       InsertIndices.push_back(i);
5313       continue;
5314     }
5315
5316     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5317     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5318     // Quit if non-constant index.
5319     if (!isa<ConstantSDNode>(ExtIdx))
5320       return SDValue();
5321     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5322
5323     // Quit if extracted from vector of different type.
5324     if (ExtractedFromVec.getValueType() != VT)
5325       return SDValue();
5326
5327     if (!VecIn1.getNode())
5328       VecIn1 = ExtractedFromVec;
5329     else if (VecIn1 != ExtractedFromVec) {
5330       if (!VecIn2.getNode())
5331         VecIn2 = ExtractedFromVec;
5332       else if (VecIn2 != ExtractedFromVec)
5333         // Quit if more than 2 vectors to shuffle
5334         return SDValue();
5335     }
5336
5337     if (ExtractedFromVec == VecIn1)
5338       Mask[i] = Idx;
5339     else if (ExtractedFromVec == VecIn2)
5340       Mask[i] = Idx + NumElems;
5341   }
5342
5343   if (!VecIn1.getNode())
5344     return SDValue();
5345
5346   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5347   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5348   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5349     unsigned Idx = InsertIndices[i];
5350     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5351                      DAG.getIntPtrConstant(Idx, DL));
5352   }
5353
5354   return NV;
5355 }
5356
5357 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5358   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5359          Op.getScalarValueSizeInBits() == 1 &&
5360          "Can not convert non-constant vector");
5361   uint64_t Immediate = 0;
5362   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5363     SDValue In = Op.getOperand(idx);
5364     if (In.getOpcode() != ISD::UNDEF)
5365       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5366   }
5367   SDLoc dl(Op);
5368   MVT VT =
5369    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5370   return DAG.getConstant(Immediate, dl, VT);
5371 }
5372 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5373 SDValue
5374 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5375
5376   MVT VT = Op.getSimpleValueType();
5377   assert((VT.getVectorElementType() == MVT::i1) &&
5378          "Unexpected type in LowerBUILD_VECTORvXi1!");
5379
5380   SDLoc dl(Op);
5381   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5382     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5383     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5384     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5385   }
5386
5387   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5388     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5389     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5390     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5391   }
5392
5393   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5394     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5395     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5396       return DAG.getBitcast(VT, Imm);
5397     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5398     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5399                         DAG.getIntPtrConstant(0, dl));
5400   }
5401
5402   // Vector has one or more non-const elements
5403   uint64_t Immediate = 0;
5404   SmallVector<unsigned, 16> NonConstIdx;
5405   bool IsSplat = true;
5406   bool HasConstElts = false;
5407   int SplatIdx = -1;
5408   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5409     SDValue In = Op.getOperand(idx);
5410     if (In.getOpcode() == ISD::UNDEF)
5411       continue;
5412     if (!isa<ConstantSDNode>(In))
5413       NonConstIdx.push_back(idx);
5414     else {
5415       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5416       HasConstElts = true;
5417     }
5418     if (SplatIdx == -1)
5419       SplatIdx = idx;
5420     else if (In != Op.getOperand(SplatIdx))
5421       IsSplat = false;
5422   }
5423
5424   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5425   if (IsSplat)
5426     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5427                        DAG.getConstant(1, dl, VT),
5428                        DAG.getConstant(0, dl, VT));
5429
5430   // insert elements one by one
5431   SDValue DstVec;
5432   SDValue Imm;
5433   if (Immediate) {
5434     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5435     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5436   }
5437   else if (HasConstElts)
5438     Imm = DAG.getConstant(0, dl, VT);
5439   else
5440     Imm = DAG.getUNDEF(VT);
5441   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5442     DstVec = DAG.getBitcast(VT, Imm);
5443   else {
5444     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5445     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5446                          DAG.getIntPtrConstant(0, dl));
5447   }
5448
5449   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5450     unsigned InsertIdx = NonConstIdx[i];
5451     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5452                          Op.getOperand(InsertIdx),
5453                          DAG.getIntPtrConstant(InsertIdx, dl));
5454   }
5455   return DstVec;
5456 }
5457
5458 /// \brief Return true if \p N implements a horizontal binop and return the
5459 /// operands for the horizontal binop into V0 and V1.
5460 ///
5461 /// This is a helper function of LowerToHorizontalOp().
5462 /// This function checks that the build_vector \p N in input implements a
5463 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5464 /// operation to match.
5465 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5466 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5467 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5468 /// arithmetic sub.
5469 ///
5470 /// This function only analyzes elements of \p N whose indices are
5471 /// in range [BaseIdx, LastIdx).
5472 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5473                               SelectionDAG &DAG,
5474                               unsigned BaseIdx, unsigned LastIdx,
5475                               SDValue &V0, SDValue &V1) {
5476   EVT VT = N->getValueType(0);
5477
5478   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5479   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5480          "Invalid Vector in input!");
5481
5482   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5483   bool CanFold = true;
5484   unsigned ExpectedVExtractIdx = BaseIdx;
5485   unsigned NumElts = LastIdx - BaseIdx;
5486   V0 = DAG.getUNDEF(VT);
5487   V1 = DAG.getUNDEF(VT);
5488
5489   // Check if N implements a horizontal binop.
5490   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5491     SDValue Op = N->getOperand(i + BaseIdx);
5492
5493     // Skip UNDEFs.
5494     if (Op->getOpcode() == ISD::UNDEF) {
5495       // Update the expected vector extract index.
5496       if (i * 2 == NumElts)
5497         ExpectedVExtractIdx = BaseIdx;
5498       ExpectedVExtractIdx += 2;
5499       continue;
5500     }
5501
5502     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5503
5504     if (!CanFold)
5505       break;
5506
5507     SDValue Op0 = Op.getOperand(0);
5508     SDValue Op1 = Op.getOperand(1);
5509
5510     // Try to match the following pattern:
5511     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5512     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5513         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5514         Op0.getOperand(0) == Op1.getOperand(0) &&
5515         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5516         isa<ConstantSDNode>(Op1.getOperand(1)));
5517     if (!CanFold)
5518       break;
5519
5520     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5521     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5522
5523     if (i * 2 < NumElts) {
5524       if (V0.getOpcode() == ISD::UNDEF) {
5525         V0 = Op0.getOperand(0);
5526         if (V0.getValueType() != VT)
5527           return false;
5528       }
5529     } else {
5530       if (V1.getOpcode() == ISD::UNDEF) {
5531         V1 = Op0.getOperand(0);
5532         if (V1.getValueType() != VT)
5533           return false;
5534       }
5535       if (i * 2 == NumElts)
5536         ExpectedVExtractIdx = BaseIdx;
5537     }
5538
5539     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5540     if (I0 == ExpectedVExtractIdx)
5541       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5542     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5543       // Try to match the following dag sequence:
5544       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5545       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5546     } else
5547       CanFold = false;
5548
5549     ExpectedVExtractIdx += 2;
5550   }
5551
5552   return CanFold;
5553 }
5554
5555 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5556 /// a concat_vector.
5557 ///
5558 /// This is a helper function of LowerToHorizontalOp().
5559 /// This function expects two 256-bit vectors called V0 and V1.
5560 /// At first, each vector is split into two separate 128-bit vectors.
5561 /// Then, the resulting 128-bit vectors are used to implement two
5562 /// horizontal binary operations.
5563 ///
5564 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5565 ///
5566 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5567 /// the two new horizontal binop.
5568 /// When Mode is set, the first horizontal binop dag node would take as input
5569 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5570 /// horizontal binop dag node would take as input the lower 128-bit of V1
5571 /// and the upper 128-bit of V1.
5572 ///   Example:
5573 ///     HADD V0_LO, V0_HI
5574 ///     HADD V1_LO, V1_HI
5575 ///
5576 /// Otherwise, the first horizontal binop dag node takes as input the lower
5577 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5578 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5579 ///   Example:
5580 ///     HADD V0_LO, V1_LO
5581 ///     HADD V0_HI, V1_HI
5582 ///
5583 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5584 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5585 /// the upper 128-bits of the result.
5586 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5587                                      SDLoc DL, SelectionDAG &DAG,
5588                                      unsigned X86Opcode, bool Mode,
5589                                      bool isUndefLO, bool isUndefHI) {
5590   EVT VT = V0.getValueType();
5591   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5592          "Invalid nodes in input!");
5593
5594   unsigned NumElts = VT.getVectorNumElements();
5595   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5596   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5597   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5598   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5599   EVT NewVT = V0_LO.getValueType();
5600
5601   SDValue LO = DAG.getUNDEF(NewVT);
5602   SDValue HI = DAG.getUNDEF(NewVT);
5603
5604   if (Mode) {
5605     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5606     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5607       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5608     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5609       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5610   } else {
5611     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5612     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5613                        V1_LO->getOpcode() != ISD::UNDEF))
5614       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5615
5616     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5617                        V1_HI->getOpcode() != ISD::UNDEF))
5618       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5619   }
5620
5621   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5622 }
5623
5624 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5625 /// node.
5626 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5627                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5628   EVT VT = BV->getValueType(0);
5629   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5630       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5631     return SDValue();
5632
5633   SDLoc DL(BV);
5634   unsigned NumElts = VT.getVectorNumElements();
5635   SDValue InVec0 = DAG.getUNDEF(VT);
5636   SDValue InVec1 = DAG.getUNDEF(VT);
5637
5638   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5639           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5640
5641   // Odd-numbered elements in the input build vector are obtained from
5642   // adding two integer/float elements.
5643   // Even-numbered elements in the input build vector are obtained from
5644   // subtracting two integer/float elements.
5645   unsigned ExpectedOpcode = ISD::FSUB;
5646   unsigned NextExpectedOpcode = ISD::FADD;
5647   bool AddFound = false;
5648   bool SubFound = false;
5649
5650   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5651     SDValue Op = BV->getOperand(i);
5652
5653     // Skip 'undef' values.
5654     unsigned Opcode = Op.getOpcode();
5655     if (Opcode == ISD::UNDEF) {
5656       std::swap(ExpectedOpcode, NextExpectedOpcode);
5657       continue;
5658     }
5659
5660     // Early exit if we found an unexpected opcode.
5661     if (Opcode != ExpectedOpcode)
5662       return SDValue();
5663
5664     SDValue Op0 = Op.getOperand(0);
5665     SDValue Op1 = Op.getOperand(1);
5666
5667     // Try to match the following pattern:
5668     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5669     // Early exit if we cannot match that sequence.
5670     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5671         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5672         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5673         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5674         Op0.getOperand(1) != Op1.getOperand(1))
5675       return SDValue();
5676
5677     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5678     if (I0 != i)
5679       return SDValue();
5680
5681     // We found a valid add/sub node. Update the information accordingly.
5682     if (i & 1)
5683       AddFound = true;
5684     else
5685       SubFound = true;
5686
5687     // Update InVec0 and InVec1.
5688     if (InVec0.getOpcode() == ISD::UNDEF) {
5689       InVec0 = Op0.getOperand(0);
5690       if (InVec0.getValueType() != VT)
5691         return SDValue();
5692     }
5693     if (InVec1.getOpcode() == ISD::UNDEF) {
5694       InVec1 = Op1.getOperand(0);
5695       if (InVec1.getValueType() != VT)
5696         return SDValue();
5697     }
5698
5699     // Make sure that operands in input to each add/sub node always
5700     // come from a same pair of vectors.
5701     if (InVec0 != Op0.getOperand(0)) {
5702       if (ExpectedOpcode == ISD::FSUB)
5703         return SDValue();
5704
5705       // FADD is commutable. Try to commute the operands
5706       // and then test again.
5707       std::swap(Op0, Op1);
5708       if (InVec0 != Op0.getOperand(0))
5709         return SDValue();
5710     }
5711
5712     if (InVec1 != Op1.getOperand(0))
5713       return SDValue();
5714
5715     // Update the pair of expected opcodes.
5716     std::swap(ExpectedOpcode, NextExpectedOpcode);
5717   }
5718
5719   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5720   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5721       InVec1.getOpcode() != ISD::UNDEF)
5722     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5723
5724   return SDValue();
5725 }
5726
5727 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5728 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5729                                    const X86Subtarget *Subtarget,
5730                                    SelectionDAG &DAG) {
5731   EVT VT = BV->getValueType(0);
5732   unsigned NumElts = VT.getVectorNumElements();
5733   unsigned NumUndefsLO = 0;
5734   unsigned NumUndefsHI = 0;
5735   unsigned Half = NumElts/2;
5736
5737   // Count the number of UNDEF operands in the build_vector in input.
5738   for (unsigned i = 0, e = Half; i != e; ++i)
5739     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5740       NumUndefsLO++;
5741
5742   for (unsigned i = Half, e = NumElts; i != e; ++i)
5743     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5744       NumUndefsHI++;
5745
5746   // Early exit if this is either a build_vector of all UNDEFs or all the
5747   // operands but one are UNDEF.
5748   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5749     return SDValue();
5750
5751   SDLoc DL(BV);
5752   SDValue InVec0, InVec1;
5753   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5754     // Try to match an SSE3 float HADD/HSUB.
5755     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5756       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5757
5758     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5759       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5760   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5761     // Try to match an SSSE3 integer HADD/HSUB.
5762     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5763       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5764
5765     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5766       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5767   }
5768
5769   if (!Subtarget->hasAVX())
5770     return SDValue();
5771
5772   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5773     // Try to match an AVX horizontal add/sub of packed single/double
5774     // precision floating point values from 256-bit vectors.
5775     SDValue InVec2, InVec3;
5776     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5777         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5778         ((InVec0.getOpcode() == ISD::UNDEF ||
5779           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5780         ((InVec1.getOpcode() == ISD::UNDEF ||
5781           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5782       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5783
5784     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5785         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5786         ((InVec0.getOpcode() == ISD::UNDEF ||
5787           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5788         ((InVec1.getOpcode() == ISD::UNDEF ||
5789           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5790       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5791   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5792     // Try to match an AVX2 horizontal add/sub of signed integers.
5793     SDValue InVec2, InVec3;
5794     unsigned X86Opcode;
5795     bool CanFold = true;
5796
5797     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5798         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5799         ((InVec0.getOpcode() == ISD::UNDEF ||
5800           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5801         ((InVec1.getOpcode() == ISD::UNDEF ||
5802           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5803       X86Opcode = X86ISD::HADD;
5804     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5805         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5806         ((InVec0.getOpcode() == ISD::UNDEF ||
5807           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5808         ((InVec1.getOpcode() == ISD::UNDEF ||
5809           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5810       X86Opcode = X86ISD::HSUB;
5811     else
5812       CanFold = false;
5813
5814     if (CanFold) {
5815       // Fold this build_vector into a single horizontal add/sub.
5816       // Do this only if the target has AVX2.
5817       if (Subtarget->hasAVX2())
5818         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5819
5820       // Do not try to expand this build_vector into a pair of horizontal
5821       // add/sub if we can emit a pair of scalar add/sub.
5822       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5823         return SDValue();
5824
5825       // Convert this build_vector into a pair of horizontal binop followed by
5826       // a concat vector.
5827       bool isUndefLO = NumUndefsLO == Half;
5828       bool isUndefHI = NumUndefsHI == Half;
5829       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5830                                    isUndefLO, isUndefHI);
5831     }
5832   }
5833
5834   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5835        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5836     unsigned X86Opcode;
5837     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5838       X86Opcode = X86ISD::HADD;
5839     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5840       X86Opcode = X86ISD::HSUB;
5841     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5842       X86Opcode = X86ISD::FHADD;
5843     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5844       X86Opcode = X86ISD::FHSUB;
5845     else
5846       return SDValue();
5847
5848     // Don't try to expand this build_vector into a pair of horizontal add/sub
5849     // if we can simply emit a pair of scalar add/sub.
5850     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5851       return SDValue();
5852
5853     // Convert this build_vector into two horizontal add/sub followed by
5854     // a concat vector.
5855     bool isUndefLO = NumUndefsLO == Half;
5856     bool isUndefHI = NumUndefsHI == Half;
5857     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5858                                  isUndefLO, isUndefHI);
5859   }
5860
5861   return SDValue();
5862 }
5863
5864 SDValue
5865 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5866   SDLoc dl(Op);
5867
5868   MVT VT = Op.getSimpleValueType();
5869   MVT ExtVT = VT.getVectorElementType();
5870   unsigned NumElems = Op.getNumOperands();
5871
5872   // Generate vectors for predicate vectors.
5873   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5874     return LowerBUILD_VECTORvXi1(Op, DAG);
5875
5876   // Vectors containing all zeros can be matched by pxor and xorps later
5877   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5878     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5879     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5880     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5881       return Op;
5882
5883     return getZeroVector(VT, Subtarget, DAG, dl);
5884   }
5885
5886   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5887   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5888   // vpcmpeqd on 256-bit vectors.
5889   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5890     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5891       return Op;
5892
5893     if (!VT.is512BitVector())
5894       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5895   }
5896
5897   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5898   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5899     return AddSub;
5900   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5901     return HorizontalOp;
5902   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5903     return Broadcast;
5904
5905   unsigned EVTBits = ExtVT.getSizeInBits();
5906
5907   unsigned NumZero  = 0;
5908   unsigned NumNonZero = 0;
5909   unsigned NonZeros = 0;
5910   bool IsAllConstants = true;
5911   SmallSet<SDValue, 8> Values;
5912   for (unsigned i = 0; i < NumElems; ++i) {
5913     SDValue Elt = Op.getOperand(i);
5914     if (Elt.getOpcode() == ISD::UNDEF)
5915       continue;
5916     Values.insert(Elt);
5917     if (Elt.getOpcode() != ISD::Constant &&
5918         Elt.getOpcode() != ISD::ConstantFP)
5919       IsAllConstants = false;
5920     if (X86::isZeroNode(Elt))
5921       NumZero++;
5922     else {
5923       NonZeros |= (1 << i);
5924       NumNonZero++;
5925     }
5926   }
5927
5928   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5929   if (NumNonZero == 0)
5930     return DAG.getUNDEF(VT);
5931
5932   // Special case for single non-zero, non-undef, element.
5933   if (NumNonZero == 1) {
5934     unsigned Idx = countTrailingZeros(NonZeros);
5935     SDValue Item = Op.getOperand(Idx);
5936
5937     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5938     // the value are obviously zero, truncate the value to i32 and do the
5939     // insertion that way.  Only do this if the value is non-constant or if the
5940     // value is a constant being inserted into element 0.  It is cheaper to do
5941     // a constant pool load than it is to do a movd + shuffle.
5942     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5943         (!IsAllConstants || Idx == 0)) {
5944       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5945         // Handle SSE only.
5946         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5947         EVT VecVT = MVT::v4i32;
5948
5949         // Truncate the value (which may itself be a constant) to i32, and
5950         // convert it to a vector with movd (S2V+shuffle to zero extend).
5951         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5952         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5953         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5954                                       Item, Idx * 2, true, Subtarget, DAG));
5955       }
5956     }
5957
5958     // If we have a constant or non-constant insertion into the low element of
5959     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5960     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5961     // depending on what the source datatype is.
5962     if (Idx == 0) {
5963       if (NumZero == 0)
5964         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5965
5966       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5967           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5968         if (VT.is512BitVector()) {
5969           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5970           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5971                              Item, DAG.getIntPtrConstant(0, dl));
5972         }
5973         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5974                "Expected an SSE value type!");
5975         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5976         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5977         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5978       }
5979
5980       // We can't directly insert an i8 or i16 into a vector, so zero extend
5981       // it to i32 first.
5982       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5983         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5984         if (VT.is256BitVector()) {
5985           if (Subtarget->hasAVX()) {
5986             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5987             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5988           } else {
5989             // Without AVX, we need to extend to a 128-bit vector and then
5990             // insert into the 256-bit vector.
5991             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5992             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5993             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5994           }
5995         } else {
5996           assert(VT.is128BitVector() && "Expected an SSE value type!");
5997           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5998           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5999         }
6000         return DAG.getBitcast(VT, Item);
6001       }
6002     }
6003
6004     // Is it a vector logical left shift?
6005     if (NumElems == 2 && Idx == 1 &&
6006         X86::isZeroNode(Op.getOperand(0)) &&
6007         !X86::isZeroNode(Op.getOperand(1))) {
6008       unsigned NumBits = VT.getSizeInBits();
6009       return getVShift(true, VT,
6010                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6011                                    VT, Op.getOperand(1)),
6012                        NumBits/2, DAG, *this, dl);
6013     }
6014
6015     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6016       return SDValue();
6017
6018     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6019     // is a non-constant being inserted into an element other than the low one,
6020     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6021     // movd/movss) to move this into the low element, then shuffle it into
6022     // place.
6023     if (EVTBits == 32) {
6024       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6026     }
6027   }
6028
6029   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6030   if (Values.size() == 1) {
6031     if (EVTBits == 32) {
6032       // Instead of a shuffle like this:
6033       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6034       // Check if it's possible to issue this instead.
6035       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6036       unsigned Idx = countTrailingZeros(NonZeros);
6037       SDValue Item = Op.getOperand(Idx);
6038       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6039         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6040     }
6041     return SDValue();
6042   }
6043
6044   // A vector full of immediates; various special cases are already
6045   // handled, so this is best done with a single constant-pool load.
6046   if (IsAllConstants)
6047     return SDValue();
6048
6049   // For AVX-length vectors, see if we can use a vector load to get all of the
6050   // elements, otherwise build the individual 128-bit pieces and use
6051   // shuffles to put them in place.
6052   if (VT.is256BitVector() || VT.is512BitVector()) {
6053     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6054
6055     // Check for a build vector of consecutive loads.
6056     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6057       return LD;
6058
6059     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6060
6061     // Build both the lower and upper subvector.
6062     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6063                                 makeArrayRef(&V[0], NumElems/2));
6064     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6065                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6066
6067     // Recreate the wider vector with the lower and upper part.
6068     if (VT.is256BitVector())
6069       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6070     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6071   }
6072
6073   // Let legalizer expand 2-wide build_vectors.
6074   if (EVTBits == 64) {
6075     if (NumNonZero == 1) {
6076       // One half is zero or undef.
6077       unsigned Idx = countTrailingZeros(NonZeros);
6078       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6079                                  Op.getOperand(Idx));
6080       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6081     }
6082     return SDValue();
6083   }
6084
6085   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6086   if (EVTBits == 8 && NumElems == 16)
6087     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6088                                         Subtarget, *this))
6089       return V;
6090
6091   if (EVTBits == 16 && NumElems == 8)
6092     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6093                                       Subtarget, *this))
6094       return V;
6095
6096   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6097   if (EVTBits == 32 && NumElems == 4)
6098     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6099       return V;
6100
6101   // If element VT is == 32 bits, turn it into a number of shuffles.
6102   SmallVector<SDValue, 8> V(NumElems);
6103   if (NumElems == 4 && NumZero > 0) {
6104     for (unsigned i = 0; i < 4; ++i) {
6105       bool isZero = !(NonZeros & (1 << i));
6106       if (isZero)
6107         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6108       else
6109         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6110     }
6111
6112     for (unsigned i = 0; i < 2; ++i) {
6113       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6114         default: break;
6115         case 0:
6116           V[i] = V[i*2];  // Must be a zero vector.
6117           break;
6118         case 1:
6119           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6120           break;
6121         case 2:
6122           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6123           break;
6124         case 3:
6125           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6126           break;
6127       }
6128     }
6129
6130     bool Reverse1 = (NonZeros & 0x3) == 2;
6131     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6132     int MaskVec[] = {
6133       Reverse1 ? 1 : 0,
6134       Reverse1 ? 0 : 1,
6135       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6136       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6137     };
6138     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6139   }
6140
6141   if (Values.size() > 1 && VT.is128BitVector()) {
6142     // Check for a build vector of consecutive loads.
6143     for (unsigned i = 0; i < NumElems; ++i)
6144       V[i] = Op.getOperand(i);
6145
6146     // Check for elements which are consecutive loads.
6147     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6148       return LD;
6149
6150     // Check for a build vector from mostly shuffle plus few inserting.
6151     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6152       return Sh;
6153
6154     // For SSE 4.1, use insertps to put the high elements into the low element.
6155     if (Subtarget->hasSSE41()) {
6156       SDValue Result;
6157       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6158         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6159       else
6160         Result = DAG.getUNDEF(VT);
6161
6162       for (unsigned i = 1; i < NumElems; ++i) {
6163         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6164         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6165                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6166       }
6167       return Result;
6168     }
6169
6170     // Otherwise, expand into a number of unpckl*, start by extending each of
6171     // our (non-undef) elements to the full vector width with the element in the
6172     // bottom slot of the vector (which generates no code for SSE).
6173     for (unsigned i = 0; i < NumElems; ++i) {
6174       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6175         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6176       else
6177         V[i] = DAG.getUNDEF(VT);
6178     }
6179
6180     // Next, we iteratively mix elements, e.g. for v4f32:
6181     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6182     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6183     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6184     unsigned EltStride = NumElems >> 1;
6185     while (EltStride != 0) {
6186       for (unsigned i = 0; i < EltStride; ++i) {
6187         // If V[i+EltStride] is undef and this is the first round of mixing,
6188         // then it is safe to just drop this shuffle: V[i] is already in the
6189         // right place, the one element (since it's the first round) being
6190         // inserted as undef can be dropped.  This isn't safe for successive
6191         // rounds because they will permute elements within both vectors.
6192         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6193             EltStride == NumElems/2)
6194           continue;
6195
6196         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6197       }
6198       EltStride >>= 1;
6199     }
6200     return V[0];
6201   }
6202   return SDValue();
6203 }
6204
6205 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6206 // to create 256-bit vectors from two other 128-bit ones.
6207 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6208   SDLoc dl(Op);
6209   MVT ResVT = Op.getSimpleValueType();
6210
6211   assert((ResVT.is256BitVector() ||
6212           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6213
6214   SDValue V1 = Op.getOperand(0);
6215   SDValue V2 = Op.getOperand(1);
6216   unsigned NumElems = ResVT.getVectorNumElements();
6217   if (ResVT.is256BitVector())
6218     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6219
6220   if (Op.getNumOperands() == 4) {
6221     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6222                                 ResVT.getVectorNumElements()/2);
6223     SDValue V3 = Op.getOperand(2);
6224     SDValue V4 = Op.getOperand(3);
6225     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6226       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6227   }
6228   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6229 }
6230
6231 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6232                                        const X86Subtarget *Subtarget,
6233                                        SelectionDAG & DAG) {
6234   SDLoc dl(Op);
6235   MVT ResVT = Op.getSimpleValueType();
6236   unsigned NumOfOperands = Op.getNumOperands();
6237
6238   assert(isPowerOf2_32(NumOfOperands) &&
6239          "Unexpected number of operands in CONCAT_VECTORS");
6240
6241   if (NumOfOperands > 2) {
6242     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6243                                   ResVT.getVectorNumElements()/2);
6244     SmallVector<SDValue, 2> Ops;
6245     for (unsigned i = 0; i < NumOfOperands/2; i++)
6246       Ops.push_back(Op.getOperand(i));
6247     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6248     Ops.clear();
6249     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6250       Ops.push_back(Op.getOperand(i));
6251     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6252     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6253   }
6254
6255   SDValue V1 = Op.getOperand(0);
6256   SDValue V2 = Op.getOperand(1);
6257   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6258   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6259
6260   if (IsZeroV1 && IsZeroV2)
6261     return getZeroVector(ResVT, Subtarget, DAG, dl);
6262
6263   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6264   SDValue Undef = DAG.getUNDEF(ResVT);
6265   unsigned NumElems = ResVT.getVectorNumElements();
6266   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6267
6268   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6269   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6270   if (IsZeroV1)
6271     return V2;
6272
6273   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6274   // Zero the upper bits of V1
6275   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6276   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6277   if (IsZeroV2)
6278     return V1;
6279   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6280 }
6281
6282 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6283                                    const X86Subtarget *Subtarget,
6284                                    SelectionDAG &DAG) {
6285   MVT VT = Op.getSimpleValueType();
6286   if (VT.getVectorElementType() == MVT::i1)
6287     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6288
6289   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6290          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6291           Op.getNumOperands() == 4)));
6292
6293   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6294   // from two other 128-bit ones.
6295
6296   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6297   return LowerAVXCONCAT_VECTORS(Op, DAG);
6298 }
6299
6300
6301 //===----------------------------------------------------------------------===//
6302 // Vector shuffle lowering
6303 //
6304 // This is an experimental code path for lowering vector shuffles on x86. It is
6305 // designed to handle arbitrary vector shuffles and blends, gracefully
6306 // degrading performance as necessary. It works hard to recognize idiomatic
6307 // shuffles and lower them to optimal instruction patterns without leaving
6308 // a framework that allows reasonably efficient handling of all vector shuffle
6309 // patterns.
6310 //===----------------------------------------------------------------------===//
6311
6312 /// \brief Tiny helper function to identify a no-op mask.
6313 ///
6314 /// This is a somewhat boring predicate function. It checks whether the mask
6315 /// array input, which is assumed to be a single-input shuffle mask of the kind
6316 /// used by the X86 shuffle instructions (not a fully general
6317 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6318 /// in-place shuffle are 'no-op's.
6319 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6320   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6321     if (Mask[i] != -1 && Mask[i] != i)
6322       return false;
6323   return true;
6324 }
6325
6326 /// \brief Helper function to classify a mask as a single-input mask.
6327 ///
6328 /// This isn't a generic single-input test because in the vector shuffle
6329 /// lowering we canonicalize single inputs to be the first input operand. This
6330 /// means we can more quickly test for a single input by only checking whether
6331 /// an input from the second operand exists. We also assume that the size of
6332 /// mask corresponds to the size of the input vectors which isn't true in the
6333 /// fully general case.
6334 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6335   for (int M : Mask)
6336     if (M >= (int)Mask.size())
6337       return false;
6338   return true;
6339 }
6340
6341 /// \brief Test whether there are elements crossing 128-bit lanes in this
6342 /// shuffle mask.
6343 ///
6344 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6345 /// and we routinely test for these.
6346 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6347   int LaneSize = 128 / VT.getScalarSizeInBits();
6348   int Size = Mask.size();
6349   for (int i = 0; i < Size; ++i)
6350     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6351       return true;
6352   return false;
6353 }
6354
6355 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6356 ///
6357 /// This checks a shuffle mask to see if it is performing the same
6358 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6359 /// that it is also not lane-crossing. It may however involve a blend from the
6360 /// same lane of a second vector.
6361 ///
6362 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6363 /// non-trivial to compute in the face of undef lanes. The representation is
6364 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6365 /// entries from both V1 and V2 inputs to the wider mask.
6366 static bool
6367 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6368                                 SmallVectorImpl<int> &RepeatedMask) {
6369   int LaneSize = 128 / VT.getScalarSizeInBits();
6370   RepeatedMask.resize(LaneSize, -1);
6371   int Size = Mask.size();
6372   for (int i = 0; i < Size; ++i) {
6373     if (Mask[i] < 0)
6374       continue;
6375     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6376       // This entry crosses lanes, so there is no way to model this shuffle.
6377       return false;
6378
6379     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6380     if (RepeatedMask[i % LaneSize] == -1)
6381       // This is the first non-undef entry in this slot of a 128-bit lane.
6382       RepeatedMask[i % LaneSize] =
6383           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6384     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6385       // Found a mismatch with the repeated mask.
6386       return false;
6387   }
6388   return true;
6389 }
6390
6391 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6392 /// arguments.
6393 ///
6394 /// This is a fast way to test a shuffle mask against a fixed pattern:
6395 ///
6396 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6397 ///
6398 /// It returns true if the mask is exactly as wide as the argument list, and
6399 /// each element of the mask is either -1 (signifying undef) or the value given
6400 /// in the argument.
6401 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6402                                 ArrayRef<int> ExpectedMask) {
6403   if (Mask.size() != ExpectedMask.size())
6404     return false;
6405
6406   int Size = Mask.size();
6407
6408   // If the values are build vectors, we can look through them to find
6409   // equivalent inputs that make the shuffles equivalent.
6410   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6411   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6412
6413   for (int i = 0; i < Size; ++i)
6414     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6415       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6416       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6417       if (!MaskBV || !ExpectedBV ||
6418           MaskBV->getOperand(Mask[i] % Size) !=
6419               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6420         return false;
6421     }
6422
6423   return true;
6424 }
6425
6426 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6427 ///
6428 /// This helper function produces an 8-bit shuffle immediate corresponding to
6429 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6430 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6431 /// example.
6432 ///
6433 /// NB: We rely heavily on "undef" masks preserving the input lane.
6434 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6435                                           SelectionDAG &DAG) {
6436   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6437   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6438   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6439   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6440   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6441
6442   unsigned Imm = 0;
6443   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6444   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6445   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6446   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6447   return DAG.getConstant(Imm, DL, MVT::i8);
6448 }
6449
6450 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6451 ///
6452 /// This is used as a fallback approach when first class blend instructions are
6453 /// unavailable. Currently it is only suitable for integer vectors, but could
6454 /// be generalized for floating point vectors if desirable.
6455 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6456                                             SDValue V2, ArrayRef<int> Mask,
6457                                             SelectionDAG &DAG) {
6458   assert(VT.isInteger() && "Only supports integer vector types!");
6459   MVT EltVT = VT.getScalarType();
6460   int NumEltBits = EltVT.getSizeInBits();
6461   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6462   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6463                                     EltVT);
6464   SmallVector<SDValue, 16> MaskOps;
6465   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6466     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6467       return SDValue(); // Shuffled input!
6468     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6469   }
6470
6471   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6472   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6473   // We have to cast V2 around.
6474   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6475   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6476                                       DAG.getBitcast(MaskVT, V1Mask),
6477                                       DAG.getBitcast(MaskVT, V2)));
6478   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6479 }
6480
6481 /// \brief Try to emit a blend instruction for a shuffle.
6482 ///
6483 /// This doesn't do any checks for the availability of instructions for blending
6484 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6485 /// be matched in the backend with the type given. What it does check for is
6486 /// that the shuffle mask is in fact a blend.
6487 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6488                                          SDValue V2, ArrayRef<int> Mask,
6489                                          const X86Subtarget *Subtarget,
6490                                          SelectionDAG &DAG) {
6491   unsigned BlendMask = 0;
6492   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6493     if (Mask[i] >= Size) {
6494       if (Mask[i] != i + Size)
6495         return SDValue(); // Shuffled V2 input!
6496       BlendMask |= 1u << i;
6497       continue;
6498     }
6499     if (Mask[i] >= 0 && Mask[i] != i)
6500       return SDValue(); // Shuffled V1 input!
6501   }
6502   switch (VT.SimpleTy) {
6503   case MVT::v2f64:
6504   case MVT::v4f32:
6505   case MVT::v4f64:
6506   case MVT::v8f32:
6507     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6508                        DAG.getConstant(BlendMask, DL, MVT::i8));
6509
6510   case MVT::v4i64:
6511   case MVT::v8i32:
6512     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6513     // FALLTHROUGH
6514   case MVT::v2i64:
6515   case MVT::v4i32:
6516     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6517     // that instruction.
6518     if (Subtarget->hasAVX2()) {
6519       // Scale the blend by the number of 32-bit dwords per element.
6520       int Scale =  VT.getScalarSizeInBits() / 32;
6521       BlendMask = 0;
6522       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6523         if (Mask[i] >= Size)
6524           for (int j = 0; j < Scale; ++j)
6525             BlendMask |= 1u << (i * Scale + j);
6526
6527       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6528       V1 = DAG.getBitcast(BlendVT, V1);
6529       V2 = DAG.getBitcast(BlendVT, V2);
6530       return DAG.getBitcast(
6531           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6532                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6533     }
6534     // FALLTHROUGH
6535   case MVT::v8i16: {
6536     // For integer shuffles we need to expand the mask and cast the inputs to
6537     // v8i16s prior to blending.
6538     int Scale = 8 / VT.getVectorNumElements();
6539     BlendMask = 0;
6540     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6541       if (Mask[i] >= Size)
6542         for (int j = 0; j < Scale; ++j)
6543           BlendMask |= 1u << (i * Scale + j);
6544
6545     V1 = DAG.getBitcast(MVT::v8i16, V1);
6546     V2 = DAG.getBitcast(MVT::v8i16, V2);
6547     return DAG.getBitcast(VT,
6548                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6549                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6550   }
6551
6552   case MVT::v16i16: {
6553     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6554     SmallVector<int, 8> RepeatedMask;
6555     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6556       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6557       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6558       BlendMask = 0;
6559       for (int i = 0; i < 8; ++i)
6560         if (RepeatedMask[i] >= 16)
6561           BlendMask |= 1u << i;
6562       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6563                          DAG.getConstant(BlendMask, DL, MVT::i8));
6564     }
6565   }
6566     // FALLTHROUGH
6567   case MVT::v16i8:
6568   case MVT::v32i8: {
6569     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6570            "256-bit byte-blends require AVX2 support!");
6571
6572     // Scale the blend by the number of bytes per element.
6573     int Scale = VT.getScalarSizeInBits() / 8;
6574
6575     // This form of blend is always done on bytes. Compute the byte vector
6576     // type.
6577     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6578
6579     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6580     // mix of LLVM's code generator and the x86 backend. We tell the code
6581     // generator that boolean values in the elements of an x86 vector register
6582     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6583     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6584     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6585     // of the element (the remaining are ignored) and 0 in that high bit would
6586     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6587     // the LLVM model for boolean values in vector elements gets the relevant
6588     // bit set, it is set backwards and over constrained relative to x86's
6589     // actual model.
6590     SmallVector<SDValue, 32> VSELECTMask;
6591     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6592       for (int j = 0; j < Scale; ++j)
6593         VSELECTMask.push_back(
6594             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6595                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6596                                           MVT::i8));
6597
6598     V1 = DAG.getBitcast(BlendVT, V1);
6599     V2 = DAG.getBitcast(BlendVT, V2);
6600     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6601                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6602                                                       BlendVT, VSELECTMask),
6603                                           V1, V2));
6604   }
6605
6606   default:
6607     llvm_unreachable("Not a supported integer vector type!");
6608   }
6609 }
6610
6611 /// \brief Try to lower as a blend of elements from two inputs followed by
6612 /// a single-input permutation.
6613 ///
6614 /// This matches the pattern where we can blend elements from two inputs and
6615 /// then reduce the shuffle to a single-input permutation.
6616 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6617                                                    SDValue V2,
6618                                                    ArrayRef<int> Mask,
6619                                                    SelectionDAG &DAG) {
6620   // We build up the blend mask while checking whether a blend is a viable way
6621   // to reduce the shuffle.
6622   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6623   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6624
6625   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6626     if (Mask[i] < 0)
6627       continue;
6628
6629     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6630
6631     if (BlendMask[Mask[i] % Size] == -1)
6632       BlendMask[Mask[i] % Size] = Mask[i];
6633     else if (BlendMask[Mask[i] % Size] != Mask[i])
6634       return SDValue(); // Can't blend in the needed input!
6635
6636     PermuteMask[i] = Mask[i] % Size;
6637   }
6638
6639   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6640   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6641 }
6642
6643 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6644 /// blends and permutes.
6645 ///
6646 /// This matches the extremely common pattern for handling combined
6647 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6648 /// operations. It will try to pick the best arrangement of shuffles and
6649 /// blends.
6650 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6651                                                           SDValue V1,
6652                                                           SDValue V2,
6653                                                           ArrayRef<int> Mask,
6654                                                           SelectionDAG &DAG) {
6655   // Shuffle the input elements into the desired positions in V1 and V2 and
6656   // blend them together.
6657   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6658   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6659   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6660   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6661     if (Mask[i] >= 0 && Mask[i] < Size) {
6662       V1Mask[i] = Mask[i];
6663       BlendMask[i] = i;
6664     } else if (Mask[i] >= Size) {
6665       V2Mask[i] = Mask[i] - Size;
6666       BlendMask[i] = i + Size;
6667     }
6668
6669   // Try to lower with the simpler initial blend strategy unless one of the
6670   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6671   // shuffle may be able to fold with a load or other benefit. However, when
6672   // we'll have to do 2x as many shuffles in order to achieve this, blending
6673   // first is a better strategy.
6674   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6675     if (SDValue BlendPerm =
6676             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6677       return BlendPerm;
6678
6679   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6680   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6681   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6682 }
6683
6684 /// \brief Try to lower a vector shuffle as a byte rotation.
6685 ///
6686 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6687 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6688 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6689 /// try to generically lower a vector shuffle through such an pattern. It
6690 /// does not check for the profitability of lowering either as PALIGNR or
6691 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6692 /// This matches shuffle vectors that look like:
6693 ///
6694 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6695 ///
6696 /// Essentially it concatenates V1 and V2, shifts right by some number of
6697 /// elements, and takes the low elements as the result. Note that while this is
6698 /// specified as a *right shift* because x86 is little-endian, it is a *left
6699 /// rotate* of the vector lanes.
6700 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6701                                               SDValue V2,
6702                                               ArrayRef<int> Mask,
6703                                               const X86Subtarget *Subtarget,
6704                                               SelectionDAG &DAG) {
6705   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6706
6707   int NumElts = Mask.size();
6708   int NumLanes = VT.getSizeInBits() / 128;
6709   int NumLaneElts = NumElts / NumLanes;
6710
6711   // We need to detect various ways of spelling a rotation:
6712   //   [11, 12, 13, 14, 15,  0,  1,  2]
6713   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6714   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6715   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6716   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6717   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6718   int Rotation = 0;
6719   SDValue Lo, Hi;
6720   for (int l = 0; l < NumElts; l += NumLaneElts) {
6721     for (int i = 0; i < NumLaneElts; ++i) {
6722       if (Mask[l + i] == -1)
6723         continue;
6724       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6725
6726       // Get the mod-Size index and lane correct it.
6727       int LaneIdx = (Mask[l + i] % NumElts) - l;
6728       // Make sure it was in this lane.
6729       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6730         return SDValue();
6731
6732       // Determine where a rotated vector would have started.
6733       int StartIdx = i - LaneIdx;
6734       if (StartIdx == 0)
6735         // The identity rotation isn't interesting, stop.
6736         return SDValue();
6737
6738       // If we found the tail of a vector the rotation must be the missing
6739       // front. If we found the head of a vector, it must be how much of the
6740       // head.
6741       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6742
6743       if (Rotation == 0)
6744         Rotation = CandidateRotation;
6745       else if (Rotation != CandidateRotation)
6746         // The rotations don't match, so we can't match this mask.
6747         return SDValue();
6748
6749       // Compute which value this mask is pointing at.
6750       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6751
6752       // Compute which of the two target values this index should be assigned
6753       // to. This reflects whether the high elements are remaining or the low
6754       // elements are remaining.
6755       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6756
6757       // Either set up this value if we've not encountered it before, or check
6758       // that it remains consistent.
6759       if (!TargetV)
6760         TargetV = MaskV;
6761       else if (TargetV != MaskV)
6762         // This may be a rotation, but it pulls from the inputs in some
6763         // unsupported interleaving.
6764         return SDValue();
6765     }
6766   }
6767
6768   // Check that we successfully analyzed the mask, and normalize the results.
6769   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6770   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6771   if (!Lo)
6772     Lo = Hi;
6773   else if (!Hi)
6774     Hi = Lo;
6775
6776   // The actual rotate instruction rotates bytes, so we need to scale the
6777   // rotation based on how many bytes are in the vector lane.
6778   int Scale = 16 / NumLaneElts;
6779
6780   // SSSE3 targets can use the palignr instruction.
6781   if (Subtarget->hasSSSE3()) {
6782     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6783     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6784     Lo = DAG.getBitcast(AlignVT, Lo);
6785     Hi = DAG.getBitcast(AlignVT, Hi);
6786
6787     return DAG.getBitcast(
6788         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6789                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6790   }
6791
6792   assert(VT.getSizeInBits() == 128 &&
6793          "Rotate-based lowering only supports 128-bit lowering!");
6794   assert(Mask.size() <= 16 &&
6795          "Can shuffle at most 16 bytes in a 128-bit vector!");
6796
6797   // Default SSE2 implementation
6798   int LoByteShift = 16 - Rotation * Scale;
6799   int HiByteShift = Rotation * Scale;
6800
6801   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6802   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6803   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6804
6805   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6806                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6807   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6808                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6809   return DAG.getBitcast(VT,
6810                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6811 }
6812
6813 /// \brief Compute whether each element of a shuffle is zeroable.
6814 ///
6815 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6816 /// Either it is an undef element in the shuffle mask, the element of the input
6817 /// referenced is undef, or the element of the input referenced is known to be
6818 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6819 /// as many lanes with this technique as possible to simplify the remaining
6820 /// shuffle.
6821 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6822                                                      SDValue V1, SDValue V2) {
6823   SmallBitVector Zeroable(Mask.size(), false);
6824
6825   while (V1.getOpcode() == ISD::BITCAST)
6826     V1 = V1->getOperand(0);
6827   while (V2.getOpcode() == ISD::BITCAST)
6828     V2 = V2->getOperand(0);
6829
6830   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6831   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6832
6833   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6834     int M = Mask[i];
6835     // Handle the easy cases.
6836     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6837       Zeroable[i] = true;
6838       continue;
6839     }
6840
6841     // If this is an index into a build_vector node (which has the same number
6842     // of elements), dig out the input value and use it.
6843     SDValue V = M < Size ? V1 : V2;
6844     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6845       continue;
6846
6847     SDValue Input = V.getOperand(M % Size);
6848     // The UNDEF opcode check really should be dead code here, but not quite
6849     // worth asserting on (it isn't invalid, just unexpected).
6850     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6851       Zeroable[i] = true;
6852   }
6853
6854   return Zeroable;
6855 }
6856
6857 /// \brief Try to emit a bitmask instruction for a shuffle.
6858 ///
6859 /// This handles cases where we can model a blend exactly as a bitmask due to
6860 /// one of the inputs being zeroable.
6861 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6862                                            SDValue V2, ArrayRef<int> Mask,
6863                                            SelectionDAG &DAG) {
6864   MVT EltVT = VT.getScalarType();
6865   int NumEltBits = EltVT.getSizeInBits();
6866   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6867   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6868   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6869                                     IntEltVT);
6870   if (EltVT.isFloatingPoint()) {
6871     Zero = DAG.getBitcast(EltVT, Zero);
6872     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6873   }
6874   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6875   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6876   SDValue V;
6877   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6878     if (Zeroable[i])
6879       continue;
6880     if (Mask[i] % Size != i)
6881       return SDValue(); // Not a blend.
6882     if (!V)
6883       V = Mask[i] < Size ? V1 : V2;
6884     else if (V != (Mask[i] < Size ? V1 : V2))
6885       return SDValue(); // Can only let one input through the mask.
6886
6887     VMaskOps[i] = AllOnes;
6888   }
6889   if (!V)
6890     return SDValue(); // No non-zeroable elements!
6891
6892   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6893   V = DAG.getNode(VT.isFloatingPoint()
6894                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6895                   DL, VT, V, VMask);
6896   return V;
6897 }
6898
6899 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6900 ///
6901 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6902 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6903 /// matches elements from one of the input vectors shuffled to the left or
6904 /// right with zeroable elements 'shifted in'. It handles both the strictly
6905 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6906 /// quad word lane.
6907 ///
6908 /// PSHL : (little-endian) left bit shift.
6909 /// [ zz, 0, zz,  2 ]
6910 /// [ -1, 4, zz, -1 ]
6911 /// PSRL : (little-endian) right bit shift.
6912 /// [  1, zz,  3, zz]
6913 /// [ -1, -1,  7, zz]
6914 /// PSLLDQ : (little-endian) left byte shift
6915 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6916 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6917 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6918 /// PSRLDQ : (little-endian) right byte shift
6919 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6920 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6921 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6922 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6923                                          SDValue V2, ArrayRef<int> Mask,
6924                                          SelectionDAG &DAG) {
6925   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6926
6927   int Size = Mask.size();
6928   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6929
6930   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6931     for (int i = 0; i < Size; i += Scale)
6932       for (int j = 0; j < Shift; ++j)
6933         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6934           return false;
6935
6936     return true;
6937   };
6938
6939   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6940     for (int i = 0; i != Size; i += Scale) {
6941       unsigned Pos = Left ? i + Shift : i;
6942       unsigned Low = Left ? i : i + Shift;
6943       unsigned Len = Scale - Shift;
6944       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6945                                       Low + (V == V1 ? 0 : Size)))
6946         return SDValue();
6947     }
6948
6949     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6950     bool ByteShift = ShiftEltBits > 64;
6951     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6952                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6953     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6954
6955     // Normalize the scale for byte shifts to still produce an i64 element
6956     // type.
6957     Scale = ByteShift ? Scale / 2 : Scale;
6958
6959     // We need to round trip through the appropriate type for the shift.
6960     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6961     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6962     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6963            "Illegal integer vector type");
6964     V = DAG.getBitcast(ShiftVT, V);
6965
6966     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6967                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6968     return DAG.getBitcast(VT, V);
6969   };
6970
6971   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6972   // keep doubling the size of the integer elements up to that. We can
6973   // then shift the elements of the integer vector by whole multiples of
6974   // their width within the elements of the larger integer vector. Test each
6975   // multiple to see if we can find a match with the moved element indices
6976   // and that the shifted in elements are all zeroable.
6977   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6978     for (int Shift = 1; Shift != Scale; ++Shift)
6979       for (bool Left : {true, false})
6980         if (CheckZeros(Shift, Scale, Left))
6981           for (SDValue V : {V1, V2})
6982             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6983               return Match;
6984
6985   // no match
6986   return SDValue();
6987 }
6988
6989 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6990 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6991                                            SDValue V2, ArrayRef<int> Mask,
6992                                            SelectionDAG &DAG) {
6993   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6994   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6995
6996   int Size = Mask.size();
6997   int HalfSize = Size / 2;
6998   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6999
7000   // Upper half must be undefined.
7001   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7002     return SDValue();
7003
7004   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7005   // Remainder of lower half result is zero and upper half is all undef.
7006   auto LowerAsEXTRQ = [&]() {
7007     // Determine the extraction length from the part of the
7008     // lower half that isn't zeroable.
7009     int Len = HalfSize;
7010     for (; Len >= 0; --Len)
7011       if (!Zeroable[Len - 1])
7012         break;
7013     assert(Len > 0 && "Zeroable shuffle mask");
7014
7015     // Attempt to match first Len sequential elements from the lower half.
7016     SDValue Src;
7017     int Idx = -1;
7018     for (int i = 0; i != Len; ++i) {
7019       int M = Mask[i];
7020       if (M < 0)
7021         continue;
7022       SDValue &V = (M < Size ? V1 : V2);
7023       M = M % Size;
7024
7025       // All mask elements must be in the lower half.
7026       if (M > HalfSize)
7027         return SDValue();
7028
7029       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7030         Src = V;
7031         Idx = M - i;
7032         continue;
7033       }
7034       return SDValue();
7035     }
7036
7037     if (Idx < 0)
7038       return SDValue();
7039
7040     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7041     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7042     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7043     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7044                        DAG.getConstant(BitLen, DL, MVT::i8),
7045                        DAG.getConstant(BitIdx, DL, MVT::i8));
7046   };
7047
7048   if (SDValue ExtrQ = LowerAsEXTRQ())
7049     return ExtrQ;
7050
7051   // INSERTQ: Extract lowest Len elements from lower half of second source and
7052   // insert over first source, starting at Idx.
7053   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7054   auto LowerAsInsertQ = [&]() {
7055     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7056       SDValue Base;
7057
7058       // Attempt to match first source from mask before insertion point.
7059       if (isUndefInRange(Mask, 0, Idx)) {
7060         /* EMPTY */
7061       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7062         Base = V1;
7063       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7064         Base = V2;
7065       } else {
7066         continue;
7067       }
7068
7069       // Extend the extraction length looking to match both the insertion of
7070       // the second source and the remaining elements of the first.
7071       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7072         SDValue Insert;
7073         int Len = Hi - Idx;
7074
7075         // Match insertion.
7076         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7077           Insert = V1;
7078         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7079           Insert = V2;
7080         } else {
7081           continue;
7082         }
7083
7084         // Match the remaining elements of the lower half.
7085         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7086           /* EMPTY */
7087         } else if ((!Base || (Base == V1)) &&
7088                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7089           Base = V1;
7090         } else if ((!Base || (Base == V2)) &&
7091                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7092                                               Size + Hi)) {
7093           Base = V2;
7094         } else {
7095           continue;
7096         }
7097
7098         // We may not have a base (first source) - this can safely be undefined.
7099         if (!Base)
7100           Base = DAG.getUNDEF(VT);
7101
7102         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7103         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7104         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7105                            DAG.getConstant(BitLen, DL, MVT::i8),
7106                            DAG.getConstant(BitIdx, DL, MVT::i8));
7107       }
7108     }
7109
7110     return SDValue();
7111   };
7112
7113   if (SDValue InsertQ = LowerAsInsertQ())
7114     return InsertQ;
7115
7116   return SDValue();
7117 }
7118
7119 /// \brief Lower a vector shuffle as a zero or any extension.
7120 ///
7121 /// Given a specific number of elements, element bit width, and extension
7122 /// stride, produce either a zero or any extension based on the available
7123 /// features of the subtarget.
7124 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7125     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7126     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7127   assert(Scale > 1 && "Need a scale to extend.");
7128   int NumElements = VT.getVectorNumElements();
7129   int EltBits = VT.getScalarSizeInBits();
7130   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7131          "Only 8, 16, and 32 bit elements can be extended.");
7132   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7133
7134   // Found a valid zext mask! Try various lowering strategies based on the
7135   // input type and available ISA extensions.
7136   if (Subtarget->hasSSE41()) {
7137     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7138                                  NumElements / Scale);
7139     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7140   }
7141
7142   // For any extends we can cheat for larger element sizes and use shuffle
7143   // instructions that can fold with a load and/or copy.
7144   if (AnyExt && EltBits == 32) {
7145     int PSHUFDMask[4] = {0, -1, 1, -1};
7146     return DAG.getBitcast(
7147         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7148                         DAG.getBitcast(MVT::v4i32, InputV),
7149                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7150   }
7151   if (AnyExt && EltBits == 16 && Scale > 2) {
7152     int PSHUFDMask[4] = {0, -1, 0, -1};
7153     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7154                          DAG.getBitcast(MVT::v4i32, InputV),
7155                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7156     int PSHUFHWMask[4] = {1, -1, -1, -1};
7157     return DAG.getBitcast(
7158         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7159                         DAG.getBitcast(MVT::v8i16, InputV),
7160                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7161   }
7162
7163   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7164   // to 64-bits.
7165   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7166     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7167     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7168
7169     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7170                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7171                                          DAG.getConstant(EltBits, DL, MVT::i8),
7172                                          DAG.getConstant(0, DL, MVT::i8)));
7173     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7174       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7175
7176     SDValue Hi =
7177         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7178                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7179                                 DAG.getConstant(EltBits, DL, MVT::i8),
7180                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7181     return DAG.getNode(ISD::BITCAST, DL, VT,
7182                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7183   }
7184
7185   // If this would require more than 2 unpack instructions to expand, use
7186   // pshufb when available. We can only use more than 2 unpack instructions
7187   // when zero extending i8 elements which also makes it easier to use pshufb.
7188   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7189     assert(NumElements == 16 && "Unexpected byte vector width!");
7190     SDValue PSHUFBMask[16];
7191     for (int i = 0; i < 16; ++i)
7192       PSHUFBMask[i] =
7193           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7194     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7195     return DAG.getBitcast(VT,
7196                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7197                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7198                                                   MVT::v16i8, PSHUFBMask)));
7199   }
7200
7201   // Otherwise emit a sequence of unpacks.
7202   do {
7203     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7204     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7205                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7206     InputV = DAG.getBitcast(InputVT, InputV);
7207     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7208     Scale /= 2;
7209     EltBits *= 2;
7210     NumElements /= 2;
7211   } while (Scale > 1);
7212   return DAG.getBitcast(VT, InputV);
7213 }
7214
7215 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7216 ///
7217 /// This routine will try to do everything in its power to cleverly lower
7218 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7219 /// check for the profitability of this lowering,  it tries to aggressively
7220 /// match this pattern. It will use all of the micro-architectural details it
7221 /// can to emit an efficient lowering. It handles both blends with all-zero
7222 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7223 /// masking out later).
7224 ///
7225 /// The reason we have dedicated lowering for zext-style shuffles is that they
7226 /// are both incredibly common and often quite performance sensitive.
7227 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7228     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7229     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7230   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7231
7232   int Bits = VT.getSizeInBits();
7233   int NumElements = VT.getVectorNumElements();
7234   assert(VT.getScalarSizeInBits() <= 32 &&
7235          "Exceeds 32-bit integer zero extension limit");
7236   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7237
7238   // Define a helper function to check a particular ext-scale and lower to it if
7239   // valid.
7240   auto Lower = [&](int Scale) -> SDValue {
7241     SDValue InputV;
7242     bool AnyExt = true;
7243     for (int i = 0; i < NumElements; ++i) {
7244       if (Mask[i] == -1)
7245         continue; // Valid anywhere but doesn't tell us anything.
7246       if (i % Scale != 0) {
7247         // Each of the extended elements need to be zeroable.
7248         if (!Zeroable[i])
7249           return SDValue();
7250
7251         // We no longer are in the anyext case.
7252         AnyExt = false;
7253         continue;
7254       }
7255
7256       // Each of the base elements needs to be consecutive indices into the
7257       // same input vector.
7258       SDValue V = Mask[i] < NumElements ? V1 : V2;
7259       if (!InputV)
7260         InputV = V;
7261       else if (InputV != V)
7262         return SDValue(); // Flip-flopping inputs.
7263
7264       if (Mask[i] % NumElements != i / Scale)
7265         return SDValue(); // Non-consecutive strided elements.
7266     }
7267
7268     // If we fail to find an input, we have a zero-shuffle which should always
7269     // have already been handled.
7270     // FIXME: Maybe handle this here in case during blending we end up with one?
7271     if (!InputV)
7272       return SDValue();
7273
7274     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7275         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7276   };
7277
7278   // The widest scale possible for extending is to a 64-bit integer.
7279   assert(Bits % 64 == 0 &&
7280          "The number of bits in a vector must be divisible by 64 on x86!");
7281   int NumExtElements = Bits / 64;
7282
7283   // Each iteration, try extending the elements half as much, but into twice as
7284   // many elements.
7285   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7286     assert(NumElements % NumExtElements == 0 &&
7287            "The input vector size must be divisible by the extended size.");
7288     if (SDValue V = Lower(NumElements / NumExtElements))
7289       return V;
7290   }
7291
7292   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7293   if (Bits != 128)
7294     return SDValue();
7295
7296   // Returns one of the source operands if the shuffle can be reduced to a
7297   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7298   auto CanZExtLowHalf = [&]() {
7299     for (int i = NumElements / 2; i != NumElements; ++i)
7300       if (!Zeroable[i])
7301         return SDValue();
7302     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7303       return V1;
7304     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7305       return V2;
7306     return SDValue();
7307   };
7308
7309   if (SDValue V = CanZExtLowHalf()) {
7310     V = DAG.getBitcast(MVT::v2i64, V);
7311     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7312     return DAG.getBitcast(VT, V);
7313   }
7314
7315   // No viable ext lowering found.
7316   return SDValue();
7317 }
7318
7319 /// \brief Try to get a scalar value for a specific element of a vector.
7320 ///
7321 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7322 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7323                                               SelectionDAG &DAG) {
7324   MVT VT = V.getSimpleValueType();
7325   MVT EltVT = VT.getVectorElementType();
7326   while (V.getOpcode() == ISD::BITCAST)
7327     V = V.getOperand(0);
7328   // If the bitcasts shift the element size, we can't extract an equivalent
7329   // element from it.
7330   MVT NewVT = V.getSimpleValueType();
7331   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7332     return SDValue();
7333
7334   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7335       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7336     // Ensure the scalar operand is the same size as the destination.
7337     // FIXME: Add support for scalar truncation where possible.
7338     SDValue S = V.getOperand(Idx);
7339     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7340       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7341   }
7342
7343   return SDValue();
7344 }
7345
7346 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7347 ///
7348 /// This is particularly important because the set of instructions varies
7349 /// significantly based on whether the operand is a load or not.
7350 static bool isShuffleFoldableLoad(SDValue V) {
7351   while (V.getOpcode() == ISD::BITCAST)
7352     V = V.getOperand(0);
7353
7354   return ISD::isNON_EXTLoad(V.getNode());
7355 }
7356
7357 /// \brief Try to lower insertion of a single element into a zero vector.
7358 ///
7359 /// This is a common pattern that we have especially efficient patterns to lower
7360 /// across all subtarget feature sets.
7361 static SDValue lowerVectorShuffleAsElementInsertion(
7362     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7363     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7364   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7365   MVT ExtVT = VT;
7366   MVT EltVT = VT.getVectorElementType();
7367
7368   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7369                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7370                 Mask.begin();
7371   bool IsV1Zeroable = true;
7372   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7373     if (i != V2Index && !Zeroable[i]) {
7374       IsV1Zeroable = false;
7375       break;
7376     }
7377
7378   // Check for a single input from a SCALAR_TO_VECTOR node.
7379   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7380   // all the smarts here sunk into that routine. However, the current
7381   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7382   // vector shuffle lowering is dead.
7383   if (SDValue V2S = getScalarValueForVectorElement(
7384           V2, Mask[V2Index] - Mask.size(), DAG)) {
7385     // We need to zext the scalar if it is smaller than an i32.
7386     V2S = DAG.getBitcast(EltVT, V2S);
7387     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7388       // Using zext to expand a narrow element won't work for non-zero
7389       // insertions.
7390       if (!IsV1Zeroable)
7391         return SDValue();
7392
7393       // Zero-extend directly to i32.
7394       ExtVT = MVT::v4i32;
7395       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7396     }
7397     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7398   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7399              EltVT == MVT::i16) {
7400     // Either not inserting from the low element of the input or the input
7401     // element size is too small to use VZEXT_MOVL to clear the high bits.
7402     return SDValue();
7403   }
7404
7405   if (!IsV1Zeroable) {
7406     // If V1 can't be treated as a zero vector we have fewer options to lower
7407     // this. We can't support integer vectors or non-zero targets cheaply, and
7408     // the V1 elements can't be permuted in any way.
7409     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7410     if (!VT.isFloatingPoint() || V2Index != 0)
7411       return SDValue();
7412     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7413     V1Mask[V2Index] = -1;
7414     if (!isNoopShuffleMask(V1Mask))
7415       return SDValue();
7416     // This is essentially a special case blend operation, but if we have
7417     // general purpose blend operations, they are always faster. Bail and let
7418     // the rest of the lowering handle these as blends.
7419     if (Subtarget->hasSSE41())
7420       return SDValue();
7421
7422     // Otherwise, use MOVSD or MOVSS.
7423     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7424            "Only two types of floating point element types to handle!");
7425     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7426                        ExtVT, V1, V2);
7427   }
7428
7429   // This lowering only works for the low element with floating point vectors.
7430   if (VT.isFloatingPoint() && V2Index != 0)
7431     return SDValue();
7432
7433   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7434   if (ExtVT != VT)
7435     V2 = DAG.getBitcast(VT, V2);
7436
7437   if (V2Index != 0) {
7438     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7439     // the desired position. Otherwise it is more efficient to do a vector
7440     // shift left. We know that we can do a vector shift left because all
7441     // the inputs are zero.
7442     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7443       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7444       V2Shuffle[V2Index] = 0;
7445       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7446     } else {
7447       V2 = DAG.getBitcast(MVT::v2i64, V2);
7448       V2 = DAG.getNode(
7449           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7450           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7451                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7452                               DAG.getDataLayout(), VT)));
7453       V2 = DAG.getBitcast(VT, V2);
7454     }
7455   }
7456   return V2;
7457 }
7458
7459 /// \brief Try to lower broadcast of a single element.
7460 ///
7461 /// For convenience, this code also bundles all of the subtarget feature set
7462 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7463 /// a convenient way to factor it out.
7464 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7465                                              ArrayRef<int> Mask,
7466                                              const X86Subtarget *Subtarget,
7467                                              SelectionDAG &DAG) {
7468   if (!Subtarget->hasAVX())
7469     return SDValue();
7470   if (VT.isInteger() && !Subtarget->hasAVX2())
7471     return SDValue();
7472
7473   // Check that the mask is a broadcast.
7474   int BroadcastIdx = -1;
7475   for (int M : Mask)
7476     if (M >= 0 && BroadcastIdx == -1)
7477       BroadcastIdx = M;
7478     else if (M >= 0 && M != BroadcastIdx)
7479       return SDValue();
7480
7481   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7482                                             "a sorted mask where the broadcast "
7483                                             "comes from V1.");
7484
7485   // Go up the chain of (vector) values to find a scalar load that we can
7486   // combine with the broadcast.
7487   for (;;) {
7488     switch (V.getOpcode()) {
7489     case ISD::CONCAT_VECTORS: {
7490       int OperandSize = Mask.size() / V.getNumOperands();
7491       V = V.getOperand(BroadcastIdx / OperandSize);
7492       BroadcastIdx %= OperandSize;
7493       continue;
7494     }
7495
7496     case ISD::INSERT_SUBVECTOR: {
7497       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7498       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7499       if (!ConstantIdx)
7500         break;
7501
7502       int BeginIdx = (int)ConstantIdx->getZExtValue();
7503       int EndIdx =
7504           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7505       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7506         BroadcastIdx -= BeginIdx;
7507         V = VInner;
7508       } else {
7509         V = VOuter;
7510       }
7511       continue;
7512     }
7513     }
7514     break;
7515   }
7516
7517   // Check if this is a broadcast of a scalar. We special case lowering
7518   // for scalars so that we can more effectively fold with loads.
7519   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7520       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7521     V = V.getOperand(BroadcastIdx);
7522
7523     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7524     // Only AVX2 has register broadcasts.
7525     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7526       return SDValue();
7527   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7528     // We can't broadcast from a vector register without AVX2, and we can only
7529     // broadcast from the zero-element of a vector register.
7530     return SDValue();
7531   }
7532
7533   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7534 }
7535
7536 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7537 // INSERTPS when the V1 elements are already in the correct locations
7538 // because otherwise we can just always use two SHUFPS instructions which
7539 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7540 // perform INSERTPS if a single V1 element is out of place and all V2
7541 // elements are zeroable.
7542 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7543                                             ArrayRef<int> Mask,
7544                                             SelectionDAG &DAG) {
7545   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7546   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7547   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7548   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7549
7550   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7551
7552   unsigned ZMask = 0;
7553   int V1DstIndex = -1;
7554   int V2DstIndex = -1;
7555   bool V1UsedInPlace = false;
7556
7557   for (int i = 0; i < 4; ++i) {
7558     // Synthesize a zero mask from the zeroable elements (includes undefs).
7559     if (Zeroable[i]) {
7560       ZMask |= 1 << i;
7561       continue;
7562     }
7563
7564     // Flag if we use any V1 inputs in place.
7565     if (i == Mask[i]) {
7566       V1UsedInPlace = true;
7567       continue;
7568     }
7569
7570     // We can only insert a single non-zeroable element.
7571     if (V1DstIndex != -1 || V2DstIndex != -1)
7572       return SDValue();
7573
7574     if (Mask[i] < 4) {
7575       // V1 input out of place for insertion.
7576       V1DstIndex = i;
7577     } else {
7578       // V2 input for insertion.
7579       V2DstIndex = i;
7580     }
7581   }
7582
7583   // Don't bother if we have no (non-zeroable) element for insertion.
7584   if (V1DstIndex == -1 && V2DstIndex == -1)
7585     return SDValue();
7586
7587   // Determine element insertion src/dst indices. The src index is from the
7588   // start of the inserted vector, not the start of the concatenated vector.
7589   unsigned V2SrcIndex = 0;
7590   if (V1DstIndex != -1) {
7591     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7592     // and don't use the original V2 at all.
7593     V2SrcIndex = Mask[V1DstIndex];
7594     V2DstIndex = V1DstIndex;
7595     V2 = V1;
7596   } else {
7597     V2SrcIndex = Mask[V2DstIndex] - 4;
7598   }
7599
7600   // If no V1 inputs are used in place, then the result is created only from
7601   // the zero mask and the V2 insertion - so remove V1 dependency.
7602   if (!V1UsedInPlace)
7603     V1 = DAG.getUNDEF(MVT::v4f32);
7604
7605   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7606   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7607
7608   // Insert the V2 element into the desired position.
7609   SDLoc DL(Op);
7610   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7611                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7612 }
7613
7614 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7615 /// UNPCK instruction.
7616 ///
7617 /// This specifically targets cases where we end up with alternating between
7618 /// the two inputs, and so can permute them into something that feeds a single
7619 /// UNPCK instruction. Note that this routine only targets integer vectors
7620 /// because for floating point vectors we have a generalized SHUFPS lowering
7621 /// strategy that handles everything that doesn't *exactly* match an unpack,
7622 /// making this clever lowering unnecessary.
7623 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7624                                           SDValue V2, ArrayRef<int> Mask,
7625                                           SelectionDAG &DAG) {
7626   assert(!VT.isFloatingPoint() &&
7627          "This routine only supports integer vectors.");
7628   assert(!isSingleInputShuffleMask(Mask) &&
7629          "This routine should only be used when blending two inputs.");
7630   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7631
7632   int Size = Mask.size();
7633
7634   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7635     return M >= 0 && M % Size < Size / 2;
7636   });
7637   int NumHiInputs = std::count_if(
7638       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7639
7640   bool UnpackLo = NumLoInputs >= NumHiInputs;
7641
7642   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7643     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7644     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7645
7646     for (int i = 0; i < Size; ++i) {
7647       if (Mask[i] < 0)
7648         continue;
7649
7650       // Each element of the unpack contains Scale elements from this mask.
7651       int UnpackIdx = i / Scale;
7652
7653       // We only handle the case where V1 feeds the first slots of the unpack.
7654       // We rely on canonicalization to ensure this is the case.
7655       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7656         return SDValue();
7657
7658       // Setup the mask for this input. The indexing is tricky as we have to
7659       // handle the unpack stride.
7660       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7661       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7662           Mask[i] % Size;
7663     }
7664
7665     // If we will have to shuffle both inputs to use the unpack, check whether
7666     // we can just unpack first and shuffle the result. If so, skip this unpack.
7667     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7668         !isNoopShuffleMask(V2Mask))
7669       return SDValue();
7670
7671     // Shuffle the inputs into place.
7672     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7673     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7674
7675     // Cast the inputs to the type we will use to unpack them.
7676     V1 = DAG.getBitcast(UnpackVT, V1);
7677     V2 = DAG.getBitcast(UnpackVT, V2);
7678
7679     // Unpack the inputs and cast the result back to the desired type.
7680     return DAG.getBitcast(
7681         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7682                         UnpackVT, V1, V2));
7683   };
7684
7685   // We try each unpack from the largest to the smallest to try and find one
7686   // that fits this mask.
7687   int OrigNumElements = VT.getVectorNumElements();
7688   int OrigScalarSize = VT.getScalarSizeInBits();
7689   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7690     int Scale = ScalarSize / OrigScalarSize;
7691     int NumElements = OrigNumElements / Scale;
7692     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7693     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7694       return Unpack;
7695   }
7696
7697   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7698   // initial unpack.
7699   if (NumLoInputs == 0 || NumHiInputs == 0) {
7700     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7701            "We have to have *some* inputs!");
7702     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7703
7704     // FIXME: We could consider the total complexity of the permute of each
7705     // possible unpacking. Or at the least we should consider how many
7706     // half-crossings are created.
7707     // FIXME: We could consider commuting the unpacks.
7708
7709     SmallVector<int, 32> PermMask;
7710     PermMask.assign(Size, -1);
7711     for (int i = 0; i < Size; ++i) {
7712       if (Mask[i] < 0)
7713         continue;
7714
7715       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7716
7717       PermMask[i] =
7718           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7719     }
7720     return DAG.getVectorShuffle(
7721         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7722                             DL, VT, V1, V2),
7723         DAG.getUNDEF(VT), PermMask);
7724   }
7725
7726   return SDValue();
7727 }
7728
7729 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7730 ///
7731 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7732 /// support for floating point shuffles but not integer shuffles. These
7733 /// instructions will incur a domain crossing penalty on some chips though so
7734 /// it is better to avoid lowering through this for integer vectors where
7735 /// possible.
7736 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7737                                        const X86Subtarget *Subtarget,
7738                                        SelectionDAG &DAG) {
7739   SDLoc DL(Op);
7740   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7741   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7742   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7743   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7744   ArrayRef<int> Mask = SVOp->getMask();
7745   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7746
7747   if (isSingleInputShuffleMask(Mask)) {
7748     // Use low duplicate instructions for masks that match their pattern.
7749     if (Subtarget->hasSSE3())
7750       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7751         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7752
7753     // Straight shuffle of a single input vector. Simulate this by using the
7754     // single input as both of the "inputs" to this instruction..
7755     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7756
7757     if (Subtarget->hasAVX()) {
7758       // If we have AVX, we can use VPERMILPS which will allow folding a load
7759       // into the shuffle.
7760       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7761                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7762     }
7763
7764     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7765                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7766   }
7767   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7768   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7769
7770   // If we have a single input, insert that into V1 if we can do so cheaply.
7771   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7772     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7773             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7774       return Insertion;
7775     // Try inverting the insertion since for v2 masks it is easy to do and we
7776     // can't reliably sort the mask one way or the other.
7777     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7778                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7779     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7780             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7781       return Insertion;
7782   }
7783
7784   // Try to use one of the special instruction patterns to handle two common
7785   // blend patterns if a zero-blend above didn't work.
7786   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7787       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7788     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7789       // We can either use a special instruction to load over the low double or
7790       // to move just the low double.
7791       return DAG.getNode(
7792           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7793           DL, MVT::v2f64, V2,
7794           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7795
7796   if (Subtarget->hasSSE41())
7797     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7798                                                   Subtarget, DAG))
7799       return Blend;
7800
7801   // Use dedicated unpack instructions for masks that match their pattern.
7802   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7803     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7804   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7805     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7806
7807   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7808   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7809                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7810 }
7811
7812 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7813 ///
7814 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7815 /// the integer unit to minimize domain crossing penalties. However, for blends
7816 /// it falls back to the floating point shuffle operation with appropriate bit
7817 /// casting.
7818 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7819                                        const X86Subtarget *Subtarget,
7820                                        SelectionDAG &DAG) {
7821   SDLoc DL(Op);
7822   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7823   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7824   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7825   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7826   ArrayRef<int> Mask = SVOp->getMask();
7827   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7828
7829   if (isSingleInputShuffleMask(Mask)) {
7830     // Check for being able to broadcast a single element.
7831     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7832                                                           Mask, Subtarget, DAG))
7833       return Broadcast;
7834
7835     // Straight shuffle of a single input vector. For everything from SSE2
7836     // onward this has a single fast instruction with no scary immediates.
7837     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7838     V1 = DAG.getBitcast(MVT::v4i32, V1);
7839     int WidenedMask[4] = {
7840         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7841         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7842     return DAG.getBitcast(
7843         MVT::v2i64,
7844         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7845                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7846   }
7847   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7848   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7849   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7850   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7851
7852   // If we have a blend of two PACKUS operations an the blend aligns with the
7853   // low and half halves, we can just merge the PACKUS operations. This is
7854   // particularly important as it lets us merge shuffles that this routine itself
7855   // creates.
7856   auto GetPackNode = [](SDValue V) {
7857     while (V.getOpcode() == ISD::BITCAST)
7858       V = V.getOperand(0);
7859
7860     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7861   };
7862   if (SDValue V1Pack = GetPackNode(V1))
7863     if (SDValue V2Pack = GetPackNode(V2))
7864       return DAG.getBitcast(MVT::v2i64,
7865                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7866                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7867                                                      : V1Pack.getOperand(1),
7868                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7869                                                      : V2Pack.getOperand(1)));
7870
7871   // Try to use shift instructions.
7872   if (SDValue Shift =
7873           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7874     return Shift;
7875
7876   // When loading a scalar and then shuffling it into a vector we can often do
7877   // the insertion cheaply.
7878   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7879           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7880     return Insertion;
7881   // Try inverting the insertion since for v2 masks it is easy to do and we
7882   // can't reliably sort the mask one way or the other.
7883   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7884   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7885           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7886     return Insertion;
7887
7888   // We have different paths for blend lowering, but they all must use the
7889   // *exact* same predicate.
7890   bool IsBlendSupported = Subtarget->hasSSE41();
7891   if (IsBlendSupported)
7892     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7893                                                   Subtarget, DAG))
7894       return Blend;
7895
7896   // Use dedicated unpack instructions for masks that match their pattern.
7897   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7898     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7899   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7900     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7901
7902   // Try to use byte rotation instructions.
7903   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7904   if (Subtarget->hasSSSE3())
7905     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7906             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7907       return Rotate;
7908
7909   // If we have direct support for blends, we should lower by decomposing into
7910   // a permute. That will be faster than the domain cross.
7911   if (IsBlendSupported)
7912     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7913                                                       Mask, DAG);
7914
7915   // We implement this with SHUFPD which is pretty lame because it will likely
7916   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7917   // However, all the alternatives are still more cycles and newer chips don't
7918   // have this problem. It would be really nice if x86 had better shuffles here.
7919   V1 = DAG.getBitcast(MVT::v2f64, V1);
7920   V2 = DAG.getBitcast(MVT::v2f64, V2);
7921   return DAG.getBitcast(MVT::v2i64,
7922                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7923 }
7924
7925 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7926 ///
7927 /// This is used to disable more specialized lowerings when the shufps lowering
7928 /// will happen to be efficient.
7929 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7930   // This routine only handles 128-bit shufps.
7931   assert(Mask.size() == 4 && "Unsupported mask size!");
7932
7933   // To lower with a single SHUFPS we need to have the low half and high half
7934   // each requiring a single input.
7935   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7936     return false;
7937   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7938     return false;
7939
7940   return true;
7941 }
7942
7943 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7944 ///
7945 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7946 /// It makes no assumptions about whether this is the *best* lowering, it simply
7947 /// uses it.
7948 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7949                                             ArrayRef<int> Mask, SDValue V1,
7950                                             SDValue V2, SelectionDAG &DAG) {
7951   SDValue LowV = V1, HighV = V2;
7952   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7953
7954   int NumV2Elements =
7955       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7956
7957   if (NumV2Elements == 1) {
7958     int V2Index =
7959         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7960         Mask.begin();
7961
7962     // Compute the index adjacent to V2Index and in the same half by toggling
7963     // the low bit.
7964     int V2AdjIndex = V2Index ^ 1;
7965
7966     if (Mask[V2AdjIndex] == -1) {
7967       // Handles all the cases where we have a single V2 element and an undef.
7968       // This will only ever happen in the high lanes because we commute the
7969       // vector otherwise.
7970       if (V2Index < 2)
7971         std::swap(LowV, HighV);
7972       NewMask[V2Index] -= 4;
7973     } else {
7974       // Handle the case where the V2 element ends up adjacent to a V1 element.
7975       // To make this work, blend them together as the first step.
7976       int V1Index = V2AdjIndex;
7977       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7978       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7979                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7980
7981       // Now proceed to reconstruct the final blend as we have the necessary
7982       // high or low half formed.
7983       if (V2Index < 2) {
7984         LowV = V2;
7985         HighV = V1;
7986       } else {
7987         HighV = V2;
7988       }
7989       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7990       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7991     }
7992   } else if (NumV2Elements == 2) {
7993     if (Mask[0] < 4 && Mask[1] < 4) {
7994       // Handle the easy case where we have V1 in the low lanes and V2 in the
7995       // high lanes.
7996       NewMask[2] -= 4;
7997       NewMask[3] -= 4;
7998     } else if (Mask[2] < 4 && Mask[3] < 4) {
7999       // We also handle the reversed case because this utility may get called
8000       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8001       // arrange things in the right direction.
8002       NewMask[0] -= 4;
8003       NewMask[1] -= 4;
8004       HighV = V1;
8005       LowV = V2;
8006     } else {
8007       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8008       // trying to place elements directly, just blend them and set up the final
8009       // shuffle to place them.
8010
8011       // The first two blend mask elements are for V1, the second two are for
8012       // V2.
8013       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8014                           Mask[2] < 4 ? Mask[2] : Mask[3],
8015                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8016                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8017       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8018                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8019
8020       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8021       // a blend.
8022       LowV = HighV = V1;
8023       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8024       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8025       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8026       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8027     }
8028   }
8029   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8030                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8031 }
8032
8033 /// \brief Lower 4-lane 32-bit floating point shuffles.
8034 ///
8035 /// Uses instructions exclusively from the floating point unit to minimize
8036 /// domain crossing penalties, as these are sufficient to implement all v4f32
8037 /// shuffles.
8038 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8039                                        const X86Subtarget *Subtarget,
8040                                        SelectionDAG &DAG) {
8041   SDLoc DL(Op);
8042   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8043   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8044   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8046   ArrayRef<int> Mask = SVOp->getMask();
8047   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8048
8049   int NumV2Elements =
8050       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8051
8052   if (NumV2Elements == 0) {
8053     // Check for being able to broadcast a single element.
8054     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8055                                                           Mask, Subtarget, DAG))
8056       return Broadcast;
8057
8058     // Use even/odd duplicate instructions for masks that match their pattern.
8059     if (Subtarget->hasSSE3()) {
8060       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8061         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8062       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8063         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8064     }
8065
8066     if (Subtarget->hasAVX()) {
8067       // If we have AVX, we can use VPERMILPS which will allow folding a load
8068       // into the shuffle.
8069       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8070                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8071     }
8072
8073     // Otherwise, use a straight shuffle of a single input vector. We pass the
8074     // input vector to both operands to simulate this with a SHUFPS.
8075     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8076                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8077   }
8078
8079   // There are special ways we can lower some single-element blends. However, we
8080   // have custom ways we can lower more complex single-element blends below that
8081   // we defer to if both this and BLENDPS fail to match, so restrict this to
8082   // when the V2 input is targeting element 0 of the mask -- that is the fast
8083   // case here.
8084   if (NumV2Elements == 1 && Mask[0] >= 4)
8085     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8086                                                          Mask, Subtarget, DAG))
8087       return V;
8088
8089   if (Subtarget->hasSSE41()) {
8090     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8091                                                   Subtarget, DAG))
8092       return Blend;
8093
8094     // Use INSERTPS if we can complete the shuffle efficiently.
8095     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8096       return V;
8097
8098     if (!isSingleSHUFPSMask(Mask))
8099       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8100               DL, MVT::v4f32, V1, V2, Mask, DAG))
8101         return BlendPerm;
8102   }
8103
8104   // Use dedicated unpack instructions for masks that match their pattern.
8105   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8106     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8107   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8108     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8109   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8110     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8111   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8112     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8113
8114   // Otherwise fall back to a SHUFPS lowering strategy.
8115   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8116 }
8117
8118 /// \brief Lower 4-lane i32 vector shuffles.
8119 ///
8120 /// We try to handle these with integer-domain shuffles where we can, but for
8121 /// blends we use the floating point domain blend instructions.
8122 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8123                                        const X86Subtarget *Subtarget,
8124                                        SelectionDAG &DAG) {
8125   SDLoc DL(Op);
8126   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8127   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8128   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8129   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8130   ArrayRef<int> Mask = SVOp->getMask();
8131   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8132
8133   // Whenever we can lower this as a zext, that instruction is strictly faster
8134   // than any alternative. It also allows us to fold memory operands into the
8135   // shuffle in many cases.
8136   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8137                                                          Mask, Subtarget, DAG))
8138     return ZExt;
8139
8140   int NumV2Elements =
8141       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8142
8143   if (NumV2Elements == 0) {
8144     // Check for being able to broadcast a single element.
8145     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8146                                                           Mask, Subtarget, DAG))
8147       return Broadcast;
8148
8149     // Straight shuffle of a single input vector. For everything from SSE2
8150     // onward this has a single fast instruction with no scary immediates.
8151     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8152     // but we aren't actually going to use the UNPCK instruction because doing
8153     // so prevents folding a load into this instruction or making a copy.
8154     const int UnpackLoMask[] = {0, 0, 1, 1};
8155     const int UnpackHiMask[] = {2, 2, 3, 3};
8156     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8157       Mask = UnpackLoMask;
8158     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8159       Mask = UnpackHiMask;
8160
8161     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8162                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8163   }
8164
8165   // Try to use shift instructions.
8166   if (SDValue Shift =
8167           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8168     return Shift;
8169
8170   // There are special ways we can lower some single-element blends.
8171   if (NumV2Elements == 1)
8172     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8173                                                          Mask, Subtarget, DAG))
8174       return V;
8175
8176   // We have different paths for blend lowering, but they all must use the
8177   // *exact* same predicate.
8178   bool IsBlendSupported = Subtarget->hasSSE41();
8179   if (IsBlendSupported)
8180     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8181                                                   Subtarget, DAG))
8182       return Blend;
8183
8184   if (SDValue Masked =
8185           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8186     return Masked;
8187
8188   // Use dedicated unpack instructions for masks that match their pattern.
8189   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8190     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8191   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8192     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8193   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8194     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8195   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8196     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8197
8198   // Try to use byte rotation instructions.
8199   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8200   if (Subtarget->hasSSSE3())
8201     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8202             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8203       return Rotate;
8204
8205   // If we have direct support for blends, we should lower by decomposing into
8206   // a permute. That will be faster than the domain cross.
8207   if (IsBlendSupported)
8208     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8209                                                       Mask, DAG);
8210
8211   // Try to lower by permuting the inputs into an unpack instruction.
8212   if (SDValue Unpack =
8213           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8214     return Unpack;
8215
8216   // We implement this with SHUFPS because it can blend from two vectors.
8217   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8218   // up the inputs, bypassing domain shift penalties that we would encur if we
8219   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8220   // relevant.
8221   return DAG.getBitcast(
8222       MVT::v4i32,
8223       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8224                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8225 }
8226
8227 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8228 /// shuffle lowering, and the most complex part.
8229 ///
8230 /// The lowering strategy is to try to form pairs of input lanes which are
8231 /// targeted at the same half of the final vector, and then use a dword shuffle
8232 /// to place them onto the right half, and finally unpack the paired lanes into
8233 /// their final position.
8234 ///
8235 /// The exact breakdown of how to form these dword pairs and align them on the
8236 /// correct sides is really tricky. See the comments within the function for
8237 /// more of the details.
8238 ///
8239 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8240 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8241 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8242 /// vector, form the analogous 128-bit 8-element Mask.
8243 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8244     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8245     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8246   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8247   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8248
8249   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8250   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8251   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8252
8253   SmallVector<int, 4> LoInputs;
8254   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8255                [](int M) { return M >= 0; });
8256   std::sort(LoInputs.begin(), LoInputs.end());
8257   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8258   SmallVector<int, 4> HiInputs;
8259   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8260                [](int M) { return M >= 0; });
8261   std::sort(HiInputs.begin(), HiInputs.end());
8262   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8263   int NumLToL =
8264       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8265   int NumHToL = LoInputs.size() - NumLToL;
8266   int NumLToH =
8267       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8268   int NumHToH = HiInputs.size() - NumLToH;
8269   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8270   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8271   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8272   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8273
8274   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8275   // such inputs we can swap two of the dwords across the half mark and end up
8276   // with <=2 inputs to each half in each half. Once there, we can fall through
8277   // to the generic code below. For example:
8278   //
8279   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8280   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8281   //
8282   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8283   // and an existing 2-into-2 on the other half. In this case we may have to
8284   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8285   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8286   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8287   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8288   // half than the one we target for fixing) will be fixed when we re-enter this
8289   // path. We will also combine away any sequence of PSHUFD instructions that
8290   // result into a single instruction. Here is an example of the tricky case:
8291   //
8292   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8293   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8294   //
8295   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8296   //
8297   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8298   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8299   //
8300   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8301   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8302   //
8303   // The result is fine to be handled by the generic logic.
8304   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8305                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8306                           int AOffset, int BOffset) {
8307     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8308            "Must call this with A having 3 or 1 inputs from the A half.");
8309     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8310            "Must call this with B having 1 or 3 inputs from the B half.");
8311     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8312            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8313
8314     // Compute the index of dword with only one word among the three inputs in
8315     // a half by taking the sum of the half with three inputs and subtracting
8316     // the sum of the actual three inputs. The difference is the remaining
8317     // slot.
8318     int ADWord, BDWord;
8319     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8320     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8321     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8322     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8323     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8324     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8325     int TripleNonInputIdx =
8326         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8327     TripleDWord = TripleNonInputIdx / 2;
8328
8329     // We use xor with one to compute the adjacent DWord to whichever one the
8330     // OneInput is in.
8331     OneInputDWord = (OneInput / 2) ^ 1;
8332
8333     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8334     // and BToA inputs. If there is also such a problem with the BToB and AToB
8335     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8336     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8337     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8338     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8339       // Compute how many inputs will be flipped by swapping these DWords. We
8340       // need
8341       // to balance this to ensure we don't form a 3-1 shuffle in the other
8342       // half.
8343       int NumFlippedAToBInputs =
8344           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8345           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8346       int NumFlippedBToBInputs =
8347           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8348           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8349       if ((NumFlippedAToBInputs == 1 &&
8350            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8351           (NumFlippedBToBInputs == 1 &&
8352            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8353         // We choose whether to fix the A half or B half based on whether that
8354         // half has zero flipped inputs. At zero, we may not be able to fix it
8355         // with that half. We also bias towards fixing the B half because that
8356         // will more commonly be the high half, and we have to bias one way.
8357         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8358                                                        ArrayRef<int> Inputs) {
8359           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8360           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8361                                          PinnedIdx ^ 1) != Inputs.end();
8362           // Determine whether the free index is in the flipped dword or the
8363           // unflipped dword based on where the pinned index is. We use this bit
8364           // in an xor to conditionally select the adjacent dword.
8365           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8366           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8367                                              FixFreeIdx) != Inputs.end();
8368           if (IsFixIdxInput == IsFixFreeIdxInput)
8369             FixFreeIdx += 1;
8370           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8371                                         FixFreeIdx) != Inputs.end();
8372           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8373                  "We need to be changing the number of flipped inputs!");
8374           int PSHUFHalfMask[] = {0, 1, 2, 3};
8375           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8376           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8377                           MVT::v8i16, V,
8378                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8379
8380           for (int &M : Mask)
8381             if (M != -1 && M == FixIdx)
8382               M = FixFreeIdx;
8383             else if (M != -1 && M == FixFreeIdx)
8384               M = FixIdx;
8385         };
8386         if (NumFlippedBToBInputs != 0) {
8387           int BPinnedIdx =
8388               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8389           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8390         } else {
8391           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8392           int APinnedIdx =
8393               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8394           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8395         }
8396       }
8397     }
8398
8399     int PSHUFDMask[] = {0, 1, 2, 3};
8400     PSHUFDMask[ADWord] = BDWord;
8401     PSHUFDMask[BDWord] = ADWord;
8402     V = DAG.getBitcast(
8403         VT,
8404         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8405                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8406
8407     // Adjust the mask to match the new locations of A and B.
8408     for (int &M : Mask)
8409       if (M != -1 && M/2 == ADWord)
8410         M = 2 * BDWord + M % 2;
8411       else if (M != -1 && M/2 == BDWord)
8412         M = 2 * ADWord + M % 2;
8413
8414     // Recurse back into this routine to re-compute state now that this isn't
8415     // a 3 and 1 problem.
8416     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8417                                                      DAG);
8418   };
8419   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8420     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8421   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8422     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8423
8424   // At this point there are at most two inputs to the low and high halves from
8425   // each half. That means the inputs can always be grouped into dwords and
8426   // those dwords can then be moved to the correct half with a dword shuffle.
8427   // We use at most one low and one high word shuffle to collect these paired
8428   // inputs into dwords, and finally a dword shuffle to place them.
8429   int PSHUFLMask[4] = {-1, -1, -1, -1};
8430   int PSHUFHMask[4] = {-1, -1, -1, -1};
8431   int PSHUFDMask[4] = {-1, -1, -1, -1};
8432
8433   // First fix the masks for all the inputs that are staying in their
8434   // original halves. This will then dictate the targets of the cross-half
8435   // shuffles.
8436   auto fixInPlaceInputs =
8437       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8438                     MutableArrayRef<int> SourceHalfMask,
8439                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8440     if (InPlaceInputs.empty())
8441       return;
8442     if (InPlaceInputs.size() == 1) {
8443       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8444           InPlaceInputs[0] - HalfOffset;
8445       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8446       return;
8447     }
8448     if (IncomingInputs.empty()) {
8449       // Just fix all of the in place inputs.
8450       for (int Input : InPlaceInputs) {
8451         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8452         PSHUFDMask[Input / 2] = Input / 2;
8453       }
8454       return;
8455     }
8456
8457     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8458     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8459         InPlaceInputs[0] - HalfOffset;
8460     // Put the second input next to the first so that they are packed into
8461     // a dword. We find the adjacent index by toggling the low bit.
8462     int AdjIndex = InPlaceInputs[0] ^ 1;
8463     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8464     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8465     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8466   };
8467   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8468   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8469
8470   // Now gather the cross-half inputs and place them into a free dword of
8471   // their target half.
8472   // FIXME: This operation could almost certainly be simplified dramatically to
8473   // look more like the 3-1 fixing operation.
8474   auto moveInputsToRightHalf = [&PSHUFDMask](
8475       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8476       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8477       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8478       int DestOffset) {
8479     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8480       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8481     };
8482     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8483                                                int Word) {
8484       int LowWord = Word & ~1;
8485       int HighWord = Word | 1;
8486       return isWordClobbered(SourceHalfMask, LowWord) ||
8487              isWordClobbered(SourceHalfMask, HighWord);
8488     };
8489
8490     if (IncomingInputs.empty())
8491       return;
8492
8493     if (ExistingInputs.empty()) {
8494       // Map any dwords with inputs from them into the right half.
8495       for (int Input : IncomingInputs) {
8496         // If the source half mask maps over the inputs, turn those into
8497         // swaps and use the swapped lane.
8498         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8499           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8500             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8501                 Input - SourceOffset;
8502             // We have to swap the uses in our half mask in one sweep.
8503             for (int &M : HalfMask)
8504               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8505                 M = Input;
8506               else if (M == Input)
8507                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8508           } else {
8509             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8510                        Input - SourceOffset &&
8511                    "Previous placement doesn't match!");
8512           }
8513           // Note that this correctly re-maps both when we do a swap and when
8514           // we observe the other side of the swap above. We rely on that to
8515           // avoid swapping the members of the input list directly.
8516           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8517         }
8518
8519         // Map the input's dword into the correct half.
8520         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8521           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8522         else
8523           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8524                      Input / 2 &&
8525                  "Previous placement doesn't match!");
8526       }
8527
8528       // And just directly shift any other-half mask elements to be same-half
8529       // as we will have mirrored the dword containing the element into the
8530       // same position within that half.
8531       for (int &M : HalfMask)
8532         if (M >= SourceOffset && M < SourceOffset + 4) {
8533           M = M - SourceOffset + DestOffset;
8534           assert(M >= 0 && "This should never wrap below zero!");
8535         }
8536       return;
8537     }
8538
8539     // Ensure we have the input in a viable dword of its current half. This
8540     // is particularly tricky because the original position may be clobbered
8541     // by inputs being moved and *staying* in that half.
8542     if (IncomingInputs.size() == 1) {
8543       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8544         int InputFixed = std::find(std::begin(SourceHalfMask),
8545                                    std::end(SourceHalfMask), -1) -
8546                          std::begin(SourceHalfMask) + SourceOffset;
8547         SourceHalfMask[InputFixed - SourceOffset] =
8548             IncomingInputs[0] - SourceOffset;
8549         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8550                      InputFixed);
8551         IncomingInputs[0] = InputFixed;
8552       }
8553     } else if (IncomingInputs.size() == 2) {
8554       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8555           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8556         // We have two non-adjacent or clobbered inputs we need to extract from
8557         // the source half. To do this, we need to map them into some adjacent
8558         // dword slot in the source mask.
8559         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8560                               IncomingInputs[1] - SourceOffset};
8561
8562         // If there is a free slot in the source half mask adjacent to one of
8563         // the inputs, place the other input in it. We use (Index XOR 1) to
8564         // compute an adjacent index.
8565         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8566             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8567           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8568           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8569           InputsFixed[1] = InputsFixed[0] ^ 1;
8570         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8571                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8572           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8573           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8574           InputsFixed[0] = InputsFixed[1] ^ 1;
8575         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8576                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8577           // The two inputs are in the same DWord but it is clobbered and the
8578           // adjacent DWord isn't used at all. Move both inputs to the free
8579           // slot.
8580           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8581           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8582           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8583           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8584         } else {
8585           // The only way we hit this point is if there is no clobbering
8586           // (because there are no off-half inputs to this half) and there is no
8587           // free slot adjacent to one of the inputs. In this case, we have to
8588           // swap an input with a non-input.
8589           for (int i = 0; i < 4; ++i)
8590             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8591                    "We can't handle any clobbers here!");
8592           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8593                  "Cannot have adjacent inputs here!");
8594
8595           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8596           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8597
8598           // We also have to update the final source mask in this case because
8599           // it may need to undo the above swap.
8600           for (int &M : FinalSourceHalfMask)
8601             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8602               M = InputsFixed[1] + SourceOffset;
8603             else if (M == InputsFixed[1] + SourceOffset)
8604               M = (InputsFixed[0] ^ 1) + SourceOffset;
8605
8606           InputsFixed[1] = InputsFixed[0] ^ 1;
8607         }
8608
8609         // Point everything at the fixed inputs.
8610         for (int &M : HalfMask)
8611           if (M == IncomingInputs[0])
8612             M = InputsFixed[0] + SourceOffset;
8613           else if (M == IncomingInputs[1])
8614             M = InputsFixed[1] + SourceOffset;
8615
8616         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8617         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8618       }
8619     } else {
8620       llvm_unreachable("Unhandled input size!");
8621     }
8622
8623     // Now hoist the DWord down to the right half.
8624     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8625     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8626     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8627     for (int &M : HalfMask)
8628       for (int Input : IncomingInputs)
8629         if (M == Input)
8630           M = FreeDWord * 2 + Input % 2;
8631   };
8632   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8633                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8634   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8635                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8636
8637   // Now enact all the shuffles we've computed to move the inputs into their
8638   // target half.
8639   if (!isNoopShuffleMask(PSHUFLMask))
8640     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8641                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8642   if (!isNoopShuffleMask(PSHUFHMask))
8643     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8644                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8645   if (!isNoopShuffleMask(PSHUFDMask))
8646     V = DAG.getBitcast(
8647         VT,
8648         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8649                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8650
8651   // At this point, each half should contain all its inputs, and we can then
8652   // just shuffle them into their final position.
8653   assert(std::count_if(LoMask.begin(), LoMask.end(),
8654                        [](int M) { return M >= 4; }) == 0 &&
8655          "Failed to lift all the high half inputs to the low mask!");
8656   assert(std::count_if(HiMask.begin(), HiMask.end(),
8657                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8658          "Failed to lift all the low half inputs to the high mask!");
8659
8660   // Do a half shuffle for the low mask.
8661   if (!isNoopShuffleMask(LoMask))
8662     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8663                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8664
8665   // Do a half shuffle with the high mask after shifting its values down.
8666   for (int &M : HiMask)
8667     if (M >= 0)
8668       M -= 4;
8669   if (!isNoopShuffleMask(HiMask))
8670     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8671                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8672
8673   return V;
8674 }
8675
8676 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8677 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8678                                           SDValue V2, ArrayRef<int> Mask,
8679                                           SelectionDAG &DAG, bool &V1InUse,
8680                                           bool &V2InUse) {
8681   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8682   SDValue V1Mask[16];
8683   SDValue V2Mask[16];
8684   V1InUse = false;
8685   V2InUse = false;
8686
8687   int Size = Mask.size();
8688   int Scale = 16 / Size;
8689   for (int i = 0; i < 16; ++i) {
8690     if (Mask[i / Scale] == -1) {
8691       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8692     } else {
8693       const int ZeroMask = 0x80;
8694       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8695                                           : ZeroMask;
8696       int V2Idx = Mask[i / Scale] < Size
8697                       ? ZeroMask
8698                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8699       if (Zeroable[i / Scale])
8700         V1Idx = V2Idx = ZeroMask;
8701       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8702       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8703       V1InUse |= (ZeroMask != V1Idx);
8704       V2InUse |= (ZeroMask != V2Idx);
8705     }
8706   }
8707
8708   if (V1InUse)
8709     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8710                      DAG.getBitcast(MVT::v16i8, V1),
8711                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8712   if (V2InUse)
8713     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8714                      DAG.getBitcast(MVT::v16i8, V2),
8715                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8716
8717   // If we need shuffled inputs from both, blend the two.
8718   SDValue V;
8719   if (V1InUse && V2InUse)
8720     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8721   else
8722     V = V1InUse ? V1 : V2;
8723
8724   // Cast the result back to the correct type.
8725   return DAG.getBitcast(VT, V);
8726 }
8727
8728 /// \brief Generic lowering of 8-lane i16 shuffles.
8729 ///
8730 /// This handles both single-input shuffles and combined shuffle/blends with
8731 /// two inputs. The single input shuffles are immediately delegated to
8732 /// a dedicated lowering routine.
8733 ///
8734 /// The blends are lowered in one of three fundamental ways. If there are few
8735 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8736 /// of the input is significantly cheaper when lowered as an interleaving of
8737 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8738 /// halves of the inputs separately (making them have relatively few inputs)
8739 /// and then concatenate them.
8740 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8741                                        const X86Subtarget *Subtarget,
8742                                        SelectionDAG &DAG) {
8743   SDLoc DL(Op);
8744   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8745   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8746   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8747   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8748   ArrayRef<int> OrigMask = SVOp->getMask();
8749   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8750                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8751   MutableArrayRef<int> Mask(MaskStorage);
8752
8753   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8754
8755   // Whenever we can lower this as a zext, that instruction is strictly faster
8756   // than any alternative.
8757   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8758           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8759     return ZExt;
8760
8761   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8762   (void)isV1;
8763   auto isV2 = [](int M) { return M >= 8; };
8764
8765   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8766
8767   if (NumV2Inputs == 0) {
8768     // Check for being able to broadcast a single element.
8769     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8770                                                           Mask, Subtarget, DAG))
8771       return Broadcast;
8772
8773     // Try to use shift instructions.
8774     if (SDValue Shift =
8775             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8776       return Shift;
8777
8778     // Use dedicated unpack instructions for masks that match their pattern.
8779     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8780       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8781     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8782       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8783
8784     // Try to use byte rotation instructions.
8785     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8786                                                         Mask, Subtarget, DAG))
8787       return Rotate;
8788
8789     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8790                                                      Subtarget, DAG);
8791   }
8792
8793   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8794          "All single-input shuffles should be canonicalized to be V1-input "
8795          "shuffles.");
8796
8797   // Try to use shift instructions.
8798   if (SDValue Shift =
8799           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8800     return Shift;
8801
8802   // See if we can use SSE4A Extraction / Insertion.
8803   if (Subtarget->hasSSE4A())
8804     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8805       return V;
8806
8807   // There are special ways we can lower some single-element blends.
8808   if (NumV2Inputs == 1)
8809     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8810                                                          Mask, Subtarget, DAG))
8811       return V;
8812
8813   // We have different paths for blend lowering, but they all must use the
8814   // *exact* same predicate.
8815   bool IsBlendSupported = Subtarget->hasSSE41();
8816   if (IsBlendSupported)
8817     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8818                                                   Subtarget, DAG))
8819       return Blend;
8820
8821   if (SDValue Masked =
8822           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8823     return Masked;
8824
8825   // Use dedicated unpack instructions for masks that match their pattern.
8826   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8827     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8828   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8829     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8830
8831   // Try to use byte rotation instructions.
8832   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8833           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8834     return Rotate;
8835
8836   if (SDValue BitBlend =
8837           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8838     return BitBlend;
8839
8840   if (SDValue Unpack =
8841           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8842     return Unpack;
8843
8844   // If we can't directly blend but can use PSHUFB, that will be better as it
8845   // can both shuffle and set up the inefficient blend.
8846   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8847     bool V1InUse, V2InUse;
8848     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8849                                       V1InUse, V2InUse);
8850   }
8851
8852   // We can always bit-blend if we have to so the fallback strategy is to
8853   // decompose into single-input permutes and blends.
8854   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8855                                                       Mask, DAG);
8856 }
8857
8858 /// \brief Check whether a compaction lowering can be done by dropping even
8859 /// elements and compute how many times even elements must be dropped.
8860 ///
8861 /// This handles shuffles which take every Nth element where N is a power of
8862 /// two. Example shuffle masks:
8863 ///
8864 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8865 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8866 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8867 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8868 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8869 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8870 ///
8871 /// Any of these lanes can of course be undef.
8872 ///
8873 /// This routine only supports N <= 3.
8874 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8875 /// for larger N.
8876 ///
8877 /// \returns N above, or the number of times even elements must be dropped if
8878 /// there is such a number. Otherwise returns zero.
8879 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8880   // Figure out whether we're looping over two inputs or just one.
8881   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8882
8883   // The modulus for the shuffle vector entries is based on whether this is
8884   // a single input or not.
8885   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8886   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8887          "We should only be called with masks with a power-of-2 size!");
8888
8889   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8890
8891   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8892   // and 2^3 simultaneously. This is because we may have ambiguity with
8893   // partially undef inputs.
8894   bool ViableForN[3] = {true, true, true};
8895
8896   for (int i = 0, e = Mask.size(); i < e; ++i) {
8897     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8898     // want.
8899     if (Mask[i] == -1)
8900       continue;
8901
8902     bool IsAnyViable = false;
8903     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8904       if (ViableForN[j]) {
8905         uint64_t N = j + 1;
8906
8907         // The shuffle mask must be equal to (i * 2^N) % M.
8908         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8909           IsAnyViable = true;
8910         else
8911           ViableForN[j] = false;
8912       }
8913     // Early exit if we exhaust the possible powers of two.
8914     if (!IsAnyViable)
8915       break;
8916   }
8917
8918   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8919     if (ViableForN[j])
8920       return j + 1;
8921
8922   // Return 0 as there is no viable power of two.
8923   return 0;
8924 }
8925
8926 /// \brief Generic lowering of v16i8 shuffles.
8927 ///
8928 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8929 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8930 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8931 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8932 /// back together.
8933 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8934                                        const X86Subtarget *Subtarget,
8935                                        SelectionDAG &DAG) {
8936   SDLoc DL(Op);
8937   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8938   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8939   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8941   ArrayRef<int> Mask = SVOp->getMask();
8942   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8943
8944   // Try to use shift instructions.
8945   if (SDValue Shift =
8946           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8947     return Shift;
8948
8949   // Try to use byte rotation instructions.
8950   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8951           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8952     return Rotate;
8953
8954   // Try to use a zext lowering.
8955   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8956           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8957     return ZExt;
8958
8959   // See if we can use SSE4A Extraction / Insertion.
8960   if (Subtarget->hasSSE4A())
8961     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8962       return V;
8963
8964   int NumV2Elements =
8965       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8966
8967   // For single-input shuffles, there are some nicer lowering tricks we can use.
8968   if (NumV2Elements == 0) {
8969     // Check for being able to broadcast a single element.
8970     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8971                                                           Mask, Subtarget, DAG))
8972       return Broadcast;
8973
8974     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8975     // Notably, this handles splat and partial-splat shuffles more efficiently.
8976     // However, it only makes sense if the pre-duplication shuffle simplifies
8977     // things significantly. Currently, this means we need to be able to
8978     // express the pre-duplication shuffle as an i16 shuffle.
8979     //
8980     // FIXME: We should check for other patterns which can be widened into an
8981     // i16 shuffle as well.
8982     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8983       for (int i = 0; i < 16; i += 2)
8984         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8985           return false;
8986
8987       return true;
8988     };
8989     auto tryToWidenViaDuplication = [&]() -> SDValue {
8990       if (!canWidenViaDuplication(Mask))
8991         return SDValue();
8992       SmallVector<int, 4> LoInputs;
8993       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8994                    [](int M) { return M >= 0 && M < 8; });
8995       std::sort(LoInputs.begin(), LoInputs.end());
8996       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8997                      LoInputs.end());
8998       SmallVector<int, 4> HiInputs;
8999       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9000                    [](int M) { return M >= 8; });
9001       std::sort(HiInputs.begin(), HiInputs.end());
9002       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9003                      HiInputs.end());
9004
9005       bool TargetLo = LoInputs.size() >= HiInputs.size();
9006       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9007       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9008
9009       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9010       SmallDenseMap<int, int, 8> LaneMap;
9011       for (int I : InPlaceInputs) {
9012         PreDupI16Shuffle[I/2] = I/2;
9013         LaneMap[I] = I;
9014       }
9015       int j = TargetLo ? 0 : 4, je = j + 4;
9016       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9017         // Check if j is already a shuffle of this input. This happens when
9018         // there are two adjacent bytes after we move the low one.
9019         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9020           // If we haven't yet mapped the input, search for a slot into which
9021           // we can map it.
9022           while (j < je && PreDupI16Shuffle[j] != -1)
9023             ++j;
9024
9025           if (j == je)
9026             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9027             return SDValue();
9028
9029           // Map this input with the i16 shuffle.
9030           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9031         }
9032
9033         // Update the lane map based on the mapping we ended up with.
9034         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9035       }
9036       V1 = DAG.getBitcast(
9037           MVT::v16i8,
9038           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9039                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9040
9041       // Unpack the bytes to form the i16s that will be shuffled into place.
9042       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9043                        MVT::v16i8, V1, V1);
9044
9045       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9046       for (int i = 0; i < 16; ++i)
9047         if (Mask[i] != -1) {
9048           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9049           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9050           if (PostDupI16Shuffle[i / 2] == -1)
9051             PostDupI16Shuffle[i / 2] = MappedMask;
9052           else
9053             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9054                    "Conflicting entrties in the original shuffle!");
9055         }
9056       return DAG.getBitcast(
9057           MVT::v16i8,
9058           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9059                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9060     };
9061     if (SDValue V = tryToWidenViaDuplication())
9062       return V;
9063   }
9064
9065   // Use dedicated unpack instructions for masks that match their pattern.
9066   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9067                                          0, 16, 1, 17, 2, 18, 3, 19,
9068                                          // High half.
9069                                          4, 20, 5, 21, 6, 22, 7, 23}))
9070     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9071   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9072                                          8, 24, 9, 25, 10, 26, 11, 27,
9073                                          // High half.
9074                                          12, 28, 13, 29, 14, 30, 15, 31}))
9075     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9076
9077   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9078   // with PSHUFB. It is important to do this before we attempt to generate any
9079   // blends but after all of the single-input lowerings. If the single input
9080   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9081   // want to preserve that and we can DAG combine any longer sequences into
9082   // a PSHUFB in the end. But once we start blending from multiple inputs,
9083   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9084   // and there are *very* few patterns that would actually be faster than the
9085   // PSHUFB approach because of its ability to zero lanes.
9086   //
9087   // FIXME: The only exceptions to the above are blends which are exact
9088   // interleavings with direct instructions supporting them. We currently don't
9089   // handle those well here.
9090   if (Subtarget->hasSSSE3()) {
9091     bool V1InUse = false;
9092     bool V2InUse = false;
9093
9094     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9095                                                 DAG, V1InUse, V2InUse);
9096
9097     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9098     // do so. This avoids using them to handle blends-with-zero which is
9099     // important as a single pshufb is significantly faster for that.
9100     if (V1InUse && V2InUse) {
9101       if (Subtarget->hasSSE41())
9102         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9103                                                       Mask, Subtarget, DAG))
9104           return Blend;
9105
9106       // We can use an unpack to do the blending rather than an or in some
9107       // cases. Even though the or may be (very minorly) more efficient, we
9108       // preference this lowering because there are common cases where part of
9109       // the complexity of the shuffles goes away when we do the final blend as
9110       // an unpack.
9111       // FIXME: It might be worth trying to detect if the unpack-feeding
9112       // shuffles will both be pshufb, in which case we shouldn't bother with
9113       // this.
9114       if (SDValue Unpack =
9115               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9116         return Unpack;
9117     }
9118
9119     return PSHUFB;
9120   }
9121
9122   // There are special ways we can lower some single-element blends.
9123   if (NumV2Elements == 1)
9124     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9125                                                          Mask, Subtarget, DAG))
9126       return V;
9127
9128   if (SDValue BitBlend =
9129           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9130     return BitBlend;
9131
9132   // Check whether a compaction lowering can be done. This handles shuffles
9133   // which take every Nth element for some even N. See the helper function for
9134   // details.
9135   //
9136   // We special case these as they can be particularly efficiently handled with
9137   // the PACKUSB instruction on x86 and they show up in common patterns of
9138   // rearranging bytes to truncate wide elements.
9139   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9140     // NumEvenDrops is the power of two stride of the elements. Another way of
9141     // thinking about it is that we need to drop the even elements this many
9142     // times to get the original input.
9143     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9144
9145     // First we need to zero all the dropped bytes.
9146     assert(NumEvenDrops <= 3 &&
9147            "No support for dropping even elements more than 3 times.");
9148     // We use the mask type to pick which bytes are preserved based on how many
9149     // elements are dropped.
9150     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9151     SDValue ByteClearMask = DAG.getBitcast(
9152         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9153     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9154     if (!IsSingleInput)
9155       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9156
9157     // Now pack things back together.
9158     V1 = DAG.getBitcast(MVT::v8i16, V1);
9159     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9160     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9161     for (int i = 1; i < NumEvenDrops; ++i) {
9162       Result = DAG.getBitcast(MVT::v8i16, Result);
9163       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9164     }
9165
9166     return Result;
9167   }
9168
9169   // Handle multi-input cases by blending single-input shuffles.
9170   if (NumV2Elements > 0)
9171     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9172                                                       Mask, DAG);
9173
9174   // The fallback path for single-input shuffles widens this into two v8i16
9175   // vectors with unpacks, shuffles those, and then pulls them back together
9176   // with a pack.
9177   SDValue V = V1;
9178
9179   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9180   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9181   for (int i = 0; i < 16; ++i)
9182     if (Mask[i] >= 0)
9183       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9184
9185   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9186
9187   SDValue VLoHalf, VHiHalf;
9188   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9189   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9190   // i16s.
9191   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9192                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9193       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9194                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9195     // Use a mask to drop the high bytes.
9196     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9197     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9198                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9199
9200     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9201     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9202
9203     // Squash the masks to point directly into VLoHalf.
9204     for (int &M : LoBlendMask)
9205       if (M >= 0)
9206         M /= 2;
9207     for (int &M : HiBlendMask)
9208       if (M >= 0)
9209         M /= 2;
9210   } else {
9211     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9212     // VHiHalf so that we can blend them as i16s.
9213     VLoHalf = DAG.getBitcast(
9214         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9215     VHiHalf = DAG.getBitcast(
9216         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9217   }
9218
9219   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9220   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9221
9222   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9223 }
9224
9225 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9226 ///
9227 /// This routine breaks down the specific type of 128-bit shuffle and
9228 /// dispatches to the lowering routines accordingly.
9229 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9230                                         MVT VT, const X86Subtarget *Subtarget,
9231                                         SelectionDAG &DAG) {
9232   switch (VT.SimpleTy) {
9233   case MVT::v2i64:
9234     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9235   case MVT::v2f64:
9236     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9237   case MVT::v4i32:
9238     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9239   case MVT::v4f32:
9240     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9241   case MVT::v8i16:
9242     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9243   case MVT::v16i8:
9244     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9245
9246   default:
9247     llvm_unreachable("Unimplemented!");
9248   }
9249 }
9250
9251 /// \brief Helper function to test whether a shuffle mask could be
9252 /// simplified by widening the elements being shuffled.
9253 ///
9254 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9255 /// leaves it in an unspecified state.
9256 ///
9257 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9258 /// shuffle masks. The latter have the special property of a '-2' representing
9259 /// a zero-ed lane of a vector.
9260 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9261                                     SmallVectorImpl<int> &WidenedMask) {
9262   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9263     // If both elements are undef, its trivial.
9264     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9265       WidenedMask.push_back(SM_SentinelUndef);
9266       continue;
9267     }
9268
9269     // Check for an undef mask and a mask value properly aligned to fit with
9270     // a pair of values. If we find such a case, use the non-undef mask's value.
9271     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9272       WidenedMask.push_back(Mask[i + 1] / 2);
9273       continue;
9274     }
9275     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9276       WidenedMask.push_back(Mask[i] / 2);
9277       continue;
9278     }
9279
9280     // When zeroing, we need to spread the zeroing across both lanes to widen.
9281     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9282       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9283           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9284         WidenedMask.push_back(SM_SentinelZero);
9285         continue;
9286       }
9287       return false;
9288     }
9289
9290     // Finally check if the two mask values are adjacent and aligned with
9291     // a pair.
9292     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9293       WidenedMask.push_back(Mask[i] / 2);
9294       continue;
9295     }
9296
9297     // Otherwise we can't safely widen the elements used in this shuffle.
9298     return false;
9299   }
9300   assert(WidenedMask.size() == Mask.size() / 2 &&
9301          "Incorrect size of mask after widening the elements!");
9302
9303   return true;
9304 }
9305
9306 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9307 ///
9308 /// This routine just extracts two subvectors, shuffles them independently, and
9309 /// then concatenates them back together. This should work effectively with all
9310 /// AVX vector shuffle types.
9311 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9312                                           SDValue V2, ArrayRef<int> Mask,
9313                                           SelectionDAG &DAG) {
9314   assert(VT.getSizeInBits() >= 256 &&
9315          "Only for 256-bit or wider vector shuffles!");
9316   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9317   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9318
9319   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9320   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9321
9322   int NumElements = VT.getVectorNumElements();
9323   int SplitNumElements = NumElements / 2;
9324   MVT ScalarVT = VT.getScalarType();
9325   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9326
9327   // Rather than splitting build-vectors, just build two narrower build
9328   // vectors. This helps shuffling with splats and zeros.
9329   auto SplitVector = [&](SDValue V) {
9330     while (V.getOpcode() == ISD::BITCAST)
9331       V = V->getOperand(0);
9332
9333     MVT OrigVT = V.getSimpleValueType();
9334     int OrigNumElements = OrigVT.getVectorNumElements();
9335     int OrigSplitNumElements = OrigNumElements / 2;
9336     MVT OrigScalarVT = OrigVT.getScalarType();
9337     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9338
9339     SDValue LoV, HiV;
9340
9341     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9342     if (!BV) {
9343       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9344                         DAG.getIntPtrConstant(0, DL));
9345       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9346                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9347     } else {
9348
9349       SmallVector<SDValue, 16> LoOps, HiOps;
9350       for (int i = 0; i < OrigSplitNumElements; ++i) {
9351         LoOps.push_back(BV->getOperand(i));
9352         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9353       }
9354       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9355       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9356     }
9357     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9358                           DAG.getBitcast(SplitVT, HiV));
9359   };
9360
9361   SDValue LoV1, HiV1, LoV2, HiV2;
9362   std::tie(LoV1, HiV1) = SplitVector(V1);
9363   std::tie(LoV2, HiV2) = SplitVector(V2);
9364
9365   // Now create two 4-way blends of these half-width vectors.
9366   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9367     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9368     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9369     for (int i = 0; i < SplitNumElements; ++i) {
9370       int M = HalfMask[i];
9371       if (M >= NumElements) {
9372         if (M >= NumElements + SplitNumElements)
9373           UseHiV2 = true;
9374         else
9375           UseLoV2 = true;
9376         V2BlendMask.push_back(M - NumElements);
9377         V1BlendMask.push_back(-1);
9378         BlendMask.push_back(SplitNumElements + i);
9379       } else if (M >= 0) {
9380         if (M >= SplitNumElements)
9381           UseHiV1 = true;
9382         else
9383           UseLoV1 = true;
9384         V2BlendMask.push_back(-1);
9385         V1BlendMask.push_back(M);
9386         BlendMask.push_back(i);
9387       } else {
9388         V2BlendMask.push_back(-1);
9389         V1BlendMask.push_back(-1);
9390         BlendMask.push_back(-1);
9391       }
9392     }
9393
9394     // Because the lowering happens after all combining takes place, we need to
9395     // manually combine these blend masks as much as possible so that we create
9396     // a minimal number of high-level vector shuffle nodes.
9397
9398     // First try just blending the halves of V1 or V2.
9399     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9400       return DAG.getUNDEF(SplitVT);
9401     if (!UseLoV2 && !UseHiV2)
9402       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9403     if (!UseLoV1 && !UseHiV1)
9404       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9405
9406     SDValue V1Blend, V2Blend;
9407     if (UseLoV1 && UseHiV1) {
9408       V1Blend =
9409         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9410     } else {
9411       // We only use half of V1 so map the usage down into the final blend mask.
9412       V1Blend = UseLoV1 ? LoV1 : HiV1;
9413       for (int i = 0; i < SplitNumElements; ++i)
9414         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9415           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9416     }
9417     if (UseLoV2 && UseHiV2) {
9418       V2Blend =
9419         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9420     } else {
9421       // We only use half of V2 so map the usage down into the final blend mask.
9422       V2Blend = UseLoV2 ? LoV2 : HiV2;
9423       for (int i = 0; i < SplitNumElements; ++i)
9424         if (BlendMask[i] >= SplitNumElements)
9425           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9426     }
9427     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9428   };
9429   SDValue Lo = HalfBlend(LoMask);
9430   SDValue Hi = HalfBlend(HiMask);
9431   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9432 }
9433
9434 /// \brief Either split a vector in halves or decompose the shuffles and the
9435 /// blend.
9436 ///
9437 /// This is provided as a good fallback for many lowerings of non-single-input
9438 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9439 /// between splitting the shuffle into 128-bit components and stitching those
9440 /// back together vs. extracting the single-input shuffles and blending those
9441 /// results.
9442 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9443                                                 SDValue V2, ArrayRef<int> Mask,
9444                                                 SelectionDAG &DAG) {
9445   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9446                                             "lower single-input shuffles as it "
9447                                             "could then recurse on itself.");
9448   int Size = Mask.size();
9449
9450   // If this can be modeled as a broadcast of two elements followed by a blend,
9451   // prefer that lowering. This is especially important because broadcasts can
9452   // often fold with memory operands.
9453   auto DoBothBroadcast = [&] {
9454     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9455     for (int M : Mask)
9456       if (M >= Size) {
9457         if (V2BroadcastIdx == -1)
9458           V2BroadcastIdx = M - Size;
9459         else if (M - Size != V2BroadcastIdx)
9460           return false;
9461       } else if (M >= 0) {
9462         if (V1BroadcastIdx == -1)
9463           V1BroadcastIdx = M;
9464         else if (M != V1BroadcastIdx)
9465           return false;
9466       }
9467     return true;
9468   };
9469   if (DoBothBroadcast())
9470     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9471                                                       DAG);
9472
9473   // If the inputs all stem from a single 128-bit lane of each input, then we
9474   // split them rather than blending because the split will decompose to
9475   // unusually few instructions.
9476   int LaneCount = VT.getSizeInBits() / 128;
9477   int LaneSize = Size / LaneCount;
9478   SmallBitVector LaneInputs[2];
9479   LaneInputs[0].resize(LaneCount, false);
9480   LaneInputs[1].resize(LaneCount, false);
9481   for (int i = 0; i < Size; ++i)
9482     if (Mask[i] >= 0)
9483       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9484   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9485     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9486
9487   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9488   // that the decomposed single-input shuffles don't end up here.
9489   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9490 }
9491
9492 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9493 /// a permutation and blend of those lanes.
9494 ///
9495 /// This essentially blends the out-of-lane inputs to each lane into the lane
9496 /// from a permuted copy of the vector. This lowering strategy results in four
9497 /// instructions in the worst case for a single-input cross lane shuffle which
9498 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9499 /// of. Special cases for each particular shuffle pattern should be handled
9500 /// prior to trying this lowering.
9501 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9502                                                        SDValue V1, SDValue V2,
9503                                                        ArrayRef<int> Mask,
9504                                                        SelectionDAG &DAG) {
9505   // FIXME: This should probably be generalized for 512-bit vectors as well.
9506   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9507   int LaneSize = Mask.size() / 2;
9508
9509   // If there are only inputs from one 128-bit lane, splitting will in fact be
9510   // less expensive. The flags track whether the given lane contains an element
9511   // that crosses to another lane.
9512   bool LaneCrossing[2] = {false, false};
9513   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9514     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9515       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9516   if (!LaneCrossing[0] || !LaneCrossing[1])
9517     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9518
9519   if (isSingleInputShuffleMask(Mask)) {
9520     SmallVector<int, 32> FlippedBlendMask;
9521     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9522       FlippedBlendMask.push_back(
9523           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9524                                   ? Mask[i]
9525                                   : Mask[i] % LaneSize +
9526                                         (i / LaneSize) * LaneSize + Size));
9527
9528     // Flip the vector, and blend the results which should now be in-lane. The
9529     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9530     // 5 for the high source. The value 3 selects the high half of source 2 and
9531     // the value 2 selects the low half of source 2. We only use source 2 to
9532     // allow folding it into a memory operand.
9533     unsigned PERMMask = 3 | 2 << 4;
9534     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9535                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9536     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9537   }
9538
9539   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9540   // will be handled by the above logic and a blend of the results, much like
9541   // other patterns in AVX.
9542   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9543 }
9544
9545 /// \brief Handle lowering 2-lane 128-bit shuffles.
9546 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9547                                         SDValue V2, ArrayRef<int> Mask,
9548                                         const X86Subtarget *Subtarget,
9549                                         SelectionDAG &DAG) {
9550   // TODO: If minimizing size and one of the inputs is a zero vector and the
9551   // the zero vector has only one use, we could use a VPERM2X128 to save the
9552   // instruction bytes needed to explicitly generate the zero vector.
9553
9554   // Blends are faster and handle all the non-lane-crossing cases.
9555   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9556                                                 Subtarget, DAG))
9557     return Blend;
9558
9559   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9560   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9561
9562   // If either input operand is a zero vector, use VPERM2X128 because its mask
9563   // allows us to replace the zero input with an implicit zero.
9564   if (!IsV1Zero && !IsV2Zero) {
9565     // Check for patterns which can be matched with a single insert of a 128-bit
9566     // subvector.
9567     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9568     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9569       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9570                                    VT.getVectorNumElements() / 2);
9571       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9572                                 DAG.getIntPtrConstant(0, DL));
9573       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9574                                 OnlyUsesV1 ? V1 : V2,
9575                                 DAG.getIntPtrConstant(0, DL));
9576       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9577     }
9578   }
9579
9580   // Otherwise form a 128-bit permutation. After accounting for undefs,
9581   // convert the 64-bit shuffle mask selection values into 128-bit
9582   // selection bits by dividing the indexes by 2 and shifting into positions
9583   // defined by a vperm2*128 instruction's immediate control byte.
9584
9585   // The immediate permute control byte looks like this:
9586   //    [1:0] - select 128 bits from sources for low half of destination
9587   //    [2]   - ignore
9588   //    [3]   - zero low half of destination
9589   //    [5:4] - select 128 bits from sources for high half of destination
9590   //    [6]   - ignore
9591   //    [7]   - zero high half of destination
9592
9593   int MaskLO = Mask[0];
9594   if (MaskLO == SM_SentinelUndef)
9595     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9596
9597   int MaskHI = Mask[2];
9598   if (MaskHI == SM_SentinelUndef)
9599     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9600
9601   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9602
9603   // If either input is a zero vector, replace it with an undef input.
9604   // Shuffle mask values <  4 are selecting elements of V1.
9605   // Shuffle mask values >= 4 are selecting elements of V2.
9606   // Adjust each half of the permute mask by clearing the half that was
9607   // selecting the zero vector and setting the zero mask bit.
9608   if (IsV1Zero) {
9609     V1 = DAG.getUNDEF(VT);
9610     if (MaskLO < 4)
9611       PermMask = (PermMask & 0xf0) | 0x08;
9612     if (MaskHI < 4)
9613       PermMask = (PermMask & 0x0f) | 0x80;
9614   }
9615   if (IsV2Zero) {
9616     V2 = DAG.getUNDEF(VT);
9617     if (MaskLO >= 4)
9618       PermMask = (PermMask & 0xf0) | 0x08;
9619     if (MaskHI >= 4)
9620       PermMask = (PermMask & 0x0f) | 0x80;
9621   }
9622
9623   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9624                      DAG.getConstant(PermMask, DL, MVT::i8));
9625 }
9626
9627 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9628 /// shuffling each lane.
9629 ///
9630 /// This will only succeed when the result of fixing the 128-bit lanes results
9631 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9632 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9633 /// the lane crosses early and then use simpler shuffles within each lane.
9634 ///
9635 /// FIXME: It might be worthwhile at some point to support this without
9636 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9637 /// in x86 only floating point has interesting non-repeating shuffles, and even
9638 /// those are still *marginally* more expensive.
9639 static SDValue lowerVectorShuffleByMerging128BitLanes(
9640     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9641     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9642   assert(!isSingleInputShuffleMask(Mask) &&
9643          "This is only useful with multiple inputs.");
9644
9645   int Size = Mask.size();
9646   int LaneSize = 128 / VT.getScalarSizeInBits();
9647   int NumLanes = Size / LaneSize;
9648   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9649
9650   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9651   // check whether the in-128-bit lane shuffles share a repeating pattern.
9652   SmallVector<int, 4> Lanes;
9653   Lanes.resize(NumLanes, -1);
9654   SmallVector<int, 4> InLaneMask;
9655   InLaneMask.resize(LaneSize, -1);
9656   for (int i = 0; i < Size; ++i) {
9657     if (Mask[i] < 0)
9658       continue;
9659
9660     int j = i / LaneSize;
9661
9662     if (Lanes[j] < 0) {
9663       // First entry we've seen for this lane.
9664       Lanes[j] = Mask[i] / LaneSize;
9665     } else if (Lanes[j] != Mask[i] / LaneSize) {
9666       // This doesn't match the lane selected previously!
9667       return SDValue();
9668     }
9669
9670     // Check that within each lane we have a consistent shuffle mask.
9671     int k = i % LaneSize;
9672     if (InLaneMask[k] < 0) {
9673       InLaneMask[k] = Mask[i] % LaneSize;
9674     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9675       // This doesn't fit a repeating in-lane mask.
9676       return SDValue();
9677     }
9678   }
9679
9680   // First shuffle the lanes into place.
9681   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9682                                 VT.getSizeInBits() / 64);
9683   SmallVector<int, 8> LaneMask;
9684   LaneMask.resize(NumLanes * 2, -1);
9685   for (int i = 0; i < NumLanes; ++i)
9686     if (Lanes[i] >= 0) {
9687       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9688       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9689     }
9690
9691   V1 = DAG.getBitcast(LaneVT, V1);
9692   V2 = DAG.getBitcast(LaneVT, V2);
9693   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9694
9695   // Cast it back to the type we actually want.
9696   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9697
9698   // Now do a simple shuffle that isn't lane crossing.
9699   SmallVector<int, 8> NewMask;
9700   NewMask.resize(Size, -1);
9701   for (int i = 0; i < Size; ++i)
9702     if (Mask[i] >= 0)
9703       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9704   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9705          "Must not introduce lane crosses at this point!");
9706
9707   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9708 }
9709
9710 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9711 /// given mask.
9712 ///
9713 /// This returns true if the elements from a particular input are already in the
9714 /// slot required by the given mask and require no permutation.
9715 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9716   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9717   int Size = Mask.size();
9718   for (int i = 0; i < Size; ++i)
9719     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9720       return false;
9721
9722   return true;
9723 }
9724
9725 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9726                                             ArrayRef<int> Mask, SDValue V1,
9727                                             SDValue V2, SelectionDAG &DAG) {
9728
9729   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9730   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9731   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9732   int NumElts = VT.getVectorNumElements();
9733   bool ShufpdMask = true;
9734   bool CommutableMask = true;
9735   unsigned Immediate = 0;
9736   for (int i = 0; i < NumElts; ++i) {
9737     if (Mask[i] < 0)
9738       continue;
9739     int Val = (i & 6) + NumElts * (i & 1);
9740     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9741     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9742       ShufpdMask = false;
9743     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9744       CommutableMask = false;
9745     Immediate |= (Mask[i] % 2) << i;
9746   }
9747   if (ShufpdMask)
9748     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9749                        DAG.getConstant(Immediate, DL, MVT::i8));
9750   if (CommutableMask)
9751     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9752                        DAG.getConstant(Immediate, DL, MVT::i8));
9753   return SDValue();
9754 }
9755
9756 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9757 ///
9758 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9759 /// isn't available.
9760 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9761                                        const X86Subtarget *Subtarget,
9762                                        SelectionDAG &DAG) {
9763   SDLoc DL(Op);
9764   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9765   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9766   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9767   ArrayRef<int> Mask = SVOp->getMask();
9768   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9769
9770   SmallVector<int, 4> WidenedMask;
9771   if (canWidenShuffleElements(Mask, WidenedMask))
9772     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9773                                     DAG);
9774
9775   if (isSingleInputShuffleMask(Mask)) {
9776     // Check for being able to broadcast a single element.
9777     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9778                                                           Mask, Subtarget, DAG))
9779       return Broadcast;
9780
9781     // Use low duplicate instructions for masks that match their pattern.
9782     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9783       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9784
9785     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9786       // Non-half-crossing single input shuffles can be lowerid with an
9787       // interleaved permutation.
9788       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9789                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9790       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9791                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9792     }
9793
9794     // With AVX2 we have direct support for this permutation.
9795     if (Subtarget->hasAVX2())
9796       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9797                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9798
9799     // Otherwise, fall back.
9800     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9801                                                    DAG);
9802   }
9803
9804   // X86 has dedicated unpack instructions that can handle specific blend
9805   // operations: UNPCKH and UNPCKL.
9806   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9807     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9808   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9809     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9810   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9811     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9812   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9813     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9814
9815   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9816                                                 Subtarget, DAG))
9817     return Blend;
9818
9819   // Check if the blend happens to exactly fit that of SHUFPD.
9820   if (SDValue Op =
9821       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9822     return Op;
9823
9824   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9825   // shuffle. However, if we have AVX2 and either inputs are already in place,
9826   // we will be able to shuffle even across lanes the other input in a single
9827   // instruction so skip this pattern.
9828   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9829                                  isShuffleMaskInputInPlace(1, Mask))))
9830     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9831             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9832       return Result;
9833
9834   // If we have AVX2 then we always want to lower with a blend because an v4 we
9835   // can fully permute the elements.
9836   if (Subtarget->hasAVX2())
9837     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9838                                                       Mask, DAG);
9839
9840   // Otherwise fall back on generic lowering.
9841   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9842 }
9843
9844 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9845 ///
9846 /// This routine is only called when we have AVX2 and thus a reasonable
9847 /// instruction set for v4i64 shuffling..
9848 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9849                                        const X86Subtarget *Subtarget,
9850                                        SelectionDAG &DAG) {
9851   SDLoc DL(Op);
9852   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9853   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9854   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855   ArrayRef<int> Mask = SVOp->getMask();
9856   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9857   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9858
9859   SmallVector<int, 4> WidenedMask;
9860   if (canWidenShuffleElements(Mask, WidenedMask))
9861     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9862                                     DAG);
9863
9864   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9865                                                 Subtarget, DAG))
9866     return Blend;
9867
9868   // Check for being able to broadcast a single element.
9869   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9870                                                         Mask, Subtarget, DAG))
9871     return Broadcast;
9872
9873   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9874   // use lower latency instructions that will operate on both 128-bit lanes.
9875   SmallVector<int, 2> RepeatedMask;
9876   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9877     if (isSingleInputShuffleMask(Mask)) {
9878       int PSHUFDMask[] = {-1, -1, -1, -1};
9879       for (int i = 0; i < 2; ++i)
9880         if (RepeatedMask[i] >= 0) {
9881           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9882           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9883         }
9884       return DAG.getBitcast(
9885           MVT::v4i64,
9886           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9887                       DAG.getBitcast(MVT::v8i32, V1),
9888                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9889     }
9890   }
9891
9892   // AVX2 provides a direct instruction for permuting a single input across
9893   // lanes.
9894   if (isSingleInputShuffleMask(Mask))
9895     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9896                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9897
9898   // Try to use shift instructions.
9899   if (SDValue Shift =
9900           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9901     return Shift;
9902
9903   // Use dedicated unpack instructions for masks that match their pattern.
9904   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9905     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9906   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9907     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9908   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9909     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9910   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9911     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9912
9913   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9914   // shuffle. However, if we have AVX2 and either inputs are already in place,
9915   // we will be able to shuffle even across lanes the other input in a single
9916   // instruction so skip this pattern.
9917   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9918                                  isShuffleMaskInputInPlace(1, Mask))))
9919     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9920             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9921       return Result;
9922
9923   // Otherwise fall back on generic blend lowering.
9924   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9925                                                     Mask, DAG);
9926 }
9927
9928 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9929 ///
9930 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9931 /// isn't available.
9932 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9933                                        const X86Subtarget *Subtarget,
9934                                        SelectionDAG &DAG) {
9935   SDLoc DL(Op);
9936   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9937   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9938   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9939   ArrayRef<int> Mask = SVOp->getMask();
9940   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9941
9942   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9943                                                 Subtarget, DAG))
9944     return Blend;
9945
9946   // Check for being able to broadcast a single element.
9947   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9948                                                         Mask, Subtarget, DAG))
9949     return Broadcast;
9950
9951   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9952   // options to efficiently lower the shuffle.
9953   SmallVector<int, 4> RepeatedMask;
9954   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9955     assert(RepeatedMask.size() == 4 &&
9956            "Repeated masks must be half the mask width!");
9957
9958     // Use even/odd duplicate instructions for masks that match their pattern.
9959     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9960       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9961     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9962       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9963
9964     if (isSingleInputShuffleMask(Mask))
9965       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9966                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9967
9968     // Use dedicated unpack instructions for masks that match their pattern.
9969     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9970       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9971     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9972       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9973     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9974       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9975     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9976       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9977
9978     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9979     // have already handled any direct blends. We also need to squash the
9980     // repeated mask into a simulated v4f32 mask.
9981     for (int i = 0; i < 4; ++i)
9982       if (RepeatedMask[i] >= 8)
9983         RepeatedMask[i] -= 4;
9984     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9985   }
9986
9987   // If we have a single input shuffle with different shuffle patterns in the
9988   // two 128-bit lanes use the variable mask to VPERMILPS.
9989   if (isSingleInputShuffleMask(Mask)) {
9990     SDValue VPermMask[8];
9991     for (int i = 0; i < 8; ++i)
9992       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9993                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9994     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9995       return DAG.getNode(
9996           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9997           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9998
9999     if (Subtarget->hasAVX2())
10000       return DAG.getNode(
10001           X86ISD::VPERMV, DL, MVT::v8f32,
10002           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10003                                                  MVT::v8i32, VPermMask)),
10004           V1);
10005
10006     // Otherwise, fall back.
10007     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10008                                                    DAG);
10009   }
10010
10011   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10012   // shuffle.
10013   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10014           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10015     return Result;
10016
10017   // If we have AVX2 then we always want to lower with a blend because at v8 we
10018   // can fully permute the elements.
10019   if (Subtarget->hasAVX2())
10020     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10021                                                       Mask, DAG);
10022
10023   // Otherwise fall back on generic lowering.
10024   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10025 }
10026
10027 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10028 ///
10029 /// This routine is only called when we have AVX2 and thus a reasonable
10030 /// instruction set for v8i32 shuffling..
10031 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10032                                        const X86Subtarget *Subtarget,
10033                                        SelectionDAG &DAG) {
10034   SDLoc DL(Op);
10035   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10036   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10037   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10038   ArrayRef<int> Mask = SVOp->getMask();
10039   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10040   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10041
10042   // Whenever we can lower this as a zext, that instruction is strictly faster
10043   // than any alternative. It also allows us to fold memory operands into the
10044   // shuffle in many cases.
10045   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10046                                                          Mask, Subtarget, DAG))
10047     return ZExt;
10048
10049   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10050                                                 Subtarget, DAG))
10051     return Blend;
10052
10053   // Check for being able to broadcast a single element.
10054   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10055                                                         Mask, Subtarget, DAG))
10056     return Broadcast;
10057
10058   // If the shuffle mask is repeated in each 128-bit lane we can use more
10059   // efficient instructions that mirror the shuffles across the two 128-bit
10060   // lanes.
10061   SmallVector<int, 4> RepeatedMask;
10062   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10063     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10064     if (isSingleInputShuffleMask(Mask))
10065       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10066                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10067
10068     // Use dedicated unpack instructions for masks that match their pattern.
10069     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10070       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10071     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10072       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10073     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10074       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10075     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10076       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10077   }
10078
10079   // Try to use shift instructions.
10080   if (SDValue Shift =
10081           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10082     return Shift;
10083
10084   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10085           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10086     return Rotate;
10087
10088   // If the shuffle patterns aren't repeated but it is a single input, directly
10089   // generate a cross-lane VPERMD instruction.
10090   if (isSingleInputShuffleMask(Mask)) {
10091     SDValue VPermMask[8];
10092     for (int i = 0; i < 8; ++i)
10093       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10094                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10095     return DAG.getNode(
10096         X86ISD::VPERMV, DL, MVT::v8i32,
10097         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10098   }
10099
10100   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10101   // shuffle.
10102   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10103           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10104     return Result;
10105
10106   // Otherwise fall back on generic blend lowering.
10107   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10108                                                     Mask, DAG);
10109 }
10110
10111 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10112 ///
10113 /// This routine is only called when we have AVX2 and thus a reasonable
10114 /// instruction set for v16i16 shuffling..
10115 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10116                                         const X86Subtarget *Subtarget,
10117                                         SelectionDAG &DAG) {
10118   SDLoc DL(Op);
10119   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10120   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10121   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10122   ArrayRef<int> Mask = SVOp->getMask();
10123   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10124   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10125
10126   // Whenever we can lower this as a zext, that instruction is strictly faster
10127   // than any alternative. It also allows us to fold memory operands into the
10128   // shuffle in many cases.
10129   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10130                                                          Mask, Subtarget, DAG))
10131     return ZExt;
10132
10133   // Check for being able to broadcast a single element.
10134   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10135                                                         Mask, Subtarget, DAG))
10136     return Broadcast;
10137
10138   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10139                                                 Subtarget, DAG))
10140     return Blend;
10141
10142   // Use dedicated unpack instructions for masks that match their pattern.
10143   if (isShuffleEquivalent(V1, V2, Mask,
10144                           {// First 128-bit lane:
10145                            0, 16, 1, 17, 2, 18, 3, 19,
10146                            // Second 128-bit lane:
10147                            8, 24, 9, 25, 10, 26, 11, 27}))
10148     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10149   if (isShuffleEquivalent(V1, V2, Mask,
10150                           {// First 128-bit lane:
10151                            4, 20, 5, 21, 6, 22, 7, 23,
10152                            // Second 128-bit lane:
10153                            12, 28, 13, 29, 14, 30, 15, 31}))
10154     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10155
10156   // Try to use shift instructions.
10157   if (SDValue Shift =
10158           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10159     return Shift;
10160
10161   // Try to use byte rotation instructions.
10162   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10163           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10164     return Rotate;
10165
10166   if (isSingleInputShuffleMask(Mask)) {
10167     // There are no generalized cross-lane shuffle operations available on i16
10168     // element types.
10169     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10170       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10171                                                      Mask, DAG);
10172
10173     SmallVector<int, 8> RepeatedMask;
10174     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10175       // As this is a single-input shuffle, the repeated mask should be
10176       // a strictly valid v8i16 mask that we can pass through to the v8i16
10177       // lowering to handle even the v16 case.
10178       return lowerV8I16GeneralSingleInputVectorShuffle(
10179           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10180     }
10181
10182     SDValue PSHUFBMask[32];
10183     for (int i = 0; i < 16; ++i) {
10184       if (Mask[i] == -1) {
10185         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10186         continue;
10187       }
10188
10189       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10190       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10191       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10192       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10193     }
10194     return DAG.getBitcast(MVT::v16i16,
10195                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10196                                       DAG.getBitcast(MVT::v32i8, V1),
10197                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10198                                                   MVT::v32i8, PSHUFBMask)));
10199   }
10200
10201   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10202   // shuffle.
10203   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10204           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10205     return Result;
10206
10207   // Otherwise fall back on generic lowering.
10208   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10209 }
10210
10211 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10212 ///
10213 /// This routine is only called when we have AVX2 and thus a reasonable
10214 /// instruction set for v32i8 shuffling..
10215 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10216                                        const X86Subtarget *Subtarget,
10217                                        SelectionDAG &DAG) {
10218   SDLoc DL(Op);
10219   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10220   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10221   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10222   ArrayRef<int> Mask = SVOp->getMask();
10223   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10224   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10225
10226   // Whenever we can lower this as a zext, that instruction is strictly faster
10227   // than any alternative. It also allows us to fold memory operands into the
10228   // shuffle in many cases.
10229   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10230                                                          Mask, Subtarget, DAG))
10231     return ZExt;
10232
10233   // Check for being able to broadcast a single element.
10234   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10235                                                         Mask, Subtarget, DAG))
10236     return Broadcast;
10237
10238   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10239                                                 Subtarget, DAG))
10240     return Blend;
10241
10242   // Use dedicated unpack instructions for masks that match their pattern.
10243   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10244   // 256-bit lanes.
10245   if (isShuffleEquivalent(
10246           V1, V2, Mask,
10247           {// First 128-bit lane:
10248            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10249            // Second 128-bit lane:
10250            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10251     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10252   if (isShuffleEquivalent(
10253           V1, V2, Mask,
10254           {// First 128-bit lane:
10255            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10256            // Second 128-bit lane:
10257            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10258     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10259
10260   // Try to use shift instructions.
10261   if (SDValue Shift =
10262           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10263     return Shift;
10264
10265   // Try to use byte rotation instructions.
10266   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10267           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10268     return Rotate;
10269
10270   if (isSingleInputShuffleMask(Mask)) {
10271     // There are no generalized cross-lane shuffle operations available on i8
10272     // element types.
10273     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10274       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10275                                                      Mask, DAG);
10276
10277     SDValue PSHUFBMask[32];
10278     for (int i = 0; i < 32; ++i)
10279       PSHUFBMask[i] =
10280           Mask[i] < 0
10281               ? DAG.getUNDEF(MVT::i8)
10282               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10283                                 MVT::i8);
10284
10285     return DAG.getNode(
10286         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10287         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10288   }
10289
10290   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10291   // shuffle.
10292   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10293           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10294     return Result;
10295
10296   // Otherwise fall back on generic lowering.
10297   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10298 }
10299
10300 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10301 ///
10302 /// This routine either breaks down the specific type of a 256-bit x86 vector
10303 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10304 /// together based on the available instructions.
10305 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10306                                         MVT VT, const X86Subtarget *Subtarget,
10307                                         SelectionDAG &DAG) {
10308   SDLoc DL(Op);
10309   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10310   ArrayRef<int> Mask = SVOp->getMask();
10311
10312   // If we have a single input to the zero element, insert that into V1 if we
10313   // can do so cheaply.
10314   int NumElts = VT.getVectorNumElements();
10315   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10316     return M >= NumElts;
10317   });
10318
10319   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10320     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10321                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10322       return Insertion;
10323
10324   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10325   // check for those subtargets here and avoid much of the subtarget querying in
10326   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10327   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10328   // floating point types there eventually, just immediately cast everything to
10329   // a float and operate entirely in that domain.
10330   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10331     int ElementBits = VT.getScalarSizeInBits();
10332     if (ElementBits < 32)
10333       // No floating point type available, decompose into 128-bit vectors.
10334       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10335
10336     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10337                                 VT.getVectorNumElements());
10338     V1 = DAG.getBitcast(FpVT, V1);
10339     V2 = DAG.getBitcast(FpVT, V2);
10340     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10341   }
10342
10343   switch (VT.SimpleTy) {
10344   case MVT::v4f64:
10345     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10346   case MVT::v4i64:
10347     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10348   case MVT::v8f32:
10349     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10350   case MVT::v8i32:
10351     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10352   case MVT::v16i16:
10353     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10354   case MVT::v32i8:
10355     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10356
10357   default:
10358     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10359   }
10360 }
10361
10362 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10363 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10364                                        const X86Subtarget *Subtarget,
10365                                        SelectionDAG &DAG) {
10366   SDLoc DL(Op);
10367   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10368   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10369   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10370   ArrayRef<int> Mask = SVOp->getMask();
10371   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10372
10373   // X86 has dedicated unpack instructions that can handle specific blend
10374   // operations: UNPCKH and UNPCKL.
10375   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10376     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10377   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10378     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10379
10380   // FIXME: Implement direct support for this type!
10381   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10382 }
10383
10384 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10385 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10386                                        const X86Subtarget *Subtarget,
10387                                        SelectionDAG &DAG) {
10388   SDLoc DL(Op);
10389   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10390   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10391   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10392   ArrayRef<int> Mask = SVOp->getMask();
10393   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10394
10395   // Use dedicated unpack instructions for masks that match their pattern.
10396   if (isShuffleEquivalent(V1, V2, Mask,
10397                           {// First 128-bit lane.
10398                            0, 16, 1, 17, 4, 20, 5, 21,
10399                            // Second 128-bit lane.
10400                            8, 24, 9, 25, 12, 28, 13, 29}))
10401     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10402   if (isShuffleEquivalent(V1, V2, Mask,
10403                           {// First 128-bit lane.
10404                            2, 18, 3, 19, 6, 22, 7, 23,
10405                            // Second 128-bit lane.
10406                            10, 26, 11, 27, 14, 30, 15, 31}))
10407     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10408
10409   // FIXME: Implement direct support for this type!
10410   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10411 }
10412
10413 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10414 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10415                                        const X86Subtarget *Subtarget,
10416                                        SelectionDAG &DAG) {
10417   SDLoc DL(Op);
10418   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10419   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10420   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10421   ArrayRef<int> Mask = SVOp->getMask();
10422   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10423
10424   // X86 has dedicated unpack instructions that can handle specific blend
10425   // operations: UNPCKH and UNPCKL.
10426   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10427     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10428   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10429     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10430
10431   // FIXME: Implement direct support for this type!
10432   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10433 }
10434
10435 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10436 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10437                                        const X86Subtarget *Subtarget,
10438                                        SelectionDAG &DAG) {
10439   SDLoc DL(Op);
10440   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10441   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10442   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10443   ArrayRef<int> Mask = SVOp->getMask();
10444   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10445
10446   // Use dedicated unpack instructions for masks that match their pattern.
10447   if (isShuffleEquivalent(V1, V2, Mask,
10448                           {// First 128-bit lane.
10449                            0, 16, 1, 17, 4, 20, 5, 21,
10450                            // Second 128-bit lane.
10451                            8, 24, 9, 25, 12, 28, 13, 29}))
10452     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10453   if (isShuffleEquivalent(V1, V2, Mask,
10454                           {// First 128-bit lane.
10455                            2, 18, 3, 19, 6, 22, 7, 23,
10456                            // Second 128-bit lane.
10457                            10, 26, 11, 27, 14, 30, 15, 31}))
10458     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10459
10460   // FIXME: Implement direct support for this type!
10461   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10462 }
10463
10464 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10465 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10466                                         const X86Subtarget *Subtarget,
10467                                         SelectionDAG &DAG) {
10468   SDLoc DL(Op);
10469   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10470   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10471   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10472   ArrayRef<int> Mask = SVOp->getMask();
10473   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10474   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10475
10476   // FIXME: Implement direct support for this type!
10477   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10478 }
10479
10480 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10481 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10482                                        const X86Subtarget *Subtarget,
10483                                        SelectionDAG &DAG) {
10484   SDLoc DL(Op);
10485   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10486   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10488   ArrayRef<int> Mask = SVOp->getMask();
10489   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10490   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10491
10492   // FIXME: Implement direct support for this type!
10493   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10494 }
10495
10496 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10497 ///
10498 /// This routine either breaks down the specific type of a 512-bit x86 vector
10499 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10500 /// together based on the available instructions.
10501 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10502                                         MVT VT, const X86Subtarget *Subtarget,
10503                                         SelectionDAG &DAG) {
10504   SDLoc DL(Op);
10505   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10506   ArrayRef<int> Mask = SVOp->getMask();
10507   assert(Subtarget->hasAVX512() &&
10508          "Cannot lower 512-bit vectors w/ basic ISA!");
10509
10510   // Check for being able to broadcast a single element.
10511   if (SDValue Broadcast =
10512           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10513     return Broadcast;
10514
10515   // Dispatch to each element type for lowering. If we don't have supprot for
10516   // specific element type shuffles at 512 bits, immediately split them and
10517   // lower them. Each lowering routine of a given type is allowed to assume that
10518   // the requisite ISA extensions for that element type are available.
10519   switch (VT.SimpleTy) {
10520   case MVT::v8f64:
10521     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10522   case MVT::v16f32:
10523     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10524   case MVT::v8i64:
10525     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10526   case MVT::v16i32:
10527     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10528   case MVT::v32i16:
10529     if (Subtarget->hasBWI())
10530       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10531     break;
10532   case MVT::v64i8:
10533     if (Subtarget->hasBWI())
10534       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10535     break;
10536
10537   default:
10538     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10539   }
10540
10541   // Otherwise fall back on splitting.
10542   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10543 }
10544
10545 /// \brief Top-level lowering for x86 vector shuffles.
10546 ///
10547 /// This handles decomposition, canonicalization, and lowering of all x86
10548 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10549 /// above in helper routines. The canonicalization attempts to widen shuffles
10550 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10551 /// s.t. only one of the two inputs needs to be tested, etc.
10552 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10553                                   SelectionDAG &DAG) {
10554   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10555   ArrayRef<int> Mask = SVOp->getMask();
10556   SDValue V1 = Op.getOperand(0);
10557   SDValue V2 = Op.getOperand(1);
10558   MVT VT = Op.getSimpleValueType();
10559   int NumElements = VT.getVectorNumElements();
10560   SDLoc dl(Op);
10561
10562   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10563
10564   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10565   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10566   if (V1IsUndef && V2IsUndef)
10567     return DAG.getUNDEF(VT);
10568
10569   // When we create a shuffle node we put the UNDEF node to second operand,
10570   // but in some cases the first operand may be transformed to UNDEF.
10571   // In this case we should just commute the node.
10572   if (V1IsUndef)
10573     return DAG.getCommutedVectorShuffle(*SVOp);
10574
10575   // Check for non-undef masks pointing at an undef vector and make the masks
10576   // undef as well. This makes it easier to match the shuffle based solely on
10577   // the mask.
10578   if (V2IsUndef)
10579     for (int M : Mask)
10580       if (M >= NumElements) {
10581         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10582         for (int &M : NewMask)
10583           if (M >= NumElements)
10584             M = -1;
10585         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10586       }
10587
10588   // We actually see shuffles that are entirely re-arrangements of a set of
10589   // zero inputs. This mostly happens while decomposing complex shuffles into
10590   // simple ones. Directly lower these as a buildvector of zeros.
10591   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10592   if (Zeroable.all())
10593     return getZeroVector(VT, Subtarget, DAG, dl);
10594
10595   // Try to collapse shuffles into using a vector type with fewer elements but
10596   // wider element types. We cap this to not form integers or floating point
10597   // elements wider than 64 bits, but it might be interesting to form i128
10598   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10599   SmallVector<int, 16> WidenedMask;
10600   if (VT.getScalarSizeInBits() < 64 &&
10601       canWidenShuffleElements(Mask, WidenedMask)) {
10602     MVT NewEltVT = VT.isFloatingPoint()
10603                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10604                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10605     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10606     // Make sure that the new vector type is legal. For example, v2f64 isn't
10607     // legal on SSE1.
10608     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10609       V1 = DAG.getBitcast(NewVT, V1);
10610       V2 = DAG.getBitcast(NewVT, V2);
10611       return DAG.getBitcast(
10612           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10613     }
10614   }
10615
10616   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10617   for (int M : SVOp->getMask())
10618     if (M < 0)
10619       ++NumUndefElements;
10620     else if (M < NumElements)
10621       ++NumV1Elements;
10622     else
10623       ++NumV2Elements;
10624
10625   // Commute the shuffle as needed such that more elements come from V1 than
10626   // V2. This allows us to match the shuffle pattern strictly on how many
10627   // elements come from V1 without handling the symmetric cases.
10628   if (NumV2Elements > NumV1Elements)
10629     return DAG.getCommutedVectorShuffle(*SVOp);
10630
10631   // When the number of V1 and V2 elements are the same, try to minimize the
10632   // number of uses of V2 in the low half of the vector. When that is tied,
10633   // ensure that the sum of indices for V1 is equal to or lower than the sum
10634   // indices for V2. When those are equal, try to ensure that the number of odd
10635   // indices for V1 is lower than the number of odd indices for V2.
10636   if (NumV1Elements == NumV2Elements) {
10637     int LowV1Elements = 0, LowV2Elements = 0;
10638     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10639       if (M >= NumElements)
10640         ++LowV2Elements;
10641       else if (M >= 0)
10642         ++LowV1Elements;
10643     if (LowV2Elements > LowV1Elements) {
10644       return DAG.getCommutedVectorShuffle(*SVOp);
10645     } else if (LowV2Elements == LowV1Elements) {
10646       int SumV1Indices = 0, SumV2Indices = 0;
10647       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10648         if (SVOp->getMask()[i] >= NumElements)
10649           SumV2Indices += i;
10650         else if (SVOp->getMask()[i] >= 0)
10651           SumV1Indices += i;
10652       if (SumV2Indices < SumV1Indices) {
10653         return DAG.getCommutedVectorShuffle(*SVOp);
10654       } else if (SumV2Indices == SumV1Indices) {
10655         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10656         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10657           if (SVOp->getMask()[i] >= NumElements)
10658             NumV2OddIndices += i % 2;
10659           else if (SVOp->getMask()[i] >= 0)
10660             NumV1OddIndices += i % 2;
10661         if (NumV2OddIndices < NumV1OddIndices)
10662           return DAG.getCommutedVectorShuffle(*SVOp);
10663       }
10664     }
10665   }
10666
10667   // For each vector width, delegate to a specialized lowering routine.
10668   if (VT.getSizeInBits() == 128)
10669     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10670
10671   if (VT.getSizeInBits() == 256)
10672     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10673
10674   // Force AVX-512 vectors to be scalarized for now.
10675   // FIXME: Implement AVX-512 support!
10676   if (VT.getSizeInBits() == 512)
10677     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10678
10679   llvm_unreachable("Unimplemented!");
10680 }
10681
10682 // This function assumes its argument is a BUILD_VECTOR of constants or
10683 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10684 // true.
10685 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10686                                     unsigned &MaskValue) {
10687   MaskValue = 0;
10688   unsigned NumElems = BuildVector->getNumOperands();
10689   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10690   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10691   unsigned NumElemsInLane = NumElems / NumLanes;
10692
10693   // Blend for v16i16 should be symetric for the both lanes.
10694   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10695     SDValue EltCond = BuildVector->getOperand(i);
10696     SDValue SndLaneEltCond =
10697         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10698
10699     int Lane1Cond = -1, Lane2Cond = -1;
10700     if (isa<ConstantSDNode>(EltCond))
10701       Lane1Cond = !isZero(EltCond);
10702     if (isa<ConstantSDNode>(SndLaneEltCond))
10703       Lane2Cond = !isZero(SndLaneEltCond);
10704
10705     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10706       // Lane1Cond != 0, means we want the first argument.
10707       // Lane1Cond == 0, means we want the second argument.
10708       // The encoding of this argument is 0 for the first argument, 1
10709       // for the second. Therefore, invert the condition.
10710       MaskValue |= !Lane1Cond << i;
10711     else if (Lane1Cond < 0)
10712       MaskValue |= !Lane2Cond << i;
10713     else
10714       return false;
10715   }
10716   return true;
10717 }
10718
10719 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10720 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10721                                            const X86Subtarget *Subtarget,
10722                                            SelectionDAG &DAG) {
10723   SDValue Cond = Op.getOperand(0);
10724   SDValue LHS = Op.getOperand(1);
10725   SDValue RHS = Op.getOperand(2);
10726   SDLoc dl(Op);
10727   MVT VT = Op.getSimpleValueType();
10728
10729   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10730     return SDValue();
10731   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10732
10733   // Only non-legal VSELECTs reach this lowering, convert those into generic
10734   // shuffles and re-use the shuffle lowering path for blends.
10735   SmallVector<int, 32> Mask;
10736   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10737     SDValue CondElt = CondBV->getOperand(i);
10738     Mask.push_back(
10739         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10740   }
10741   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10742 }
10743
10744 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10745   // A vselect where all conditions and data are constants can be optimized into
10746   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10747   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10748       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10749       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10750     return SDValue();
10751
10752   // Try to lower this to a blend-style vector shuffle. This can handle all
10753   // constant condition cases.
10754   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10755     return BlendOp;
10756
10757   // Variable blends are only legal from SSE4.1 onward.
10758   if (!Subtarget->hasSSE41())
10759     return SDValue();
10760
10761   // Only some types will be legal on some subtargets. If we can emit a legal
10762   // VSELECT-matching blend, return Op, and but if we need to expand, return
10763   // a null value.
10764   switch (Op.getSimpleValueType().SimpleTy) {
10765   default:
10766     // Most of the vector types have blends past SSE4.1.
10767     return Op;
10768
10769   case MVT::v32i8:
10770     // The byte blends for AVX vectors were introduced only in AVX2.
10771     if (Subtarget->hasAVX2())
10772       return Op;
10773
10774     return SDValue();
10775
10776   case MVT::v8i16:
10777   case MVT::v16i16:
10778     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10779     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10780       return Op;
10781
10782     // FIXME: We should custom lower this by fixing the condition and using i8
10783     // blends.
10784     return SDValue();
10785   }
10786 }
10787
10788 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10789   MVT VT = Op.getSimpleValueType();
10790   SDLoc dl(Op);
10791
10792   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10793     return SDValue();
10794
10795   if (VT.getSizeInBits() == 8) {
10796     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10797                                   Op.getOperand(0), Op.getOperand(1));
10798     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10799                                   DAG.getValueType(VT));
10800     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10801   }
10802
10803   if (VT.getSizeInBits() == 16) {
10804     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10805     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10806     if (Idx == 0)
10807       return DAG.getNode(
10808           ISD::TRUNCATE, dl, MVT::i16,
10809           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10810                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10811                       Op.getOperand(1)));
10812     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10813                                   Op.getOperand(0), Op.getOperand(1));
10814     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10815                                   DAG.getValueType(VT));
10816     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10817   }
10818
10819   if (VT == MVT::f32) {
10820     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10821     // the result back to FR32 register. It's only worth matching if the
10822     // result has a single use which is a store or a bitcast to i32.  And in
10823     // the case of a store, it's not worth it if the index is a constant 0,
10824     // because a MOVSSmr can be used instead, which is smaller and faster.
10825     if (!Op.hasOneUse())
10826       return SDValue();
10827     SDNode *User = *Op.getNode()->use_begin();
10828     if ((User->getOpcode() != ISD::STORE ||
10829          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10830           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10831         (User->getOpcode() != ISD::BITCAST ||
10832          User->getValueType(0) != MVT::i32))
10833       return SDValue();
10834     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10835                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10836                                   Op.getOperand(1));
10837     return DAG.getBitcast(MVT::f32, Extract);
10838   }
10839
10840   if (VT == MVT::i32 || VT == MVT::i64) {
10841     // ExtractPS/pextrq works with constant index.
10842     if (isa<ConstantSDNode>(Op.getOperand(1)))
10843       return Op;
10844   }
10845   return SDValue();
10846 }
10847
10848 /// Extract one bit from mask vector, like v16i1 or v8i1.
10849 /// AVX-512 feature.
10850 SDValue
10851 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10852   SDValue Vec = Op.getOperand(0);
10853   SDLoc dl(Vec);
10854   MVT VecVT = Vec.getSimpleValueType();
10855   SDValue Idx = Op.getOperand(1);
10856   MVT EltVT = Op.getSimpleValueType();
10857
10858   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10859   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10860          "Unexpected vector type in ExtractBitFromMaskVector");
10861
10862   // variable index can't be handled in mask registers,
10863   // extend vector to VR512
10864   if (!isa<ConstantSDNode>(Idx)) {
10865     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10866     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10867     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10868                               ExtVT.getVectorElementType(), Ext, Idx);
10869     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10870   }
10871
10872   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10874   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10875     rc = getRegClassFor(MVT::v16i1);
10876   unsigned MaxSift = rc->getSize()*8 - 1;
10877   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10878                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10879   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10880                     DAG.getConstant(MaxSift, dl, MVT::i8));
10881   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10882                        DAG.getIntPtrConstant(0, dl));
10883 }
10884
10885 SDValue
10886 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10887                                            SelectionDAG &DAG) const {
10888   SDLoc dl(Op);
10889   SDValue Vec = Op.getOperand(0);
10890   MVT VecVT = Vec.getSimpleValueType();
10891   SDValue Idx = Op.getOperand(1);
10892
10893   if (Op.getSimpleValueType() == MVT::i1)
10894     return ExtractBitFromMaskVector(Op, DAG);
10895
10896   if (!isa<ConstantSDNode>(Idx)) {
10897     if (VecVT.is512BitVector() ||
10898         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10899          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10900
10901       MVT MaskEltVT =
10902         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10903       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10904                                     MaskEltVT.getSizeInBits());
10905
10906       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10907       auto PtrVT = getPointerTy(DAG.getDataLayout());
10908       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10909                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10910                                  DAG.getConstant(0, dl, PtrVT));
10911       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10912       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10913                          DAG.getConstant(0, dl, PtrVT));
10914     }
10915     return SDValue();
10916   }
10917
10918   // If this is a 256-bit vector result, first extract the 128-bit vector and
10919   // then extract the element from the 128-bit vector.
10920   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10921
10922     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10923     // Get the 128-bit vector.
10924     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10925     MVT EltVT = VecVT.getVectorElementType();
10926
10927     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10928
10929     //if (IdxVal >= NumElems/2)
10930     //  IdxVal -= NumElems/2;
10931     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10932     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10933                        DAG.getConstant(IdxVal, dl, MVT::i32));
10934   }
10935
10936   assert(VecVT.is128BitVector() && "Unexpected vector length");
10937
10938   if (Subtarget->hasSSE41())
10939     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10940       return Res;
10941
10942   MVT VT = Op.getSimpleValueType();
10943   // TODO: handle v16i8.
10944   if (VT.getSizeInBits() == 16) {
10945     SDValue Vec = Op.getOperand(0);
10946     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10947     if (Idx == 0)
10948       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10949                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10950                                      DAG.getBitcast(MVT::v4i32, Vec),
10951                                      Op.getOperand(1)));
10952     // Transform it so it match pextrw which produces a 32-bit result.
10953     MVT EltVT = MVT::i32;
10954     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10955                                   Op.getOperand(0), Op.getOperand(1));
10956     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10957                                   DAG.getValueType(VT));
10958     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10959   }
10960
10961   if (VT.getSizeInBits() == 32) {
10962     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10963     if (Idx == 0)
10964       return Op;
10965
10966     // SHUFPS the element to the lowest double word, then movss.
10967     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10968     MVT VVT = Op.getOperand(0).getSimpleValueType();
10969     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10970                                        DAG.getUNDEF(VVT), Mask);
10971     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10972                        DAG.getIntPtrConstant(0, dl));
10973   }
10974
10975   if (VT.getSizeInBits() == 64) {
10976     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10977     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10978     //        to match extract_elt for f64.
10979     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10980     if (Idx == 0)
10981       return Op;
10982
10983     // UNPCKHPD the element to the lowest double word, then movsd.
10984     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10985     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10986     int Mask[2] = { 1, -1 };
10987     MVT VVT = Op.getOperand(0).getSimpleValueType();
10988     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10989                                        DAG.getUNDEF(VVT), Mask);
10990     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10991                        DAG.getIntPtrConstant(0, dl));
10992   }
10993
10994   return SDValue();
10995 }
10996
10997 /// Insert one bit to mask vector, like v16i1 or v8i1.
10998 /// AVX-512 feature.
10999 SDValue
11000 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11001   SDLoc dl(Op);
11002   SDValue Vec = Op.getOperand(0);
11003   SDValue Elt = Op.getOperand(1);
11004   SDValue Idx = Op.getOperand(2);
11005   MVT VecVT = Vec.getSimpleValueType();
11006
11007   if (!isa<ConstantSDNode>(Idx)) {
11008     // Non constant index. Extend source and destination,
11009     // insert element and then truncate the result.
11010     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11011     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11012     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11013       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11014       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11015     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11016   }
11017
11018   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11019   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11020   if (IdxVal)
11021     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11022                            DAG.getConstant(IdxVal, dl, MVT::i8));
11023   if (Vec.getOpcode() == ISD::UNDEF)
11024     return EltInVec;
11025   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11026 }
11027
11028 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11029                                                   SelectionDAG &DAG) const {
11030   MVT VT = Op.getSimpleValueType();
11031   MVT EltVT = VT.getVectorElementType();
11032
11033   if (EltVT == MVT::i1)
11034     return InsertBitToMaskVector(Op, DAG);
11035
11036   SDLoc dl(Op);
11037   SDValue N0 = Op.getOperand(0);
11038   SDValue N1 = Op.getOperand(1);
11039   SDValue N2 = Op.getOperand(2);
11040   if (!isa<ConstantSDNode>(N2))
11041     return SDValue();
11042   auto *N2C = cast<ConstantSDNode>(N2);
11043   unsigned IdxVal = N2C->getZExtValue();
11044
11045   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11046   // into that, and then insert the subvector back into the result.
11047   if (VT.is256BitVector() || VT.is512BitVector()) {
11048     // With a 256-bit vector, we can insert into the zero element efficiently
11049     // using a blend if we have AVX or AVX2 and the right data type.
11050     if (VT.is256BitVector() && IdxVal == 0) {
11051       // TODO: It is worthwhile to cast integer to floating point and back
11052       // and incur a domain crossing penalty if that's what we'll end up
11053       // doing anyway after extracting to a 128-bit vector.
11054       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11055           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11056         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11057         N2 = DAG.getIntPtrConstant(1, dl);
11058         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11059       }
11060     }
11061
11062     // Get the desired 128-bit vector chunk.
11063     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11064
11065     // Insert the element into the desired chunk.
11066     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11067     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11068
11069     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11070                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11071
11072     // Insert the changed part back into the bigger vector
11073     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11074   }
11075   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11076
11077   if (Subtarget->hasSSE41()) {
11078     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11079       unsigned Opc;
11080       if (VT == MVT::v8i16) {
11081         Opc = X86ISD::PINSRW;
11082       } else {
11083         assert(VT == MVT::v16i8);
11084         Opc = X86ISD::PINSRB;
11085       }
11086
11087       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11088       // argument.
11089       if (N1.getValueType() != MVT::i32)
11090         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11091       if (N2.getValueType() != MVT::i32)
11092         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11093       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11094     }
11095
11096     if (EltVT == MVT::f32) {
11097       // Bits [7:6] of the constant are the source select. This will always be
11098       //   zero here. The DAG Combiner may combine an extract_elt index into
11099       //   these bits. For example (insert (extract, 3), 2) could be matched by
11100       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11101       // Bits [5:4] of the constant are the destination select. This is the
11102       //   value of the incoming immediate.
11103       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11104       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11105
11106       const Function *F = DAG.getMachineFunction().getFunction();
11107       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11108       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11109         // If this is an insertion of 32-bits into the low 32-bits of
11110         // a vector, we prefer to generate a blend with immediate rather
11111         // than an insertps. Blends are simpler operations in hardware and so
11112         // will always have equal or better performance than insertps.
11113         // But if optimizing for size and there's a load folding opportunity,
11114         // generate insertps because blendps does not have a 32-bit memory
11115         // operand form.
11116         N2 = DAG.getIntPtrConstant(1, dl);
11117         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11118         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11119       }
11120       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11121       // Create this as a scalar to vector..
11122       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11123       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11124     }
11125
11126     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11127       // PINSR* works with constant index.
11128       return Op;
11129     }
11130   }
11131
11132   if (EltVT == MVT::i8)
11133     return SDValue();
11134
11135   if (EltVT.getSizeInBits() == 16) {
11136     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11137     // as its second argument.
11138     if (N1.getValueType() != MVT::i32)
11139       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11140     if (N2.getValueType() != MVT::i32)
11141       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11142     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11143   }
11144   return SDValue();
11145 }
11146
11147 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11148   SDLoc dl(Op);
11149   MVT OpVT = Op.getSimpleValueType();
11150
11151   // If this is a 256-bit vector result, first insert into a 128-bit
11152   // vector and then insert into the 256-bit vector.
11153   if (!OpVT.is128BitVector()) {
11154     // Insert into a 128-bit vector.
11155     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11156     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11157                                  OpVT.getVectorNumElements() / SizeFactor);
11158
11159     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11160
11161     // Insert the 128-bit vector.
11162     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11163   }
11164
11165   if (OpVT == MVT::v1i64 &&
11166       Op.getOperand(0).getValueType() == MVT::i64)
11167     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11168
11169   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11170   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11171   return DAG.getBitcast(
11172       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11173 }
11174
11175 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11176 // a simple subregister reference or explicit instructions to grab
11177 // upper bits of a vector.
11178 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11179                                       SelectionDAG &DAG) {
11180   SDLoc dl(Op);
11181   SDValue In =  Op.getOperand(0);
11182   SDValue Idx = Op.getOperand(1);
11183   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11184   MVT ResVT   = Op.getSimpleValueType();
11185   MVT InVT    = In.getSimpleValueType();
11186
11187   if (Subtarget->hasFp256()) {
11188     if (ResVT.is128BitVector() &&
11189         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11190         isa<ConstantSDNode>(Idx)) {
11191       return Extract128BitVector(In, IdxVal, DAG, dl);
11192     }
11193     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11194         isa<ConstantSDNode>(Idx)) {
11195       return Extract256BitVector(In, IdxVal, DAG, dl);
11196     }
11197   }
11198   return SDValue();
11199 }
11200
11201 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11202 // simple superregister reference or explicit instructions to insert
11203 // the upper bits of a vector.
11204 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11205                                      SelectionDAG &DAG) {
11206   if (!Subtarget->hasAVX())
11207     return SDValue();
11208
11209   SDLoc dl(Op);
11210   SDValue Vec = Op.getOperand(0);
11211   SDValue SubVec = Op.getOperand(1);
11212   SDValue Idx = Op.getOperand(2);
11213
11214   if (!isa<ConstantSDNode>(Idx))
11215     return SDValue();
11216
11217   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11218   MVT OpVT = Op.getSimpleValueType();
11219   MVT SubVecVT = SubVec.getSimpleValueType();
11220
11221   // Fold two 16-byte subvector loads into one 32-byte load:
11222   // (insert_subvector (insert_subvector undef, (load addr), 0),
11223   //                   (load addr + 16), Elts/2)
11224   // --> load32 addr
11225   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11226       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11227       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11228       !Subtarget->isUnalignedMem32Slow()) {
11229     SDValue SubVec2 = Vec.getOperand(1);
11230     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11231       if (Idx2->getZExtValue() == 0) {
11232         SDValue Ops[] = { SubVec2, SubVec };
11233         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11234           return Ld;
11235       }
11236     }
11237   }
11238
11239   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11240       SubVecVT.is128BitVector())
11241     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11242
11243   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11244     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11245
11246   if (OpVT.getVectorElementType() == MVT::i1) {
11247     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11248       return Op;
11249     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11250     SDValue Undef = DAG.getUNDEF(OpVT);
11251     unsigned NumElems = OpVT.getVectorNumElements();
11252     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11253
11254     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11255       // Zero upper bits of the Vec
11256       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11257       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11258
11259       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11260                                  SubVec, ZeroIdx);
11261       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11262       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11263     }
11264     if (IdxVal == 0) {
11265       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11266                                  SubVec, ZeroIdx);
11267       // Zero upper bits of the Vec2
11268       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11269       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11270       // Zero lower bits of the Vec
11271       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11272       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11273       // Merge them together
11274       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11275     }
11276   }
11277   return SDValue();
11278 }
11279
11280 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11281 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11282 // one of the above mentioned nodes. It has to be wrapped because otherwise
11283 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11284 // be used to form addressing mode. These wrapped nodes will be selected
11285 // into MOV32ri.
11286 SDValue
11287 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11288   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11289
11290   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11291   // global base reg.
11292   unsigned char OpFlag = 0;
11293   unsigned WrapperKind = X86ISD::Wrapper;
11294   CodeModel::Model M = DAG.getTarget().getCodeModel();
11295
11296   if (Subtarget->isPICStyleRIPRel() &&
11297       (M == CodeModel::Small || M == CodeModel::Kernel))
11298     WrapperKind = X86ISD::WrapperRIP;
11299   else if (Subtarget->isPICStyleGOT())
11300     OpFlag = X86II::MO_GOTOFF;
11301   else if (Subtarget->isPICStyleStubPIC())
11302     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11303
11304   auto PtrVT = getPointerTy(DAG.getDataLayout());
11305   SDValue Result = DAG.getTargetConstantPool(
11306       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11307   SDLoc DL(CP);
11308   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11309   // With PIC, the address is actually $g + Offset.
11310   if (OpFlag) {
11311     Result =
11312         DAG.getNode(ISD::ADD, DL, PtrVT,
11313                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11314   }
11315
11316   return Result;
11317 }
11318
11319 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11320   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11321
11322   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11323   // global base reg.
11324   unsigned char OpFlag = 0;
11325   unsigned WrapperKind = X86ISD::Wrapper;
11326   CodeModel::Model M = DAG.getTarget().getCodeModel();
11327
11328   if (Subtarget->isPICStyleRIPRel() &&
11329       (M == CodeModel::Small || M == CodeModel::Kernel))
11330     WrapperKind = X86ISD::WrapperRIP;
11331   else if (Subtarget->isPICStyleGOT())
11332     OpFlag = X86II::MO_GOTOFF;
11333   else if (Subtarget->isPICStyleStubPIC())
11334     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11335
11336   auto PtrVT = getPointerTy(DAG.getDataLayout());
11337   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11338   SDLoc DL(JT);
11339   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11340
11341   // With PIC, the address is actually $g + Offset.
11342   if (OpFlag)
11343     Result =
11344         DAG.getNode(ISD::ADD, DL, PtrVT,
11345                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11346
11347   return Result;
11348 }
11349
11350 SDValue
11351 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11352   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11353
11354   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11355   // global base reg.
11356   unsigned char OpFlag = 0;
11357   unsigned WrapperKind = X86ISD::Wrapper;
11358   CodeModel::Model M = DAG.getTarget().getCodeModel();
11359
11360   if (Subtarget->isPICStyleRIPRel() &&
11361       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11362     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11363       OpFlag = X86II::MO_GOTPCREL;
11364     WrapperKind = X86ISD::WrapperRIP;
11365   } else if (Subtarget->isPICStyleGOT()) {
11366     OpFlag = X86II::MO_GOT;
11367   } else if (Subtarget->isPICStyleStubPIC()) {
11368     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11369   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11370     OpFlag = X86II::MO_DARWIN_NONLAZY;
11371   }
11372
11373   auto PtrVT = getPointerTy(DAG.getDataLayout());
11374   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11375
11376   SDLoc DL(Op);
11377   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11378
11379   // With PIC, the address is actually $g + Offset.
11380   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11381       !Subtarget->is64Bit()) {
11382     Result =
11383         DAG.getNode(ISD::ADD, DL, PtrVT,
11384                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11385   }
11386
11387   // For symbols that require a load from a stub to get the address, emit the
11388   // load.
11389   if (isGlobalStubReference(OpFlag))
11390     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11391                          MachinePointerInfo::getGOT(), false, false, false, 0);
11392
11393   return Result;
11394 }
11395
11396 SDValue
11397 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11398   // Create the TargetBlockAddressAddress node.
11399   unsigned char OpFlags =
11400     Subtarget->ClassifyBlockAddressReference();
11401   CodeModel::Model M = DAG.getTarget().getCodeModel();
11402   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11403   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11404   SDLoc dl(Op);
11405   auto PtrVT = getPointerTy(DAG.getDataLayout());
11406   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11407
11408   if (Subtarget->isPICStyleRIPRel() &&
11409       (M == CodeModel::Small || M == CodeModel::Kernel))
11410     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11411   else
11412     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11413
11414   // With PIC, the address is actually $g + Offset.
11415   if (isGlobalRelativeToPICBase(OpFlags)) {
11416     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11417                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11418   }
11419
11420   return Result;
11421 }
11422
11423 SDValue
11424 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11425                                       int64_t Offset, SelectionDAG &DAG) const {
11426   // Create the TargetGlobalAddress node, folding in the constant
11427   // offset if it is legal.
11428   unsigned char OpFlags =
11429       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11430   CodeModel::Model M = DAG.getTarget().getCodeModel();
11431   auto PtrVT = getPointerTy(DAG.getDataLayout());
11432   SDValue Result;
11433   if (OpFlags == X86II::MO_NO_FLAG &&
11434       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11435     // A direct static reference to a global.
11436     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11437     Offset = 0;
11438   } else {
11439     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11440   }
11441
11442   if (Subtarget->isPICStyleRIPRel() &&
11443       (M == CodeModel::Small || M == CodeModel::Kernel))
11444     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11445   else
11446     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11447
11448   // With PIC, the address is actually $g + Offset.
11449   if (isGlobalRelativeToPICBase(OpFlags)) {
11450     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11451                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11452   }
11453
11454   // For globals that require a load from a stub to get the address, emit the
11455   // load.
11456   if (isGlobalStubReference(OpFlags))
11457     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11458                          MachinePointerInfo::getGOT(), false, false, false, 0);
11459
11460   // If there was a non-zero offset that we didn't fold, create an explicit
11461   // addition for it.
11462   if (Offset != 0)
11463     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11464                          DAG.getConstant(Offset, dl, PtrVT));
11465
11466   return Result;
11467 }
11468
11469 SDValue
11470 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11471   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11472   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11473   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11474 }
11475
11476 static SDValue
11477 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11478            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11479            unsigned char OperandFlags, bool LocalDynamic = false) {
11480   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11481   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11482   SDLoc dl(GA);
11483   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11484                                            GA->getValueType(0),
11485                                            GA->getOffset(),
11486                                            OperandFlags);
11487
11488   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11489                                            : X86ISD::TLSADDR;
11490
11491   if (InFlag) {
11492     SDValue Ops[] = { Chain,  TGA, *InFlag };
11493     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11494   } else {
11495     SDValue Ops[]  = { Chain, TGA };
11496     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11497   }
11498
11499   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11500   MFI->setAdjustsStack(true);
11501   MFI->setHasCalls(true);
11502
11503   SDValue Flag = Chain.getValue(1);
11504   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11505 }
11506
11507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11508 static SDValue
11509 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11510                                 const EVT PtrVT) {
11511   SDValue InFlag;
11512   SDLoc dl(GA);  // ? function entry point might be better
11513   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11514                                    DAG.getNode(X86ISD::GlobalBaseReg,
11515                                                SDLoc(), PtrVT), InFlag);
11516   InFlag = Chain.getValue(1);
11517
11518   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11519 }
11520
11521 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11522 static SDValue
11523 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11524                                 const EVT PtrVT) {
11525   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11526                     X86::RAX, X86II::MO_TLSGD);
11527 }
11528
11529 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11530                                            SelectionDAG &DAG,
11531                                            const EVT PtrVT,
11532                                            bool is64Bit) {
11533   SDLoc dl(GA);
11534
11535   // Get the start address of the TLS block for this module.
11536   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11537       .getInfo<X86MachineFunctionInfo>();
11538   MFI->incNumLocalDynamicTLSAccesses();
11539
11540   SDValue Base;
11541   if (is64Bit) {
11542     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11543                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11544   } else {
11545     SDValue InFlag;
11546     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11547         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11548     InFlag = Chain.getValue(1);
11549     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11550                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11551   }
11552
11553   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11554   // of Base.
11555
11556   // Build x@dtpoff.
11557   unsigned char OperandFlags = X86II::MO_DTPOFF;
11558   unsigned WrapperKind = X86ISD::Wrapper;
11559   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11560                                            GA->getValueType(0),
11561                                            GA->getOffset(), OperandFlags);
11562   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11563
11564   // Add x@dtpoff with the base.
11565   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11566 }
11567
11568 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11569 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11570                                    const EVT PtrVT, TLSModel::Model model,
11571                                    bool is64Bit, bool isPIC) {
11572   SDLoc dl(GA);
11573
11574   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11575   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11576                                                          is64Bit ? 257 : 256));
11577
11578   SDValue ThreadPointer =
11579       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11580                   MachinePointerInfo(Ptr), false, false, false, 0);
11581
11582   unsigned char OperandFlags = 0;
11583   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11584   // initialexec.
11585   unsigned WrapperKind = X86ISD::Wrapper;
11586   if (model == TLSModel::LocalExec) {
11587     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11588   } else if (model == TLSModel::InitialExec) {
11589     if (is64Bit) {
11590       OperandFlags = X86II::MO_GOTTPOFF;
11591       WrapperKind = X86ISD::WrapperRIP;
11592     } else {
11593       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11594     }
11595   } else {
11596     llvm_unreachable("Unexpected model");
11597   }
11598
11599   // emit "addl x@ntpoff,%eax" (local exec)
11600   // or "addl x@indntpoff,%eax" (initial exec)
11601   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11602   SDValue TGA =
11603       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11604                                  GA->getOffset(), OperandFlags);
11605   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11606
11607   if (model == TLSModel::InitialExec) {
11608     if (isPIC && !is64Bit) {
11609       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11610                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11611                            Offset);
11612     }
11613
11614     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11615                          MachinePointerInfo::getGOT(), false, false, false, 0);
11616   }
11617
11618   // The address of the thread local variable is the add of the thread
11619   // pointer with the offset of the variable.
11620   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11621 }
11622
11623 SDValue
11624 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11625
11626   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11627   const GlobalValue *GV = GA->getGlobal();
11628   auto PtrVT = getPointerTy(DAG.getDataLayout());
11629
11630   if (Subtarget->isTargetELF()) {
11631     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11632     switch (model) {
11633       case TLSModel::GeneralDynamic:
11634         if (Subtarget->is64Bit())
11635           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11636         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11637       case TLSModel::LocalDynamic:
11638         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11639                                            Subtarget->is64Bit());
11640       case TLSModel::InitialExec:
11641       case TLSModel::LocalExec:
11642         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11643                                    DAG.getTarget().getRelocationModel() ==
11644                                        Reloc::PIC_);
11645     }
11646     llvm_unreachable("Unknown TLS model.");
11647   }
11648
11649   if (Subtarget->isTargetDarwin()) {
11650     // Darwin only has one model of TLS.  Lower to that.
11651     unsigned char OpFlag = 0;
11652     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11653                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11654
11655     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11656     // global base reg.
11657     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11658                  !Subtarget->is64Bit();
11659     if (PIC32)
11660       OpFlag = X86II::MO_TLVP_PIC_BASE;
11661     else
11662       OpFlag = X86II::MO_TLVP;
11663     SDLoc DL(Op);
11664     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11665                                                 GA->getValueType(0),
11666                                                 GA->getOffset(), OpFlag);
11667     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11668
11669     // With PIC32, the address is actually $g + Offset.
11670     if (PIC32)
11671       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11672                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11673                            Offset);
11674
11675     // Lowering the machine isd will make sure everything is in the right
11676     // location.
11677     SDValue Chain = DAG.getEntryNode();
11678     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11679     SDValue Args[] = { Chain, Offset };
11680     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11681
11682     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11683     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11684     MFI->setAdjustsStack(true);
11685
11686     // And our return value (tls address) is in the standard call return value
11687     // location.
11688     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11689     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11690   }
11691
11692   if (Subtarget->isTargetKnownWindowsMSVC() ||
11693       Subtarget->isTargetWindowsGNU()) {
11694     // Just use the implicit TLS architecture
11695     // Need to generate someting similar to:
11696     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11697     //                                  ; from TEB
11698     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11699     //   mov     rcx, qword [rdx+rcx*8]
11700     //   mov     eax, .tls$:tlsvar
11701     //   [rax+rcx] contains the address
11702     // Windows 64bit: gs:0x58
11703     // Windows 32bit: fs:__tls_array
11704
11705     SDLoc dl(GA);
11706     SDValue Chain = DAG.getEntryNode();
11707
11708     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11709     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11710     // use its literal value of 0x2C.
11711     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11712                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11713                                                              256)
11714                                         : Type::getInt32PtrTy(*DAG.getContext(),
11715                                                               257));
11716
11717     SDValue TlsArray = Subtarget->is64Bit()
11718                            ? DAG.getIntPtrConstant(0x58, dl)
11719                            : (Subtarget->isTargetWindowsGNU()
11720                                   ? DAG.getIntPtrConstant(0x2C, dl)
11721                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11722
11723     SDValue ThreadPointer =
11724         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11725                     false, false, 0);
11726
11727     SDValue res;
11728     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11729       res = ThreadPointer;
11730     } else {
11731       // Load the _tls_index variable
11732       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11733       if (Subtarget->is64Bit())
11734         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11735                              MachinePointerInfo(), MVT::i32, false, false,
11736                              false, 0);
11737       else
11738         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11739                           false, false, 0);
11740
11741       auto &DL = DAG.getDataLayout();
11742       SDValue Scale =
11743           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11744       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11745
11746       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11747     }
11748
11749     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11750                       false, 0);
11751
11752     // Get the offset of start of .tls section
11753     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11754                                              GA->getValueType(0),
11755                                              GA->getOffset(), X86II::MO_SECREL);
11756     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11757
11758     // The address of the thread local variable is the add of the thread
11759     // pointer with the offset of the variable.
11760     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11761   }
11762
11763   llvm_unreachable("TLS not implemented for this target.");
11764 }
11765
11766 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11767 /// and take a 2 x i32 value to shift plus a shift amount.
11768 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11769   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11770   MVT VT = Op.getSimpleValueType();
11771   unsigned VTBits = VT.getSizeInBits();
11772   SDLoc dl(Op);
11773   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11774   SDValue ShOpLo = Op.getOperand(0);
11775   SDValue ShOpHi = Op.getOperand(1);
11776   SDValue ShAmt  = Op.getOperand(2);
11777   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11778   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11779   // during isel.
11780   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11781                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11782   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11783                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11784                        : DAG.getConstant(0, dl, VT);
11785
11786   SDValue Tmp2, Tmp3;
11787   if (Op.getOpcode() == ISD::SHL_PARTS) {
11788     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11789     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11790   } else {
11791     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11792     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11793   }
11794
11795   // If the shift amount is larger or equal than the width of a part we can't
11796   // rely on the results of shld/shrd. Insert a test and select the appropriate
11797   // values for large shift amounts.
11798   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11799                                 DAG.getConstant(VTBits, dl, MVT::i8));
11800   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11801                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11802
11803   SDValue Hi, Lo;
11804   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11805   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11806   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11807
11808   if (Op.getOpcode() == ISD::SHL_PARTS) {
11809     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11810     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11811   } else {
11812     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11813     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11814   }
11815
11816   SDValue Ops[2] = { Lo, Hi };
11817   return DAG.getMergeValues(Ops, dl);
11818 }
11819
11820 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11821                                            SelectionDAG &DAG) const {
11822   SDValue Src = Op.getOperand(0);
11823   MVT SrcVT = Src.getSimpleValueType();
11824   MVT VT = Op.getSimpleValueType();
11825   SDLoc dl(Op);
11826
11827   if (SrcVT.isVector()) {
11828     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11829       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11830                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11831                          DAG.getUNDEF(SrcVT)));
11832     }
11833     if (SrcVT.getVectorElementType() == MVT::i1) {
11834       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11835       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11836                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11837     }
11838     return SDValue();
11839   }
11840
11841   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11842          "Unknown SINT_TO_FP to lower!");
11843
11844   // These are really Legal; return the operand so the caller accepts it as
11845   // Legal.
11846   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11847     return Op;
11848   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11849       Subtarget->is64Bit()) {
11850     return Op;
11851   }
11852
11853   unsigned Size = SrcVT.getSizeInBits()/8;
11854   MachineFunction &MF = DAG.getMachineFunction();
11855   auto PtrVT = getPointerTy(MF.getDataLayout());
11856   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11857   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11858   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11859                                StackSlot,
11860                                MachinePointerInfo::getFixedStack(SSFI),
11861                                false, false, 0);
11862   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11863 }
11864
11865 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11866                                      SDValue StackSlot,
11867                                      SelectionDAG &DAG) const {
11868   // Build the FILD
11869   SDLoc DL(Op);
11870   SDVTList Tys;
11871   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11872   if (useSSE)
11873     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11874   else
11875     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11876
11877   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11878
11879   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11880   MachineMemOperand *MMO;
11881   if (FI) {
11882     int SSFI = FI->getIndex();
11883     MMO =
11884       DAG.getMachineFunction()
11885       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11886                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11887   } else {
11888     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11889     StackSlot = StackSlot.getOperand(1);
11890   }
11891   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11892   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11893                                            X86ISD::FILD, DL,
11894                                            Tys, Ops, SrcVT, MMO);
11895
11896   if (useSSE) {
11897     Chain = Result.getValue(1);
11898     SDValue InFlag = Result.getValue(2);
11899
11900     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11901     // shouldn't be necessary except that RFP cannot be live across
11902     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11903     MachineFunction &MF = DAG.getMachineFunction();
11904     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11905     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11906     auto PtrVT = getPointerTy(MF.getDataLayout());
11907     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11908     Tys = DAG.getVTList(MVT::Other);
11909     SDValue Ops[] = {
11910       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11911     };
11912     MachineMemOperand *MMO =
11913       DAG.getMachineFunction()
11914       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11915                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11916
11917     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11918                                     Ops, Op.getValueType(), MMO);
11919     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11920                          MachinePointerInfo::getFixedStack(SSFI),
11921                          false, false, false, 0);
11922   }
11923
11924   return Result;
11925 }
11926
11927 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11928 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11929                                                SelectionDAG &DAG) const {
11930   // This algorithm is not obvious. Here it is what we're trying to output:
11931   /*
11932      movq       %rax,  %xmm0
11933      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11934      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11935      #ifdef __SSE3__
11936        haddpd   %xmm0, %xmm0
11937      #else
11938        pshufd   $0x4e, %xmm0, %xmm1
11939        addpd    %xmm1, %xmm0
11940      #endif
11941   */
11942
11943   SDLoc dl(Op);
11944   LLVMContext *Context = DAG.getContext();
11945
11946   // Build some magic constants.
11947   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11948   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11949   auto PtrVT = getPointerTy(DAG.getDataLayout());
11950   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11951
11952   SmallVector<Constant*,2> CV1;
11953   CV1.push_back(
11954     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11955                                       APInt(64, 0x4330000000000000ULL))));
11956   CV1.push_back(
11957     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11958                                       APInt(64, 0x4530000000000000ULL))));
11959   Constant *C1 = ConstantVector::get(CV1);
11960   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11961
11962   // Load the 64-bit value into an XMM register.
11963   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11964                             Op.getOperand(0));
11965   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11966                               MachinePointerInfo::getConstantPool(),
11967                               false, false, false, 16);
11968   SDValue Unpck1 =
11969       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11970
11971   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11972                               MachinePointerInfo::getConstantPool(),
11973                               false, false, false, 16);
11974   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11975   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11976   SDValue Result;
11977
11978   if (Subtarget->hasSSE3()) {
11979     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11980     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11981   } else {
11982     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11983     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11984                                            S2F, 0x4E, DAG);
11985     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11986                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11987   }
11988
11989   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11990                      DAG.getIntPtrConstant(0, dl));
11991 }
11992
11993 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11994 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11995                                                SelectionDAG &DAG) const {
11996   SDLoc dl(Op);
11997   // FP constant to bias correct the final result.
11998   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11999                                    MVT::f64);
12000
12001   // Load the 32-bit value into an XMM register.
12002   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12003                              Op.getOperand(0));
12004
12005   // Zero out the upper parts of the register.
12006   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12007
12008   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12009                      DAG.getBitcast(MVT::v2f64, Load),
12010                      DAG.getIntPtrConstant(0, dl));
12011
12012   // Or the load with the bias.
12013   SDValue Or = DAG.getNode(
12014       ISD::OR, dl, MVT::v2i64,
12015       DAG.getBitcast(MVT::v2i64,
12016                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12017       DAG.getBitcast(MVT::v2i64,
12018                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12019   Or =
12020       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12021                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12022
12023   // Subtract the bias.
12024   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12025
12026   // Handle final rounding.
12027   EVT DestVT = Op.getValueType();
12028
12029   if (DestVT.bitsLT(MVT::f64))
12030     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12031                        DAG.getIntPtrConstant(0, dl));
12032   if (DestVT.bitsGT(MVT::f64))
12033     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12034
12035   // Handle final rounding.
12036   return Sub;
12037 }
12038
12039 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12040                                      const X86Subtarget &Subtarget) {
12041   // The algorithm is the following:
12042   // #ifdef __SSE4_1__
12043   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12044   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12045   //                                 (uint4) 0x53000000, 0xaa);
12046   // #else
12047   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12048   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12049   // #endif
12050   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12051   //     return (float4) lo + fhi;
12052
12053   SDLoc DL(Op);
12054   SDValue V = Op->getOperand(0);
12055   EVT VecIntVT = V.getValueType();
12056   bool Is128 = VecIntVT == MVT::v4i32;
12057   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12058   // If we convert to something else than the supported type, e.g., to v4f64,
12059   // abort early.
12060   if (VecFloatVT != Op->getValueType(0))
12061     return SDValue();
12062
12063   unsigned NumElts = VecIntVT.getVectorNumElements();
12064   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12065          "Unsupported custom type");
12066   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12067
12068   // In the #idef/#else code, we have in common:
12069   // - The vector of constants:
12070   // -- 0x4b000000
12071   // -- 0x53000000
12072   // - A shift:
12073   // -- v >> 16
12074
12075   // Create the splat vector for 0x4b000000.
12076   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12077   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12078                            CstLow, CstLow, CstLow, CstLow};
12079   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12080                                   makeArrayRef(&CstLowArray[0], NumElts));
12081   // Create the splat vector for 0x53000000.
12082   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12083   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12084                             CstHigh, CstHigh, CstHigh, CstHigh};
12085   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12086                                    makeArrayRef(&CstHighArray[0], NumElts));
12087
12088   // Create the right shift.
12089   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12090   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12091                              CstShift, CstShift, CstShift, CstShift};
12092   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12093                                     makeArrayRef(&CstShiftArray[0], NumElts));
12094   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12095
12096   SDValue Low, High;
12097   if (Subtarget.hasSSE41()) {
12098     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12099     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12100     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12101     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12102     // Low will be bitcasted right away, so do not bother bitcasting back to its
12103     // original type.
12104     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12105                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12106     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12107     //                                 (uint4) 0x53000000, 0xaa);
12108     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12109     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12110     // High will be bitcasted right away, so do not bother bitcasting back to
12111     // its original type.
12112     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12113                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12114   } else {
12115     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12116     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12117                                      CstMask, CstMask, CstMask);
12118     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12119     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12120     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12121
12122     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12123     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12124   }
12125
12126   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12127   SDValue CstFAdd = DAG.getConstantFP(
12128       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12129   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12130                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12131   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12132                                    makeArrayRef(&CstFAddArray[0], NumElts));
12133
12134   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12135   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12136   SDValue FHigh =
12137       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12138   //     return (float4) lo + fhi;
12139   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12140   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12141 }
12142
12143 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12144                                                SelectionDAG &DAG) const {
12145   SDValue N0 = Op.getOperand(0);
12146   MVT SVT = N0.getSimpleValueType();
12147   SDLoc dl(Op);
12148
12149   switch (SVT.SimpleTy) {
12150   default:
12151     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12152   case MVT::v4i8:
12153   case MVT::v4i16:
12154   case MVT::v8i8:
12155   case MVT::v8i16: {
12156     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12157     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12158                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12159   }
12160   case MVT::v4i32:
12161   case MVT::v8i32:
12162     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12163   case MVT::v16i8:
12164   case MVT::v16i16:
12165     if (Subtarget->hasAVX512())
12166       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12167                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12168   }
12169   llvm_unreachable(nullptr);
12170 }
12171
12172 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12173                                            SelectionDAG &DAG) const {
12174   SDValue N0 = Op.getOperand(0);
12175   SDLoc dl(Op);
12176   auto PtrVT = getPointerTy(DAG.getDataLayout());
12177
12178   if (Op.getValueType().isVector())
12179     return lowerUINT_TO_FP_vec(Op, DAG);
12180
12181   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12182   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12183   // the optimization here.
12184   if (DAG.SignBitIsZero(N0))
12185     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12186
12187   MVT SrcVT = N0.getSimpleValueType();
12188   MVT DstVT = Op.getSimpleValueType();
12189   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12190     return LowerUINT_TO_FP_i64(Op, DAG);
12191   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12192     return LowerUINT_TO_FP_i32(Op, DAG);
12193   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12194     return SDValue();
12195
12196   // Make a 64-bit buffer, and use it to build an FILD.
12197   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12198   if (SrcVT == MVT::i32) {
12199     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12200     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12201     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12202                                   StackSlot, MachinePointerInfo(),
12203                                   false, false, 0);
12204     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12205                                   OffsetSlot, MachinePointerInfo(),
12206                                   false, false, 0);
12207     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12208     return Fild;
12209   }
12210
12211   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12212   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12213                                StackSlot, MachinePointerInfo(),
12214                                false, false, 0);
12215   // For i64 source, we need to add the appropriate power of 2 if the input
12216   // was negative.  This is the same as the optimization in
12217   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12218   // we must be careful to do the computation in x87 extended precision, not
12219   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12220   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12221   MachineMemOperand *MMO =
12222     DAG.getMachineFunction()
12223     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12224                           MachineMemOperand::MOLoad, 8, 8);
12225
12226   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12227   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12228   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12229                                          MVT::i64, MMO);
12230
12231   APInt FF(32, 0x5F800000ULL);
12232
12233   // Check whether the sign bit is set.
12234   SDValue SignSet = DAG.getSetCC(
12235       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12236       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12237
12238   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12239   SDValue FudgePtr = DAG.getConstantPool(
12240       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12241
12242   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12243   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12244   SDValue Four = DAG.getIntPtrConstant(4, dl);
12245   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12246                                Zero, Four);
12247   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12248
12249   // Load the value out, extending it from f32 to f80.
12250   // FIXME: Avoid the extend by constructing the right constant pool?
12251   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12252                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12253                                  MVT::f32, false, false, false, 4);
12254   // Extend everything to 80 bits to force it to be done on x87.
12255   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12256   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12257                      DAG.getIntPtrConstant(0, dl));
12258 }
12259
12260 std::pair<SDValue,SDValue>
12261 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12262                                     bool IsSigned, bool IsReplace) const {
12263   SDLoc DL(Op);
12264
12265   EVT DstTy = Op.getValueType();
12266   auto PtrVT = getPointerTy(DAG.getDataLayout());
12267
12268   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12269     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12270     DstTy = MVT::i64;
12271   }
12272
12273   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12274          DstTy.getSimpleVT() >= MVT::i16 &&
12275          "Unknown FP_TO_INT to lower!");
12276
12277   // These are really Legal.
12278   if (DstTy == MVT::i32 &&
12279       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12280     return std::make_pair(SDValue(), SDValue());
12281   if (Subtarget->is64Bit() &&
12282       DstTy == MVT::i64 &&
12283       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12284     return std::make_pair(SDValue(), SDValue());
12285
12286   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12287   // stack slot, or into the FTOL runtime function.
12288   MachineFunction &MF = DAG.getMachineFunction();
12289   unsigned MemSize = DstTy.getSizeInBits()/8;
12290   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12291   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12292
12293   unsigned Opc;
12294   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12295     Opc = X86ISD::WIN_FTOL;
12296   else
12297     switch (DstTy.getSimpleVT().SimpleTy) {
12298     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12299     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12300     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12301     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12302     }
12303
12304   SDValue Chain = DAG.getEntryNode();
12305   SDValue Value = Op.getOperand(0);
12306   EVT TheVT = Op.getOperand(0).getValueType();
12307   // FIXME This causes a redundant load/store if the SSE-class value is already
12308   // in memory, such as if it is on the callstack.
12309   if (isScalarFPTypeInSSEReg(TheVT)) {
12310     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12311     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12312                          MachinePointerInfo::getFixedStack(SSFI),
12313                          false, false, 0);
12314     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12315     SDValue Ops[] = {
12316       Chain, StackSlot, DAG.getValueType(TheVT)
12317     };
12318
12319     MachineMemOperand *MMO =
12320       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12321                               MachineMemOperand::MOLoad, MemSize, MemSize);
12322     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12323     Chain = Value.getValue(1);
12324     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12325     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12326   }
12327
12328   MachineMemOperand *MMO =
12329     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12330                             MachineMemOperand::MOStore, MemSize, MemSize);
12331
12332   if (Opc != X86ISD::WIN_FTOL) {
12333     // Build the FP_TO_INT*_IN_MEM
12334     SDValue Ops[] = { Chain, Value, StackSlot };
12335     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12336                                            Ops, DstTy, MMO);
12337     return std::make_pair(FIST, StackSlot);
12338   } else {
12339     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12340       DAG.getVTList(MVT::Other, MVT::Glue),
12341       Chain, Value);
12342     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12343       MVT::i32, ftol.getValue(1));
12344     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12345       MVT::i32, eax.getValue(2));
12346     SDValue Ops[] = { eax, edx };
12347     SDValue pair = IsReplace
12348       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12349       : DAG.getMergeValues(Ops, DL);
12350     return std::make_pair(pair, SDValue());
12351   }
12352 }
12353
12354 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12355                               const X86Subtarget *Subtarget) {
12356   MVT VT = Op->getSimpleValueType(0);
12357   SDValue In = Op->getOperand(0);
12358   MVT InVT = In.getSimpleValueType();
12359   SDLoc dl(Op);
12360
12361   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12362     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12363
12364   // Optimize vectors in AVX mode:
12365   //
12366   //   v8i16 -> v8i32
12367   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12368   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12369   //   Concat upper and lower parts.
12370   //
12371   //   v4i32 -> v4i64
12372   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12373   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12374   //   Concat upper and lower parts.
12375   //
12376
12377   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12378       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12379       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12380     return SDValue();
12381
12382   if (Subtarget->hasInt256())
12383     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12384
12385   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12386   SDValue Undef = DAG.getUNDEF(InVT);
12387   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12388   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12389   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12390
12391   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12392                              VT.getVectorNumElements()/2);
12393
12394   OpLo = DAG.getBitcast(HVT, OpLo);
12395   OpHi = DAG.getBitcast(HVT, OpHi);
12396
12397   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12398 }
12399
12400 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12401                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12402   MVT VT = Op->getSimpleValueType(0);
12403   SDValue In = Op->getOperand(0);
12404   MVT InVT = In.getSimpleValueType();
12405   SDLoc DL(Op);
12406   unsigned int NumElts = VT.getVectorNumElements();
12407   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12408     return SDValue();
12409
12410   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12411     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12412
12413   assert(InVT.getVectorElementType() == MVT::i1);
12414   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12415   SDValue One =
12416    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12417   SDValue Zero =
12418    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12419
12420   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12421   if (VT.is512BitVector())
12422     return V;
12423   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12424 }
12425
12426 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12427                                SelectionDAG &DAG) {
12428   if (Subtarget->hasFp256())
12429     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12430       return Res;
12431
12432   return SDValue();
12433 }
12434
12435 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12436                                 SelectionDAG &DAG) {
12437   SDLoc DL(Op);
12438   MVT VT = Op.getSimpleValueType();
12439   SDValue In = Op.getOperand(0);
12440   MVT SVT = In.getSimpleValueType();
12441
12442   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12443     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12444
12445   if (Subtarget->hasFp256())
12446     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12447       return Res;
12448
12449   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12450          VT.getVectorNumElements() != SVT.getVectorNumElements());
12451   return SDValue();
12452 }
12453
12454 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12455   SDLoc DL(Op);
12456   MVT VT = Op.getSimpleValueType();
12457   SDValue In = Op.getOperand(0);
12458   MVT InVT = In.getSimpleValueType();
12459
12460   if (VT == MVT::i1) {
12461     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12462            "Invalid scalar TRUNCATE operation");
12463     if (InVT.getSizeInBits() >= 32)
12464       return SDValue();
12465     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12466     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12467   }
12468   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12469          "Invalid TRUNCATE operation");
12470
12471   // move vector to mask - truncate solution for SKX
12472   if (VT.getVectorElementType() == MVT::i1) {
12473     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12474         Subtarget->hasBWI())
12475       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12476     if ((InVT.is256BitVector() || InVT.is128BitVector())
12477         && InVT.getScalarSizeInBits() <= 16 &&
12478         Subtarget->hasBWI() && Subtarget->hasVLX())
12479       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12480     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12481         Subtarget->hasDQI())
12482       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12483     if ((InVT.is256BitVector() || InVT.is128BitVector())
12484         && InVT.getScalarSizeInBits() >= 32 &&
12485         Subtarget->hasDQI() && Subtarget->hasVLX())
12486       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12487   }
12488   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12489     if (VT.getVectorElementType().getSizeInBits() >=8)
12490       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12491
12492     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12493     unsigned NumElts = InVT.getVectorNumElements();
12494     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12495     if (InVT.getSizeInBits() < 512) {
12496       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12497       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12498       InVT = ExtVT;
12499     }
12500
12501     SDValue OneV =
12502      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12503     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12504     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12505   }
12506
12507   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12508     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12509     if (Subtarget->hasInt256()) {
12510       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12511       In = DAG.getBitcast(MVT::v8i32, In);
12512       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12513                                 ShufMask);
12514       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12515                          DAG.getIntPtrConstant(0, DL));
12516     }
12517
12518     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12519                                DAG.getIntPtrConstant(0, DL));
12520     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12521                                DAG.getIntPtrConstant(2, DL));
12522     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12523     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12524     static const int ShufMask[] = {0, 2, 4, 6};
12525     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12526   }
12527
12528   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12529     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12530     if (Subtarget->hasInt256()) {
12531       In = DAG.getBitcast(MVT::v32i8, In);
12532
12533       SmallVector<SDValue,32> pshufbMask;
12534       for (unsigned i = 0; i < 2; ++i) {
12535         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12536         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12537         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12538         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12539         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12540         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12541         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12542         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12543         for (unsigned j = 0; j < 8; ++j)
12544           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12545       }
12546       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12547       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12548       In = DAG.getBitcast(MVT::v4i64, In);
12549
12550       static const int ShufMask[] = {0,  2,  -1,  -1};
12551       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12552                                 &ShufMask[0]);
12553       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12554                        DAG.getIntPtrConstant(0, DL));
12555       return DAG.getBitcast(VT, In);
12556     }
12557
12558     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12559                                DAG.getIntPtrConstant(0, DL));
12560
12561     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12562                                DAG.getIntPtrConstant(4, DL));
12563
12564     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12565     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12566
12567     // The PSHUFB mask:
12568     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12569                                    -1, -1, -1, -1, -1, -1, -1, -1};
12570
12571     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12572     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12573     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12574
12575     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12576     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12577
12578     // The MOVLHPS Mask:
12579     static const int ShufMask2[] = {0, 1, 4, 5};
12580     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12581     return DAG.getBitcast(MVT::v8i16, res);
12582   }
12583
12584   // Handle truncation of V256 to V128 using shuffles.
12585   if (!VT.is128BitVector() || !InVT.is256BitVector())
12586     return SDValue();
12587
12588   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12589
12590   unsigned NumElems = VT.getVectorNumElements();
12591   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12592
12593   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12594   // Prepare truncation shuffle mask
12595   for (unsigned i = 0; i != NumElems; ++i)
12596     MaskVec[i] = i * 2;
12597   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12598                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12599   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12600                      DAG.getIntPtrConstant(0, DL));
12601 }
12602
12603 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12604                                            SelectionDAG &DAG) const {
12605   assert(!Op.getSimpleValueType().isVector());
12606
12607   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12608     /*IsSigned=*/ true, /*IsReplace=*/ false);
12609   SDValue FIST = Vals.first, StackSlot = Vals.second;
12610   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12611   if (!FIST.getNode()) return Op;
12612
12613   if (StackSlot.getNode())
12614     // Load the result.
12615     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12616                        FIST, StackSlot, MachinePointerInfo(),
12617                        false, false, false, 0);
12618
12619   // The node is the result.
12620   return FIST;
12621 }
12622
12623 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12624                                            SelectionDAG &DAG) const {
12625   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12626     /*IsSigned=*/ false, /*IsReplace=*/ false);
12627   SDValue FIST = Vals.first, StackSlot = Vals.second;
12628   assert(FIST.getNode() && "Unexpected failure");
12629
12630   if (StackSlot.getNode())
12631     // Load the result.
12632     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12633                        FIST, StackSlot, MachinePointerInfo(),
12634                        false, false, false, 0);
12635
12636   // The node is the result.
12637   return FIST;
12638 }
12639
12640 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12641   SDLoc DL(Op);
12642   MVT VT = Op.getSimpleValueType();
12643   SDValue In = Op.getOperand(0);
12644   MVT SVT = In.getSimpleValueType();
12645
12646   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12647
12648   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12649                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12650                                  In, DAG.getUNDEF(SVT)));
12651 }
12652
12653 /// The only differences between FABS and FNEG are the mask and the logic op.
12654 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12655 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12656   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12657          "Wrong opcode for lowering FABS or FNEG.");
12658
12659   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12660
12661   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12662   // into an FNABS. We'll lower the FABS after that if it is still in use.
12663   if (IsFABS)
12664     for (SDNode *User : Op->uses())
12665       if (User->getOpcode() == ISD::FNEG)
12666         return Op;
12667
12668   SDValue Op0 = Op.getOperand(0);
12669   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12670
12671   SDLoc dl(Op);
12672   MVT VT = Op.getSimpleValueType();
12673   // Assume scalar op for initialization; update for vector if needed.
12674   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12675   // generate a 16-byte vector constant and logic op even for the scalar case.
12676   // Using a 16-byte mask allows folding the load of the mask with
12677   // the logic op, so it can save (~4 bytes) on code size.
12678   MVT EltVT = VT;
12679   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12680   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12681   // decide if we should generate a 16-byte constant mask when we only need 4 or
12682   // 8 bytes for the scalar case.
12683   if (VT.isVector()) {
12684     EltVT = VT.getVectorElementType();
12685     NumElts = VT.getVectorNumElements();
12686   }
12687
12688   unsigned EltBits = EltVT.getSizeInBits();
12689   LLVMContext *Context = DAG.getContext();
12690   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12691   APInt MaskElt =
12692     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12693   Constant *C = ConstantInt::get(*Context, MaskElt);
12694   C = ConstantVector::getSplat(NumElts, C);
12695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12696   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12697   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12698   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12699                              MachinePointerInfo::getConstantPool(),
12700                              false, false, false, Alignment);
12701
12702   if (VT.isVector()) {
12703     // For a vector, cast operands to a vector type, perform the logic op,
12704     // and cast the result back to the original value type.
12705     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12706     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12707     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12708                               : DAG.getBitcast(VecVT, Op0);
12709     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12710     return DAG.getBitcast(VT,
12711                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12712   }
12713
12714   // If not vector, then scalar.
12715   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12716   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12717   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12718 }
12719
12720 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12722   LLVMContext *Context = DAG.getContext();
12723   SDValue Op0 = Op.getOperand(0);
12724   SDValue Op1 = Op.getOperand(1);
12725   SDLoc dl(Op);
12726   MVT VT = Op.getSimpleValueType();
12727   MVT SrcVT = Op1.getSimpleValueType();
12728
12729   // If second operand is smaller, extend it first.
12730   if (SrcVT.bitsLT(VT)) {
12731     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12732     SrcVT = VT;
12733   }
12734   // And if it is bigger, shrink it first.
12735   if (SrcVT.bitsGT(VT)) {
12736     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12737     SrcVT = VT;
12738   }
12739
12740   // At this point the operands and the result should have the same
12741   // type, and that won't be f80 since that is not custom lowered.
12742
12743   const fltSemantics &Sem =
12744       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12745   const unsigned SizeInBits = VT.getSizeInBits();
12746
12747   SmallVector<Constant *, 4> CV(
12748       VT == MVT::f64 ? 2 : 4,
12749       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12750
12751   // First, clear all bits but the sign bit from the second operand (sign).
12752   CV[0] = ConstantFP::get(*Context,
12753                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12754   Constant *C = ConstantVector::get(CV);
12755   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12756   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12757   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12758                               MachinePointerInfo::getConstantPool(),
12759                               false, false, false, 16);
12760   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12761
12762   // Next, clear the sign bit from the first operand (magnitude).
12763   // If it's a constant, we can clear it here.
12764   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12765     APFloat APF = Op0CN->getValueAPF();
12766     // If the magnitude is a positive zero, the sign bit alone is enough.
12767     if (APF.isPosZero())
12768       return SignBit;
12769     APF.clearSign();
12770     CV[0] = ConstantFP::get(*Context, APF);
12771   } else {
12772     CV[0] = ConstantFP::get(
12773         *Context,
12774         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12775   }
12776   C = ConstantVector::get(CV);
12777   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12778   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12779                             MachinePointerInfo::getConstantPool(),
12780                             false, false, false, 16);
12781   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12782   if (!isa<ConstantFPSDNode>(Op0))
12783     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12784
12785   // OR the magnitude value with the sign bit.
12786   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12787 }
12788
12789 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12790   SDValue N0 = Op.getOperand(0);
12791   SDLoc dl(Op);
12792   MVT VT = Op.getSimpleValueType();
12793
12794   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12795   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12796                                   DAG.getConstant(1, dl, VT));
12797   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12798 }
12799
12800 // Check whether an OR'd tree is PTEST-able.
12801 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12802                                       SelectionDAG &DAG) {
12803   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12804
12805   if (!Subtarget->hasSSE41())
12806     return SDValue();
12807
12808   if (!Op->hasOneUse())
12809     return SDValue();
12810
12811   SDNode *N = Op.getNode();
12812   SDLoc DL(N);
12813
12814   SmallVector<SDValue, 8> Opnds;
12815   DenseMap<SDValue, unsigned> VecInMap;
12816   SmallVector<SDValue, 8> VecIns;
12817   EVT VT = MVT::Other;
12818
12819   // Recognize a special case where a vector is casted into wide integer to
12820   // test all 0s.
12821   Opnds.push_back(N->getOperand(0));
12822   Opnds.push_back(N->getOperand(1));
12823
12824   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12825     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12826     // BFS traverse all OR'd operands.
12827     if (I->getOpcode() == ISD::OR) {
12828       Opnds.push_back(I->getOperand(0));
12829       Opnds.push_back(I->getOperand(1));
12830       // Re-evaluate the number of nodes to be traversed.
12831       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12832       continue;
12833     }
12834
12835     // Quit if a non-EXTRACT_VECTOR_ELT
12836     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12837       return SDValue();
12838
12839     // Quit if without a constant index.
12840     SDValue Idx = I->getOperand(1);
12841     if (!isa<ConstantSDNode>(Idx))
12842       return SDValue();
12843
12844     SDValue ExtractedFromVec = I->getOperand(0);
12845     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12846     if (M == VecInMap.end()) {
12847       VT = ExtractedFromVec.getValueType();
12848       // Quit if not 128/256-bit vector.
12849       if (!VT.is128BitVector() && !VT.is256BitVector())
12850         return SDValue();
12851       // Quit if not the same type.
12852       if (VecInMap.begin() != VecInMap.end() &&
12853           VT != VecInMap.begin()->first.getValueType())
12854         return SDValue();
12855       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12856       VecIns.push_back(ExtractedFromVec);
12857     }
12858     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12859   }
12860
12861   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12862          "Not extracted from 128-/256-bit vector.");
12863
12864   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12865
12866   for (DenseMap<SDValue, unsigned>::const_iterator
12867         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12868     // Quit if not all elements are used.
12869     if (I->second != FullMask)
12870       return SDValue();
12871   }
12872
12873   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12874
12875   // Cast all vectors into TestVT for PTEST.
12876   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12877     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12878
12879   // If more than one full vectors are evaluated, OR them first before PTEST.
12880   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12881     // Each iteration will OR 2 nodes and append the result until there is only
12882     // 1 node left, i.e. the final OR'd value of all vectors.
12883     SDValue LHS = VecIns[Slot];
12884     SDValue RHS = VecIns[Slot + 1];
12885     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12886   }
12887
12888   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12889                      VecIns.back(), VecIns.back());
12890 }
12891
12892 /// \brief return true if \c Op has a use that doesn't just read flags.
12893 static bool hasNonFlagsUse(SDValue Op) {
12894   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12895        ++UI) {
12896     SDNode *User = *UI;
12897     unsigned UOpNo = UI.getOperandNo();
12898     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12899       // Look pass truncate.
12900       UOpNo = User->use_begin().getOperandNo();
12901       User = *User->use_begin();
12902     }
12903
12904     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12905         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12906       return true;
12907   }
12908   return false;
12909 }
12910
12911 /// Emit nodes that will be selected as "test Op0,Op0", or something
12912 /// equivalent.
12913 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12914                                     SelectionDAG &DAG) const {
12915   if (Op.getValueType() == MVT::i1) {
12916     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12917     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12918                        DAG.getConstant(0, dl, MVT::i8));
12919   }
12920   // CF and OF aren't always set the way we want. Determine which
12921   // of these we need.
12922   bool NeedCF = false;
12923   bool NeedOF = false;
12924   switch (X86CC) {
12925   default: break;
12926   case X86::COND_A: case X86::COND_AE:
12927   case X86::COND_B: case X86::COND_BE:
12928     NeedCF = true;
12929     break;
12930   case X86::COND_G: case X86::COND_GE:
12931   case X86::COND_L: case X86::COND_LE:
12932   case X86::COND_O: case X86::COND_NO: {
12933     // Check if we really need to set the
12934     // Overflow flag. If NoSignedWrap is present
12935     // that is not actually needed.
12936     switch (Op->getOpcode()) {
12937     case ISD::ADD:
12938     case ISD::SUB:
12939     case ISD::MUL:
12940     case ISD::SHL: {
12941       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12942       if (BinNode->Flags.hasNoSignedWrap())
12943         break;
12944     }
12945     default:
12946       NeedOF = true;
12947       break;
12948     }
12949     break;
12950   }
12951   }
12952   // See if we can use the EFLAGS value from the operand instead of
12953   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12954   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12955   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12956     // Emit a CMP with 0, which is the TEST pattern.
12957     //if (Op.getValueType() == MVT::i1)
12958     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12959     //                     DAG.getConstant(0, MVT::i1));
12960     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12961                        DAG.getConstant(0, dl, Op.getValueType()));
12962   }
12963   unsigned Opcode = 0;
12964   unsigned NumOperands = 0;
12965
12966   // Truncate operations may prevent the merge of the SETCC instruction
12967   // and the arithmetic instruction before it. Attempt to truncate the operands
12968   // of the arithmetic instruction and use a reduced bit-width instruction.
12969   bool NeedTruncation = false;
12970   SDValue ArithOp = Op;
12971   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12972     SDValue Arith = Op->getOperand(0);
12973     // Both the trunc and the arithmetic op need to have one user each.
12974     if (Arith->hasOneUse())
12975       switch (Arith.getOpcode()) {
12976         default: break;
12977         case ISD::ADD:
12978         case ISD::SUB:
12979         case ISD::AND:
12980         case ISD::OR:
12981         case ISD::XOR: {
12982           NeedTruncation = true;
12983           ArithOp = Arith;
12984         }
12985       }
12986   }
12987
12988   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12989   // which may be the result of a CAST.  We use the variable 'Op', which is the
12990   // non-casted variable when we check for possible users.
12991   switch (ArithOp.getOpcode()) {
12992   case ISD::ADD:
12993     // Due to an isel shortcoming, be conservative if this add is likely to be
12994     // selected as part of a load-modify-store instruction. When the root node
12995     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12996     // uses of other nodes in the match, such as the ADD in this case. This
12997     // leads to the ADD being left around and reselected, with the result being
12998     // two adds in the output.  Alas, even if none our users are stores, that
12999     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13000     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13001     // climbing the DAG back to the root, and it doesn't seem to be worth the
13002     // effort.
13003     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13004          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13005       if (UI->getOpcode() != ISD::CopyToReg &&
13006           UI->getOpcode() != ISD::SETCC &&
13007           UI->getOpcode() != ISD::STORE)
13008         goto default_case;
13009
13010     if (ConstantSDNode *C =
13011         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13012       // An add of one will be selected as an INC.
13013       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13014         Opcode = X86ISD::INC;
13015         NumOperands = 1;
13016         break;
13017       }
13018
13019       // An add of negative one (subtract of one) will be selected as a DEC.
13020       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13021         Opcode = X86ISD::DEC;
13022         NumOperands = 1;
13023         break;
13024       }
13025     }
13026
13027     // Otherwise use a regular EFLAGS-setting add.
13028     Opcode = X86ISD::ADD;
13029     NumOperands = 2;
13030     break;
13031   case ISD::SHL:
13032   case ISD::SRL:
13033     // If we have a constant logical shift that's only used in a comparison
13034     // against zero turn it into an equivalent AND. This allows turning it into
13035     // a TEST instruction later.
13036     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13037         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13038       EVT VT = Op.getValueType();
13039       unsigned BitWidth = VT.getSizeInBits();
13040       unsigned ShAmt = Op->getConstantOperandVal(1);
13041       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13042         break;
13043       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13044                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13045                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13046       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13047         break;
13048       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13049                                 DAG.getConstant(Mask, dl, VT));
13050       DAG.ReplaceAllUsesWith(Op, New);
13051       Op = New;
13052     }
13053     break;
13054
13055   case ISD::AND:
13056     // If the primary and result isn't used, don't bother using X86ISD::AND,
13057     // because a TEST instruction will be better.
13058     if (!hasNonFlagsUse(Op))
13059       break;
13060     // FALL THROUGH
13061   case ISD::SUB:
13062   case ISD::OR:
13063   case ISD::XOR:
13064     // Due to the ISEL shortcoming noted above, be conservative if this op is
13065     // likely to be selected as part of a load-modify-store instruction.
13066     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13067            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13068       if (UI->getOpcode() == ISD::STORE)
13069         goto default_case;
13070
13071     // Otherwise use a regular EFLAGS-setting instruction.
13072     switch (ArithOp.getOpcode()) {
13073     default: llvm_unreachable("unexpected operator!");
13074     case ISD::SUB: Opcode = X86ISD::SUB; break;
13075     case ISD::XOR: Opcode = X86ISD::XOR; break;
13076     case ISD::AND: Opcode = X86ISD::AND; break;
13077     case ISD::OR: {
13078       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13079         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13080         if (EFLAGS.getNode())
13081           return EFLAGS;
13082       }
13083       Opcode = X86ISD::OR;
13084       break;
13085     }
13086     }
13087
13088     NumOperands = 2;
13089     break;
13090   case X86ISD::ADD:
13091   case X86ISD::SUB:
13092   case X86ISD::INC:
13093   case X86ISD::DEC:
13094   case X86ISD::OR:
13095   case X86ISD::XOR:
13096   case X86ISD::AND:
13097     return SDValue(Op.getNode(), 1);
13098   default:
13099   default_case:
13100     break;
13101   }
13102
13103   // If we found that truncation is beneficial, perform the truncation and
13104   // update 'Op'.
13105   if (NeedTruncation) {
13106     EVT VT = Op.getValueType();
13107     SDValue WideVal = Op->getOperand(0);
13108     EVT WideVT = WideVal.getValueType();
13109     unsigned ConvertedOp = 0;
13110     // Use a target machine opcode to prevent further DAGCombine
13111     // optimizations that may separate the arithmetic operations
13112     // from the setcc node.
13113     switch (WideVal.getOpcode()) {
13114       default: break;
13115       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13116       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13117       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13118       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13119       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13120     }
13121
13122     if (ConvertedOp) {
13123       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13124       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13125         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13126         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13127         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13128       }
13129     }
13130   }
13131
13132   if (Opcode == 0)
13133     // Emit a CMP with 0, which is the TEST pattern.
13134     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13135                        DAG.getConstant(0, dl, Op.getValueType()));
13136
13137   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13138   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13139
13140   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13141   DAG.ReplaceAllUsesWith(Op, New);
13142   return SDValue(New.getNode(), 1);
13143 }
13144
13145 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13146 /// equivalent.
13147 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13148                                    SDLoc dl, SelectionDAG &DAG) const {
13149   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13150     if (C->getAPIntValue() == 0)
13151       return EmitTest(Op0, X86CC, dl, DAG);
13152
13153      if (Op0.getValueType() == MVT::i1)
13154        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13155   }
13156
13157   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13158        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13159     // Do the comparison at i32 if it's smaller, besides the Atom case.
13160     // This avoids subregister aliasing issues. Keep the smaller reference
13161     // if we're optimizing for size, however, as that'll allow better folding
13162     // of memory operations.
13163     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13164         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13165             Attribute::MinSize) &&
13166         !Subtarget->isAtom()) {
13167       unsigned ExtendOp =
13168           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13169       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13170       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13171     }
13172     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13173     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13174     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13175                               Op0, Op1);
13176     return SDValue(Sub.getNode(), 1);
13177   }
13178   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13179 }
13180
13181 /// Convert a comparison if required by the subtarget.
13182 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13183                                                  SelectionDAG &DAG) const {
13184   // If the subtarget does not support the FUCOMI instruction, floating-point
13185   // comparisons have to be converted.
13186   if (Subtarget->hasCMov() ||
13187       Cmp.getOpcode() != X86ISD::CMP ||
13188       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13189       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13190     return Cmp;
13191
13192   // The instruction selector will select an FUCOM instruction instead of
13193   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13194   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13195   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13196   SDLoc dl(Cmp);
13197   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13198   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13199   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13200                             DAG.getConstant(8, dl, MVT::i8));
13201   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13202   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13203 }
13204
13205 /// The minimum architected relative accuracy is 2^-12. We need one
13206 /// Newton-Raphson step to have a good float result (24 bits of precision).
13207 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13208                                             DAGCombinerInfo &DCI,
13209                                             unsigned &RefinementSteps,
13210                                             bool &UseOneConstNR) const {
13211   EVT VT = Op.getValueType();
13212   const char *RecipOp;
13213
13214   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13215   // TODO: Add support for AVX512 (v16f32).
13216   // It is likely not profitable to do this for f64 because a double-precision
13217   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13218   // instructions: convert to single, rsqrtss, convert back to double, refine
13219   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13220   // along with FMA, this could be a throughput win.
13221   if (VT == MVT::f32 && Subtarget->hasSSE1())
13222     RecipOp = "sqrtf";
13223   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13224            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13225     RecipOp = "vec-sqrtf";
13226   else
13227     return SDValue();
13228
13229   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13230   if (!Recips.isEnabled(RecipOp))
13231     return SDValue();
13232
13233   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13234   UseOneConstNR = false;
13235   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13236 }
13237
13238 /// The minimum architected relative accuracy is 2^-12. We need one
13239 /// Newton-Raphson step to have a good float result (24 bits of precision).
13240 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13241                                             DAGCombinerInfo &DCI,
13242                                             unsigned &RefinementSteps) const {
13243   EVT VT = Op.getValueType();
13244   const char *RecipOp;
13245
13246   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13247   // TODO: Add support for AVX512 (v16f32).
13248   // It is likely not profitable to do this for f64 because a double-precision
13249   // reciprocal estimate with refinement on x86 prior to FMA requires
13250   // 15 instructions: convert to single, rcpss, convert back to double, refine
13251   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13252   // along with FMA, this could be a throughput win.
13253   if (VT == MVT::f32 && Subtarget->hasSSE1())
13254     RecipOp = "divf";
13255   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13256            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13257     RecipOp = "vec-divf";
13258   else
13259     return SDValue();
13260
13261   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13262   if (!Recips.isEnabled(RecipOp))
13263     return SDValue();
13264
13265   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13266   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13267 }
13268
13269 /// If we have at least two divisions that use the same divisor, convert to
13270 /// multplication by a reciprocal. This may need to be adjusted for a given
13271 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13272 /// This is because we still need one division to calculate the reciprocal and
13273 /// then we need two multiplies by that reciprocal as replacements for the
13274 /// original divisions.
13275 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13276   return NumUsers > 1;
13277 }
13278
13279 static bool isAllOnes(SDValue V) {
13280   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13281   return C && C->isAllOnesValue();
13282 }
13283
13284 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13285 /// if it's possible.
13286 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13287                                      SDLoc dl, SelectionDAG &DAG) const {
13288   SDValue Op0 = And.getOperand(0);
13289   SDValue Op1 = And.getOperand(1);
13290   if (Op0.getOpcode() == ISD::TRUNCATE)
13291     Op0 = Op0.getOperand(0);
13292   if (Op1.getOpcode() == ISD::TRUNCATE)
13293     Op1 = Op1.getOperand(0);
13294
13295   SDValue LHS, RHS;
13296   if (Op1.getOpcode() == ISD::SHL)
13297     std::swap(Op0, Op1);
13298   if (Op0.getOpcode() == ISD::SHL) {
13299     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13300       if (And00C->getZExtValue() == 1) {
13301         // If we looked past a truncate, check that it's only truncating away
13302         // known zeros.
13303         unsigned BitWidth = Op0.getValueSizeInBits();
13304         unsigned AndBitWidth = And.getValueSizeInBits();
13305         if (BitWidth > AndBitWidth) {
13306           APInt Zeros, Ones;
13307           DAG.computeKnownBits(Op0, Zeros, Ones);
13308           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13309             return SDValue();
13310         }
13311         LHS = Op1;
13312         RHS = Op0.getOperand(1);
13313       }
13314   } else if (Op1.getOpcode() == ISD::Constant) {
13315     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13316     uint64_t AndRHSVal = AndRHS->getZExtValue();
13317     SDValue AndLHS = Op0;
13318
13319     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13320       LHS = AndLHS.getOperand(0);
13321       RHS = AndLHS.getOperand(1);
13322     }
13323
13324     // Use BT if the immediate can't be encoded in a TEST instruction.
13325     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13326       LHS = AndLHS;
13327       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13328     }
13329   }
13330
13331   if (LHS.getNode()) {
13332     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13333     // instruction.  Since the shift amount is in-range-or-undefined, we know
13334     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13335     // the encoding for the i16 version is larger than the i32 version.
13336     // Also promote i16 to i32 for performance / code size reason.
13337     if (LHS.getValueType() == MVT::i8 ||
13338         LHS.getValueType() == MVT::i16)
13339       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13340
13341     // If the operand types disagree, extend the shift amount to match.  Since
13342     // BT ignores high bits (like shifts) we can use anyextend.
13343     if (LHS.getValueType() != RHS.getValueType())
13344       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13345
13346     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13347     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13348     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13349                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13350   }
13351
13352   return SDValue();
13353 }
13354
13355 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13356 /// mask CMPs.
13357 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13358                               SDValue &Op1) {
13359   unsigned SSECC;
13360   bool Swap = false;
13361
13362   // SSE Condition code mapping:
13363   //  0 - EQ
13364   //  1 - LT
13365   //  2 - LE
13366   //  3 - UNORD
13367   //  4 - NEQ
13368   //  5 - NLT
13369   //  6 - NLE
13370   //  7 - ORD
13371   switch (SetCCOpcode) {
13372   default: llvm_unreachable("Unexpected SETCC condition");
13373   case ISD::SETOEQ:
13374   case ISD::SETEQ:  SSECC = 0; break;
13375   case ISD::SETOGT:
13376   case ISD::SETGT:  Swap = true; // Fallthrough
13377   case ISD::SETLT:
13378   case ISD::SETOLT: SSECC = 1; break;
13379   case ISD::SETOGE:
13380   case ISD::SETGE:  Swap = true; // Fallthrough
13381   case ISD::SETLE:
13382   case ISD::SETOLE: SSECC = 2; break;
13383   case ISD::SETUO:  SSECC = 3; break;
13384   case ISD::SETUNE:
13385   case ISD::SETNE:  SSECC = 4; break;
13386   case ISD::SETULE: Swap = true; // Fallthrough
13387   case ISD::SETUGE: SSECC = 5; break;
13388   case ISD::SETULT: Swap = true; // Fallthrough
13389   case ISD::SETUGT: SSECC = 6; break;
13390   case ISD::SETO:   SSECC = 7; break;
13391   case ISD::SETUEQ:
13392   case ISD::SETONE: SSECC = 8; break;
13393   }
13394   if (Swap)
13395     std::swap(Op0, Op1);
13396
13397   return SSECC;
13398 }
13399
13400 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13401 // ones, and then concatenate the result back.
13402 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13403   MVT VT = Op.getSimpleValueType();
13404
13405   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13406          "Unsupported value type for operation");
13407
13408   unsigned NumElems = VT.getVectorNumElements();
13409   SDLoc dl(Op);
13410   SDValue CC = Op.getOperand(2);
13411
13412   // Extract the LHS vectors
13413   SDValue LHS = Op.getOperand(0);
13414   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13415   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13416
13417   // Extract the RHS vectors
13418   SDValue RHS = Op.getOperand(1);
13419   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13420   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13421
13422   // Issue the operation on the smaller types and concatenate the result back
13423   MVT EltVT = VT.getVectorElementType();
13424   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13425   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13426                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13427                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13428 }
13429
13430 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13431   SDValue Op0 = Op.getOperand(0);
13432   SDValue Op1 = Op.getOperand(1);
13433   SDValue CC = Op.getOperand(2);
13434   MVT VT = Op.getSimpleValueType();
13435   SDLoc dl(Op);
13436
13437   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13438          "Unexpected type for boolean compare operation");
13439   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13440   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13441                                DAG.getConstant(-1, dl, VT));
13442   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13443                                DAG.getConstant(-1, dl, VT));
13444   switch (SetCCOpcode) {
13445   default: llvm_unreachable("Unexpected SETCC condition");
13446   case ISD::SETEQ:
13447     // (x == y) -> ~(x ^ y)
13448     return DAG.getNode(ISD::XOR, dl, VT,
13449                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13450                        DAG.getConstant(-1, dl, VT));
13451   case ISD::SETNE:
13452     // (x != y) -> (x ^ y)
13453     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13454   case ISD::SETUGT:
13455   case ISD::SETGT:
13456     // (x > y) -> (x & ~y)
13457     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13458   case ISD::SETULT:
13459   case ISD::SETLT:
13460     // (x < y) -> (~x & y)
13461     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13462   case ISD::SETULE:
13463   case ISD::SETLE:
13464     // (x <= y) -> (~x | y)
13465     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13466   case ISD::SETUGE:
13467   case ISD::SETGE:
13468     // (x >=y) -> (x | ~y)
13469     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13470   }
13471 }
13472
13473 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13474                                      const X86Subtarget *Subtarget) {
13475   SDValue Op0 = Op.getOperand(0);
13476   SDValue Op1 = Op.getOperand(1);
13477   SDValue CC = Op.getOperand(2);
13478   MVT VT = Op.getSimpleValueType();
13479   SDLoc dl(Op);
13480
13481   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13482          Op.getValueType().getScalarType() == MVT::i1 &&
13483          "Cannot set masked compare for this operation");
13484
13485   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13486   unsigned  Opc = 0;
13487   bool Unsigned = false;
13488   bool Swap = false;
13489   unsigned SSECC;
13490   switch (SetCCOpcode) {
13491   default: llvm_unreachable("Unexpected SETCC condition");
13492   case ISD::SETNE:  SSECC = 4; break;
13493   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13494   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13495   case ISD::SETLT:  Swap = true; //fall-through
13496   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13497   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13498   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13499   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13500   case ISD::SETULE: Unsigned = true; //fall-through
13501   case ISD::SETLE:  SSECC = 2; break;
13502   }
13503
13504   if (Swap)
13505     std::swap(Op0, Op1);
13506   if (Opc)
13507     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13508   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13509   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13510                      DAG.getConstant(SSECC, dl, MVT::i8));
13511 }
13512
13513 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13514 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13515 /// return an empty value.
13516 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13517 {
13518   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13519   if (!BV)
13520     return SDValue();
13521
13522   MVT VT = Op1.getSimpleValueType();
13523   MVT EVT = VT.getVectorElementType();
13524   unsigned n = VT.getVectorNumElements();
13525   SmallVector<SDValue, 8> ULTOp1;
13526
13527   for (unsigned i = 0; i < n; ++i) {
13528     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13529     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13530       return SDValue();
13531
13532     // Avoid underflow.
13533     APInt Val = Elt->getAPIntValue();
13534     if (Val == 0)
13535       return SDValue();
13536
13537     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13538   }
13539
13540   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13541 }
13542
13543 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13544                            SelectionDAG &DAG) {
13545   SDValue Op0 = Op.getOperand(0);
13546   SDValue Op1 = Op.getOperand(1);
13547   SDValue CC = Op.getOperand(2);
13548   MVT VT = Op.getSimpleValueType();
13549   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13550   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13551   SDLoc dl(Op);
13552
13553   if (isFP) {
13554 #ifndef NDEBUG
13555     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13556     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13557 #endif
13558
13559     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13560     unsigned Opc = X86ISD::CMPP;
13561     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13562       assert(VT.getVectorNumElements() <= 16);
13563       Opc = X86ISD::CMPM;
13564     }
13565     // In the two special cases we can't handle, emit two comparisons.
13566     if (SSECC == 8) {
13567       unsigned CC0, CC1;
13568       unsigned CombineOpc;
13569       if (SetCCOpcode == ISD::SETUEQ) {
13570         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13571       } else {
13572         assert(SetCCOpcode == ISD::SETONE);
13573         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13574       }
13575
13576       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13577                                  DAG.getConstant(CC0, dl, MVT::i8));
13578       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13579                                  DAG.getConstant(CC1, dl, MVT::i8));
13580       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13581     }
13582     // Handle all other FP comparisons here.
13583     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13584                        DAG.getConstant(SSECC, dl, MVT::i8));
13585   }
13586
13587   // Break 256-bit integer vector compare into smaller ones.
13588   if (VT.is256BitVector() && !Subtarget->hasInt256())
13589     return Lower256IntVSETCC(Op, DAG);
13590
13591   EVT OpVT = Op1.getValueType();
13592   if (OpVT.getVectorElementType() == MVT::i1)
13593     return LowerBoolVSETCC_AVX512(Op, DAG);
13594
13595   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13596   if (Subtarget->hasAVX512()) {
13597     if (Op1.getValueType().is512BitVector() ||
13598         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13599         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13600       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13601
13602     // In AVX-512 architecture setcc returns mask with i1 elements,
13603     // But there is no compare instruction for i8 and i16 elements in KNL.
13604     // We are not talking about 512-bit operands in this case, these
13605     // types are illegal.
13606     if (MaskResult &&
13607         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13608          OpVT.getVectorElementType().getSizeInBits() >= 8))
13609       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13610                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13611   }
13612
13613   // We are handling one of the integer comparisons here.  Since SSE only has
13614   // GT and EQ comparisons for integer, swapping operands and multiple
13615   // operations may be required for some comparisons.
13616   unsigned Opc;
13617   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13618   bool Subus = false;
13619
13620   switch (SetCCOpcode) {
13621   default: llvm_unreachable("Unexpected SETCC condition");
13622   case ISD::SETNE:  Invert = true;
13623   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13624   case ISD::SETLT:  Swap = true;
13625   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13626   case ISD::SETGE:  Swap = true;
13627   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13628                     Invert = true; break;
13629   case ISD::SETULT: Swap = true;
13630   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13631                     FlipSigns = true; break;
13632   case ISD::SETUGE: Swap = true;
13633   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13634                     FlipSigns = true; Invert = true; break;
13635   }
13636
13637   // Special case: Use min/max operations for SETULE/SETUGE
13638   MVT VET = VT.getVectorElementType();
13639   bool hasMinMax =
13640        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13641     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13642
13643   if (hasMinMax) {
13644     switch (SetCCOpcode) {
13645     default: break;
13646     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13647     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13648     }
13649
13650     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13651   }
13652
13653   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13654   if (!MinMax && hasSubus) {
13655     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13656     // Op0 u<= Op1:
13657     //   t = psubus Op0, Op1
13658     //   pcmpeq t, <0..0>
13659     switch (SetCCOpcode) {
13660     default: break;
13661     case ISD::SETULT: {
13662       // If the comparison is against a constant we can turn this into a
13663       // setule.  With psubus, setule does not require a swap.  This is
13664       // beneficial because the constant in the register is no longer
13665       // destructed as the destination so it can be hoisted out of a loop.
13666       // Only do this pre-AVX since vpcmp* is no longer destructive.
13667       if (Subtarget->hasAVX())
13668         break;
13669       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13670       if (ULEOp1.getNode()) {
13671         Op1 = ULEOp1;
13672         Subus = true; Invert = false; Swap = false;
13673       }
13674       break;
13675     }
13676     // Psubus is better than flip-sign because it requires no inversion.
13677     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13678     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13679     }
13680
13681     if (Subus) {
13682       Opc = X86ISD::SUBUS;
13683       FlipSigns = false;
13684     }
13685   }
13686
13687   if (Swap)
13688     std::swap(Op0, Op1);
13689
13690   // Check that the operation in question is available (most are plain SSE2,
13691   // but PCMPGTQ and PCMPEQQ have different requirements).
13692   if (VT == MVT::v2i64) {
13693     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13694       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13695
13696       // First cast everything to the right type.
13697       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13698       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13699
13700       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13701       // bits of the inputs before performing those operations. The lower
13702       // compare is always unsigned.
13703       SDValue SB;
13704       if (FlipSigns) {
13705         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13706       } else {
13707         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13708         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13709         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13710                          Sign, Zero, Sign, Zero);
13711       }
13712       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13713       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13714
13715       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13716       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13717       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13718
13719       // Create masks for only the low parts/high parts of the 64 bit integers.
13720       static const int MaskHi[] = { 1, 1, 3, 3 };
13721       static const int MaskLo[] = { 0, 0, 2, 2 };
13722       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13723       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13724       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13725
13726       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13727       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13728
13729       if (Invert)
13730         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13731
13732       return DAG.getBitcast(VT, Result);
13733     }
13734
13735     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13736       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13737       // pcmpeqd + pshufd + pand.
13738       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13739
13740       // First cast everything to the right type.
13741       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13742       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13743
13744       // Do the compare.
13745       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13746
13747       // Make sure the lower and upper halves are both all-ones.
13748       static const int Mask[] = { 1, 0, 3, 2 };
13749       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13750       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13751
13752       if (Invert)
13753         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13754
13755       return DAG.getBitcast(VT, Result);
13756     }
13757   }
13758
13759   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13760   // bits of the inputs before performing those operations.
13761   if (FlipSigns) {
13762     EVT EltVT = VT.getVectorElementType();
13763     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13764                                  VT);
13765     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13766     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13767   }
13768
13769   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13770
13771   // If the logical-not of the result is required, perform that now.
13772   if (Invert)
13773     Result = DAG.getNOT(dl, Result, VT);
13774
13775   if (MinMax)
13776     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13777
13778   if (Subus)
13779     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13780                          getZeroVector(VT, Subtarget, DAG, dl));
13781
13782   return Result;
13783 }
13784
13785 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13786
13787   MVT VT = Op.getSimpleValueType();
13788
13789   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13790
13791   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13792          && "SetCC type must be 8-bit or 1-bit integer");
13793   SDValue Op0 = Op.getOperand(0);
13794   SDValue Op1 = Op.getOperand(1);
13795   SDLoc dl(Op);
13796   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13797
13798   // Optimize to BT if possible.
13799   // Lower (X & (1 << N)) == 0 to BT(X, N).
13800   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13801   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13802   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13803       Op1.getOpcode() == ISD::Constant &&
13804       cast<ConstantSDNode>(Op1)->isNullValue() &&
13805       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13806     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13807     if (NewSetCC.getNode()) {
13808       if (VT == MVT::i1)
13809         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13810       return NewSetCC;
13811     }
13812   }
13813
13814   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13815   // these.
13816   if (Op1.getOpcode() == ISD::Constant &&
13817       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13818        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13819       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13820
13821     // If the input is a setcc, then reuse the input setcc or use a new one with
13822     // the inverted condition.
13823     if (Op0.getOpcode() == X86ISD::SETCC) {
13824       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13825       bool Invert = (CC == ISD::SETNE) ^
13826         cast<ConstantSDNode>(Op1)->isNullValue();
13827       if (!Invert)
13828         return Op0;
13829
13830       CCode = X86::GetOppositeBranchCondition(CCode);
13831       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13832                                   DAG.getConstant(CCode, dl, MVT::i8),
13833                                   Op0.getOperand(1));
13834       if (VT == MVT::i1)
13835         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13836       return SetCC;
13837     }
13838   }
13839   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13840       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13841       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13842
13843     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13844     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13845   }
13846
13847   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13848   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13849   if (X86CC == X86::COND_INVALID)
13850     return SDValue();
13851
13852   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13853   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13854   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13855                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13856   if (VT == MVT::i1)
13857     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13858   return SetCC;
13859 }
13860
13861 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13862 static bool isX86LogicalCmp(SDValue Op) {
13863   unsigned Opc = Op.getNode()->getOpcode();
13864   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13865       Opc == X86ISD::SAHF)
13866     return true;
13867   if (Op.getResNo() == 1 &&
13868       (Opc == X86ISD::ADD ||
13869        Opc == X86ISD::SUB ||
13870        Opc == X86ISD::ADC ||
13871        Opc == X86ISD::SBB ||
13872        Opc == X86ISD::SMUL ||
13873        Opc == X86ISD::UMUL ||
13874        Opc == X86ISD::INC ||
13875        Opc == X86ISD::DEC ||
13876        Opc == X86ISD::OR ||
13877        Opc == X86ISD::XOR ||
13878        Opc == X86ISD::AND))
13879     return true;
13880
13881   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13882     return true;
13883
13884   return false;
13885 }
13886
13887 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13888   if (V.getOpcode() != ISD::TRUNCATE)
13889     return false;
13890
13891   SDValue VOp0 = V.getOperand(0);
13892   unsigned InBits = VOp0.getValueSizeInBits();
13893   unsigned Bits = V.getValueSizeInBits();
13894   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13895 }
13896
13897 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13898   bool addTest = true;
13899   SDValue Cond  = Op.getOperand(0);
13900   SDValue Op1 = Op.getOperand(1);
13901   SDValue Op2 = Op.getOperand(2);
13902   SDLoc DL(Op);
13903   EVT VT = Op1.getValueType();
13904   SDValue CC;
13905
13906   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13907   // are available or VBLENDV if AVX is available.
13908   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13909   if (Cond.getOpcode() == ISD::SETCC &&
13910       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13911        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13912       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13913     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13914     int SSECC = translateX86FSETCC(
13915         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13916
13917     if (SSECC != 8) {
13918       if (Subtarget->hasAVX512()) {
13919         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13920                                   DAG.getConstant(SSECC, DL, MVT::i8));
13921         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13922       }
13923
13924       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13925                                 DAG.getConstant(SSECC, DL, MVT::i8));
13926
13927       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13928       // of 3 logic instructions for size savings and potentially speed.
13929       // Unfortunately, there is no scalar form of VBLENDV.
13930
13931       // If either operand is a constant, don't try this. We can expect to
13932       // optimize away at least one of the logic instructions later in that
13933       // case, so that sequence would be faster than a variable blend.
13934
13935       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13936       // uses XMM0 as the selection register. That may need just as many
13937       // instructions as the AND/ANDN/OR sequence due to register moves, so
13938       // don't bother.
13939
13940       if (Subtarget->hasAVX() &&
13941           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13942
13943         // Convert to vectors, do a VSELECT, and convert back to scalar.
13944         // All of the conversions should be optimized away.
13945
13946         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13947         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13948         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13949         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13950
13951         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13952         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13953
13954         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13955
13956         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13957                            VSel, DAG.getIntPtrConstant(0, DL));
13958       }
13959       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13960       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13961       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13962     }
13963   }
13964
13965     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13966       SDValue Op1Scalar;
13967       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13968         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13969       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13970         Op1Scalar = Op1.getOperand(0);
13971       SDValue Op2Scalar;
13972       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13973         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13974       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13975         Op2Scalar = Op2.getOperand(0);
13976       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13977         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13978                                         Op1Scalar.getValueType(),
13979                                         Cond, Op1Scalar, Op2Scalar);
13980         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13981           return DAG.getBitcast(VT, newSelect);
13982         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13983         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13984                            DAG.getIntPtrConstant(0, DL));
13985     }
13986   }
13987
13988   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13989     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13990     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13991                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13992     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13993                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13994     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13995                                     Cond, Op1, Op2);
13996     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13997   }
13998
13999   if (Cond.getOpcode() == ISD::SETCC) {
14000     SDValue NewCond = LowerSETCC(Cond, DAG);
14001     if (NewCond.getNode())
14002       Cond = NewCond;
14003   }
14004
14005   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14006   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14007   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14008   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14009   if (Cond.getOpcode() == X86ISD::SETCC &&
14010       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14011       isZero(Cond.getOperand(1).getOperand(1))) {
14012     SDValue Cmp = Cond.getOperand(1);
14013
14014     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14015
14016     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14017         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14018       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14019
14020       SDValue CmpOp0 = Cmp.getOperand(0);
14021       // Apply further optimizations for special cases
14022       // (select (x != 0), -1, 0) -> neg & sbb
14023       // (select (x == 0), 0, -1) -> neg & sbb
14024       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14025         if (YC->isNullValue() &&
14026             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14027           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14028           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14029                                     DAG.getConstant(0, DL,
14030                                                     CmpOp0.getValueType()),
14031                                     CmpOp0);
14032           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14033                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14034                                     SDValue(Neg.getNode(), 1));
14035           return Res;
14036         }
14037
14038       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14039                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14040       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14041
14042       SDValue Res =   // Res = 0 or -1.
14043         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14044                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14045
14046       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14047         Res = DAG.getNOT(DL, Res, Res.getValueType());
14048
14049       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14050       if (!N2C || !N2C->isNullValue())
14051         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14052       return Res;
14053     }
14054   }
14055
14056   // Look past (and (setcc_carry (cmp ...)), 1).
14057   if (Cond.getOpcode() == ISD::AND &&
14058       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14059     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14060     if (C && C->getAPIntValue() == 1)
14061       Cond = Cond.getOperand(0);
14062   }
14063
14064   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14065   // setting operand in place of the X86ISD::SETCC.
14066   unsigned CondOpcode = Cond.getOpcode();
14067   if (CondOpcode == X86ISD::SETCC ||
14068       CondOpcode == X86ISD::SETCC_CARRY) {
14069     CC = Cond.getOperand(0);
14070
14071     SDValue Cmp = Cond.getOperand(1);
14072     unsigned Opc = Cmp.getOpcode();
14073     MVT VT = Op.getSimpleValueType();
14074
14075     bool IllegalFPCMov = false;
14076     if (VT.isFloatingPoint() && !VT.isVector() &&
14077         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14078       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14079
14080     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14081         Opc == X86ISD::BT) { // FIXME
14082       Cond = Cmp;
14083       addTest = false;
14084     }
14085   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14086              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14087              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14088               Cond.getOperand(0).getValueType() != MVT::i8)) {
14089     SDValue LHS = Cond.getOperand(0);
14090     SDValue RHS = Cond.getOperand(1);
14091     unsigned X86Opcode;
14092     unsigned X86Cond;
14093     SDVTList VTs;
14094     switch (CondOpcode) {
14095     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14096     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14097     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14098     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14099     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14100     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14101     default: llvm_unreachable("unexpected overflowing operator");
14102     }
14103     if (CondOpcode == ISD::UMULO)
14104       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14105                           MVT::i32);
14106     else
14107       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14108
14109     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14110
14111     if (CondOpcode == ISD::UMULO)
14112       Cond = X86Op.getValue(2);
14113     else
14114       Cond = X86Op.getValue(1);
14115
14116     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14117     addTest = false;
14118   }
14119
14120   if (addTest) {
14121     // Look pass the truncate if the high bits are known zero.
14122     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14123         Cond = Cond.getOperand(0);
14124
14125     // We know the result of AND is compared against zero. Try to match
14126     // it to BT.
14127     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14128       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14129       if (NewSetCC.getNode()) {
14130         CC = NewSetCC.getOperand(0);
14131         Cond = NewSetCC.getOperand(1);
14132         addTest = false;
14133       }
14134     }
14135   }
14136
14137   if (addTest) {
14138     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14139     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14140   }
14141
14142   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14143   // a <  b ?  0 : -1 -> RES = setcc_carry
14144   // a >= b ? -1 :  0 -> RES = setcc_carry
14145   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14146   if (Cond.getOpcode() == X86ISD::SUB) {
14147     Cond = ConvertCmpIfNecessary(Cond, DAG);
14148     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14149
14150     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14151         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14152       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14153                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14154                                 Cond);
14155       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14156         return DAG.getNOT(DL, Res, Res.getValueType());
14157       return Res;
14158     }
14159   }
14160
14161   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14162   // widen the cmov and push the truncate through. This avoids introducing a new
14163   // branch during isel and doesn't add any extensions.
14164   if (Op.getValueType() == MVT::i8 &&
14165       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14166     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14167     if (T1.getValueType() == T2.getValueType() &&
14168         // Blacklist CopyFromReg to avoid partial register stalls.
14169         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14170       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14171       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14172       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14173     }
14174   }
14175
14176   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14177   // condition is true.
14178   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14179   SDValue Ops[] = { Op2, Op1, CC, Cond };
14180   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14181 }
14182
14183 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14184                                        const X86Subtarget *Subtarget,
14185                                        SelectionDAG &DAG) {
14186   MVT VT = Op->getSimpleValueType(0);
14187   SDValue In = Op->getOperand(0);
14188   MVT InVT = In.getSimpleValueType();
14189   MVT VTElt = VT.getVectorElementType();
14190   MVT InVTElt = InVT.getVectorElementType();
14191   SDLoc dl(Op);
14192
14193   // SKX processor
14194   if ((InVTElt == MVT::i1) &&
14195       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14196         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14197
14198        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14199         VTElt.getSizeInBits() <= 16)) ||
14200
14201        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14202         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14203
14204        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14205         VTElt.getSizeInBits() >= 32))))
14206     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14207
14208   unsigned int NumElts = VT.getVectorNumElements();
14209
14210   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14211     return SDValue();
14212
14213   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14214     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14215       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14216     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14217   }
14218
14219   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14220   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14221   SDValue NegOne =
14222    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14223                    ExtVT);
14224   SDValue Zero =
14225    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14226
14227   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14228   if (VT.is512BitVector())
14229     return V;
14230   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14231 }
14232
14233 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14234                                              const X86Subtarget *Subtarget,
14235                                              SelectionDAG &DAG) {
14236   SDValue In = Op->getOperand(0);
14237   MVT VT = Op->getSimpleValueType(0);
14238   MVT InVT = In.getSimpleValueType();
14239   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14240
14241   MVT InSVT = InVT.getScalarType();
14242   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14243
14244   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14245     return SDValue();
14246   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14247     return SDValue();
14248
14249   SDLoc dl(Op);
14250
14251   // SSE41 targets can use the pmovsx* instructions directly.
14252   if (Subtarget->hasSSE41())
14253     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14254
14255   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14256   SDValue Curr = In;
14257   MVT CurrVT = InVT;
14258
14259   // As SRAI is only available on i16/i32 types, we expand only up to i32
14260   // and handle i64 separately.
14261   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14262     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14263     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14264     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14265     Curr = DAG.getBitcast(CurrVT, Curr);
14266   }
14267
14268   SDValue SignExt = Curr;
14269   if (CurrVT != InVT) {
14270     unsigned SignExtShift =
14271         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14272     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14273                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14274   }
14275
14276   if (CurrVT == VT)
14277     return SignExt;
14278
14279   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14280     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14281                                DAG.getConstant(31, dl, MVT::i8));
14282     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14283     return DAG.getBitcast(VT, Ext);
14284   }
14285
14286   return SDValue();
14287 }
14288
14289 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14290                                 SelectionDAG &DAG) {
14291   MVT VT = Op->getSimpleValueType(0);
14292   SDValue In = Op->getOperand(0);
14293   MVT InVT = In.getSimpleValueType();
14294   SDLoc dl(Op);
14295
14296   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14297     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14298
14299   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14300       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14301       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14302     return SDValue();
14303
14304   if (Subtarget->hasInt256())
14305     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14306
14307   // Optimize vectors in AVX mode
14308   // Sign extend  v8i16 to v8i32 and
14309   //              v4i32 to v4i64
14310   //
14311   // Divide input vector into two parts
14312   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14313   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14314   // concat the vectors to original VT
14315
14316   unsigned NumElems = InVT.getVectorNumElements();
14317   SDValue Undef = DAG.getUNDEF(InVT);
14318
14319   SmallVector<int,8> ShufMask1(NumElems, -1);
14320   for (unsigned i = 0; i != NumElems/2; ++i)
14321     ShufMask1[i] = i;
14322
14323   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14324
14325   SmallVector<int,8> ShufMask2(NumElems, -1);
14326   for (unsigned i = 0; i != NumElems/2; ++i)
14327     ShufMask2[i] = i + NumElems/2;
14328
14329   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14330
14331   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14332                                 VT.getVectorNumElements()/2);
14333
14334   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14335   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14336
14337   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14338 }
14339
14340 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14341 // may emit an illegal shuffle but the expansion is still better than scalar
14342 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14343 // we'll emit a shuffle and a arithmetic shift.
14344 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14345 // TODO: It is possible to support ZExt by zeroing the undef values during
14346 // the shuffle phase or after the shuffle.
14347 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14348                                  SelectionDAG &DAG) {
14349   MVT RegVT = Op.getSimpleValueType();
14350   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14351   assert(RegVT.isInteger() &&
14352          "We only custom lower integer vector sext loads.");
14353
14354   // Nothing useful we can do without SSE2 shuffles.
14355   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14356
14357   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14358   SDLoc dl(Ld);
14359   EVT MemVT = Ld->getMemoryVT();
14360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14361   unsigned RegSz = RegVT.getSizeInBits();
14362
14363   ISD::LoadExtType Ext = Ld->getExtensionType();
14364
14365   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14366          && "Only anyext and sext are currently implemented.");
14367   assert(MemVT != RegVT && "Cannot extend to the same type");
14368   assert(MemVT.isVector() && "Must load a vector from memory");
14369
14370   unsigned NumElems = RegVT.getVectorNumElements();
14371   unsigned MemSz = MemVT.getSizeInBits();
14372   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14373
14374   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14375     // The only way in which we have a legal 256-bit vector result but not the
14376     // integer 256-bit operations needed to directly lower a sextload is if we
14377     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14378     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14379     // correctly legalized. We do this late to allow the canonical form of
14380     // sextload to persist throughout the rest of the DAG combiner -- it wants
14381     // to fold together any extensions it can, and so will fuse a sign_extend
14382     // of an sextload into a sextload targeting a wider value.
14383     SDValue Load;
14384     if (MemSz == 128) {
14385       // Just switch this to a normal load.
14386       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14387                                        "it must be a legal 128-bit vector "
14388                                        "type!");
14389       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14390                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14391                   Ld->isInvariant(), Ld->getAlignment());
14392     } else {
14393       assert(MemSz < 128 &&
14394              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14395       // Do an sext load to a 128-bit vector type. We want to use the same
14396       // number of elements, but elements half as wide. This will end up being
14397       // recursively lowered by this routine, but will succeed as we definitely
14398       // have all the necessary features if we're using AVX1.
14399       EVT HalfEltVT =
14400           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14401       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14402       Load =
14403           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14404                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14405                          Ld->isNonTemporal(), Ld->isInvariant(),
14406                          Ld->getAlignment());
14407     }
14408
14409     // Replace chain users with the new chain.
14410     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14411     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14412
14413     // Finally, do a normal sign-extend to the desired register.
14414     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14415   }
14416
14417   // All sizes must be a power of two.
14418   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14419          "Non-power-of-two elements are not custom lowered!");
14420
14421   // Attempt to load the original value using scalar loads.
14422   // Find the largest scalar type that divides the total loaded size.
14423   MVT SclrLoadTy = MVT::i8;
14424   for (MVT Tp : MVT::integer_valuetypes()) {
14425     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14426       SclrLoadTy = Tp;
14427     }
14428   }
14429
14430   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14431   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14432       (64 <= MemSz))
14433     SclrLoadTy = MVT::f64;
14434
14435   // Calculate the number of scalar loads that we need to perform
14436   // in order to load our vector from memory.
14437   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14438
14439   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14440          "Can only lower sext loads with a single scalar load!");
14441
14442   unsigned loadRegZize = RegSz;
14443   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14444     loadRegZize = 128;
14445
14446   // Represent our vector as a sequence of elements which are the
14447   // largest scalar that we can load.
14448   EVT LoadUnitVecVT = EVT::getVectorVT(
14449       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14450
14451   // Represent the data using the same element type that is stored in
14452   // memory. In practice, we ''widen'' MemVT.
14453   EVT WideVecVT =
14454       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14455                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14456
14457   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14458          "Invalid vector type");
14459
14460   // We can't shuffle using an illegal type.
14461   assert(TLI.isTypeLegal(WideVecVT) &&
14462          "We only lower types that form legal widened vector types");
14463
14464   SmallVector<SDValue, 8> Chains;
14465   SDValue Ptr = Ld->getBasePtr();
14466   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14467                                       TLI.getPointerTy(DAG.getDataLayout()));
14468   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14469
14470   for (unsigned i = 0; i < NumLoads; ++i) {
14471     // Perform a single load.
14472     SDValue ScalarLoad =
14473         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14474                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14475                     Ld->getAlignment());
14476     Chains.push_back(ScalarLoad.getValue(1));
14477     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14478     // another round of DAGCombining.
14479     if (i == 0)
14480       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14481     else
14482       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14483                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14484
14485     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14486   }
14487
14488   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14489
14490   // Bitcast the loaded value to a vector of the original element type, in
14491   // the size of the target vector type.
14492   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14493   unsigned SizeRatio = RegSz / MemSz;
14494
14495   if (Ext == ISD::SEXTLOAD) {
14496     // If we have SSE4.1, we can directly emit a VSEXT node.
14497     if (Subtarget->hasSSE41()) {
14498       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14499       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14500       return Sext;
14501     }
14502
14503     // Otherwise we'll shuffle the small elements in the high bits of the
14504     // larger type and perform an arithmetic shift. If the shift is not legal
14505     // it's better to scalarize.
14506     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14507            "We can't implement a sext load without an arithmetic right shift!");
14508
14509     // Redistribute the loaded elements into the different locations.
14510     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14511     for (unsigned i = 0; i != NumElems; ++i)
14512       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14513
14514     SDValue Shuff = DAG.getVectorShuffle(
14515         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14516
14517     Shuff = DAG.getBitcast(RegVT, Shuff);
14518
14519     // Build the arithmetic shift.
14520     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14521                    MemVT.getVectorElementType().getSizeInBits();
14522     Shuff =
14523         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14524                     DAG.getConstant(Amt, dl, RegVT));
14525
14526     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14527     return Shuff;
14528   }
14529
14530   // Redistribute the loaded elements into the different locations.
14531   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14532   for (unsigned i = 0; i != NumElems; ++i)
14533     ShuffleVec[i * SizeRatio] = i;
14534
14535   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14536                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14537
14538   // Bitcast to the requested type.
14539   Shuff = DAG.getBitcast(RegVT, Shuff);
14540   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14541   return Shuff;
14542 }
14543
14544 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14545 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14546 // from the AND / OR.
14547 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14548   Opc = Op.getOpcode();
14549   if (Opc != ISD::OR && Opc != ISD::AND)
14550     return false;
14551   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14552           Op.getOperand(0).hasOneUse() &&
14553           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14554           Op.getOperand(1).hasOneUse());
14555 }
14556
14557 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14558 // 1 and that the SETCC node has a single use.
14559 static bool isXor1OfSetCC(SDValue Op) {
14560   if (Op.getOpcode() != ISD::XOR)
14561     return false;
14562   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14563   if (N1C && N1C->getAPIntValue() == 1) {
14564     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14565       Op.getOperand(0).hasOneUse();
14566   }
14567   return false;
14568 }
14569
14570 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14571   bool addTest = true;
14572   SDValue Chain = Op.getOperand(0);
14573   SDValue Cond  = Op.getOperand(1);
14574   SDValue Dest  = Op.getOperand(2);
14575   SDLoc dl(Op);
14576   SDValue CC;
14577   bool Inverted = false;
14578
14579   if (Cond.getOpcode() == ISD::SETCC) {
14580     // Check for setcc([su]{add,sub,mul}o == 0).
14581     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14582         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14583         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14584         Cond.getOperand(0).getResNo() == 1 &&
14585         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14586          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14587          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14588          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14589          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14590          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14591       Inverted = true;
14592       Cond = Cond.getOperand(0);
14593     } else {
14594       SDValue NewCond = LowerSETCC(Cond, DAG);
14595       if (NewCond.getNode())
14596         Cond = NewCond;
14597     }
14598   }
14599 #if 0
14600   // FIXME: LowerXALUO doesn't handle these!!
14601   else if (Cond.getOpcode() == X86ISD::ADD  ||
14602            Cond.getOpcode() == X86ISD::SUB  ||
14603            Cond.getOpcode() == X86ISD::SMUL ||
14604            Cond.getOpcode() == X86ISD::UMUL)
14605     Cond = LowerXALUO(Cond, DAG);
14606 #endif
14607
14608   // Look pass (and (setcc_carry (cmp ...)), 1).
14609   if (Cond.getOpcode() == ISD::AND &&
14610       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14611     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14612     if (C && C->getAPIntValue() == 1)
14613       Cond = Cond.getOperand(0);
14614   }
14615
14616   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14617   // setting operand in place of the X86ISD::SETCC.
14618   unsigned CondOpcode = Cond.getOpcode();
14619   if (CondOpcode == X86ISD::SETCC ||
14620       CondOpcode == X86ISD::SETCC_CARRY) {
14621     CC = Cond.getOperand(0);
14622
14623     SDValue Cmp = Cond.getOperand(1);
14624     unsigned Opc = Cmp.getOpcode();
14625     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14626     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14627       Cond = Cmp;
14628       addTest = false;
14629     } else {
14630       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14631       default: break;
14632       case X86::COND_O:
14633       case X86::COND_B:
14634         // These can only come from an arithmetic instruction with overflow,
14635         // e.g. SADDO, UADDO.
14636         Cond = Cond.getNode()->getOperand(1);
14637         addTest = false;
14638         break;
14639       }
14640     }
14641   }
14642   CondOpcode = Cond.getOpcode();
14643   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14644       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14645       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14646        Cond.getOperand(0).getValueType() != MVT::i8)) {
14647     SDValue LHS = Cond.getOperand(0);
14648     SDValue RHS = Cond.getOperand(1);
14649     unsigned X86Opcode;
14650     unsigned X86Cond;
14651     SDVTList VTs;
14652     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14653     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14654     // X86ISD::INC).
14655     switch (CondOpcode) {
14656     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14657     case ISD::SADDO:
14658       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14659         if (C->isOne()) {
14660           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14661           break;
14662         }
14663       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14664     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14665     case ISD::SSUBO:
14666       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14667         if (C->isOne()) {
14668           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14669           break;
14670         }
14671       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14672     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14673     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14674     default: llvm_unreachable("unexpected overflowing operator");
14675     }
14676     if (Inverted)
14677       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14678     if (CondOpcode == ISD::UMULO)
14679       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14680                           MVT::i32);
14681     else
14682       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14683
14684     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14685
14686     if (CondOpcode == ISD::UMULO)
14687       Cond = X86Op.getValue(2);
14688     else
14689       Cond = X86Op.getValue(1);
14690
14691     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14692     addTest = false;
14693   } else {
14694     unsigned CondOpc;
14695     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14696       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14697       if (CondOpc == ISD::OR) {
14698         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14699         // two branches instead of an explicit OR instruction with a
14700         // separate test.
14701         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14702             isX86LogicalCmp(Cmp)) {
14703           CC = Cond.getOperand(0).getOperand(0);
14704           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14705                               Chain, Dest, CC, Cmp);
14706           CC = Cond.getOperand(1).getOperand(0);
14707           Cond = Cmp;
14708           addTest = false;
14709         }
14710       } else { // ISD::AND
14711         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14712         // two branches instead of an explicit AND instruction with a
14713         // separate test. However, we only do this if this block doesn't
14714         // have a fall-through edge, because this requires an explicit
14715         // jmp when the condition is false.
14716         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14717             isX86LogicalCmp(Cmp) &&
14718             Op.getNode()->hasOneUse()) {
14719           X86::CondCode CCode =
14720             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14721           CCode = X86::GetOppositeBranchCondition(CCode);
14722           CC = DAG.getConstant(CCode, dl, MVT::i8);
14723           SDNode *User = *Op.getNode()->use_begin();
14724           // Look for an unconditional branch following this conditional branch.
14725           // We need this because we need to reverse the successors in order
14726           // to implement FCMP_OEQ.
14727           if (User->getOpcode() == ISD::BR) {
14728             SDValue FalseBB = User->getOperand(1);
14729             SDNode *NewBR =
14730               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14731             assert(NewBR == User);
14732             (void)NewBR;
14733             Dest = FalseBB;
14734
14735             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14736                                 Chain, Dest, CC, Cmp);
14737             X86::CondCode CCode =
14738               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14739             CCode = X86::GetOppositeBranchCondition(CCode);
14740             CC = DAG.getConstant(CCode, dl, MVT::i8);
14741             Cond = Cmp;
14742             addTest = false;
14743           }
14744         }
14745       }
14746     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14747       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14748       // It should be transformed during dag combiner except when the condition
14749       // is set by a arithmetics with overflow node.
14750       X86::CondCode CCode =
14751         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14752       CCode = X86::GetOppositeBranchCondition(CCode);
14753       CC = DAG.getConstant(CCode, dl, MVT::i8);
14754       Cond = Cond.getOperand(0).getOperand(1);
14755       addTest = false;
14756     } else if (Cond.getOpcode() == ISD::SETCC &&
14757                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14758       // For FCMP_OEQ, we can emit
14759       // two branches instead of an explicit AND instruction with a
14760       // separate test. However, we only do this if this block doesn't
14761       // have a fall-through edge, because this requires an explicit
14762       // jmp when the condition is false.
14763       if (Op.getNode()->hasOneUse()) {
14764         SDNode *User = *Op.getNode()->use_begin();
14765         // Look for an unconditional branch following this conditional branch.
14766         // We need this because we need to reverse the successors in order
14767         // to implement FCMP_OEQ.
14768         if (User->getOpcode() == ISD::BR) {
14769           SDValue FalseBB = User->getOperand(1);
14770           SDNode *NewBR =
14771             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14772           assert(NewBR == User);
14773           (void)NewBR;
14774           Dest = FalseBB;
14775
14776           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14777                                     Cond.getOperand(0), Cond.getOperand(1));
14778           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14779           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14780           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14781                               Chain, Dest, CC, Cmp);
14782           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14783           Cond = Cmp;
14784           addTest = false;
14785         }
14786       }
14787     } else if (Cond.getOpcode() == ISD::SETCC &&
14788                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14789       // For FCMP_UNE, we can emit
14790       // two branches instead of an explicit AND instruction with a
14791       // separate test. However, we only do this if this block doesn't
14792       // have a fall-through edge, because this requires an explicit
14793       // jmp when the condition is false.
14794       if (Op.getNode()->hasOneUse()) {
14795         SDNode *User = *Op.getNode()->use_begin();
14796         // Look for an unconditional branch following this conditional branch.
14797         // We need this because we need to reverse the successors in order
14798         // to implement FCMP_UNE.
14799         if (User->getOpcode() == ISD::BR) {
14800           SDValue FalseBB = User->getOperand(1);
14801           SDNode *NewBR =
14802             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14803           assert(NewBR == User);
14804           (void)NewBR;
14805
14806           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14807                                     Cond.getOperand(0), Cond.getOperand(1));
14808           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14809           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14810           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14811                               Chain, Dest, CC, Cmp);
14812           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14813           Cond = Cmp;
14814           addTest = false;
14815           Dest = FalseBB;
14816         }
14817       }
14818     }
14819   }
14820
14821   if (addTest) {
14822     // Look pass the truncate if the high bits are known zero.
14823     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14824         Cond = Cond.getOperand(0);
14825
14826     // We know the result of AND is compared against zero. Try to match
14827     // it to BT.
14828     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14829       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14830       if (NewSetCC.getNode()) {
14831         CC = NewSetCC.getOperand(0);
14832         Cond = NewSetCC.getOperand(1);
14833         addTest = false;
14834       }
14835     }
14836   }
14837
14838   if (addTest) {
14839     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14840     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14841     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14842   }
14843   Cond = ConvertCmpIfNecessary(Cond, DAG);
14844   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14845                      Chain, Dest, CC, Cond);
14846 }
14847
14848 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14849 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14850 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14851 // that the guard pages used by the OS virtual memory manager are allocated in
14852 // correct sequence.
14853 SDValue
14854 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14855                                            SelectionDAG &DAG) const {
14856   MachineFunction &MF = DAG.getMachineFunction();
14857   bool SplitStack = MF.shouldSplitStack();
14858   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14859                SplitStack;
14860   SDLoc dl(Op);
14861
14862   if (!Lower) {
14863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14864     SDNode* Node = Op.getNode();
14865
14866     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14867     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14868         " not tell us which reg is the stack pointer!");
14869     EVT VT = Node->getValueType(0);
14870     SDValue Tmp1 = SDValue(Node, 0);
14871     SDValue Tmp2 = SDValue(Node, 1);
14872     SDValue Tmp3 = Node->getOperand(2);
14873     SDValue Chain = Tmp1.getOperand(0);
14874
14875     // Chain the dynamic stack allocation so that it doesn't modify the stack
14876     // pointer when other instructions are using the stack.
14877     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14878         SDLoc(Node));
14879
14880     SDValue Size = Tmp2.getOperand(1);
14881     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14882     Chain = SP.getValue(1);
14883     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14884     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14885     unsigned StackAlign = TFI.getStackAlignment();
14886     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14887     if (Align > StackAlign)
14888       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14889           DAG.getConstant(-(uint64_t)Align, dl, VT));
14890     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14891
14892     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14893         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14894         SDLoc(Node));
14895
14896     SDValue Ops[2] = { Tmp1, Tmp2 };
14897     return DAG.getMergeValues(Ops, dl);
14898   }
14899
14900   // Get the inputs.
14901   SDValue Chain = Op.getOperand(0);
14902   SDValue Size  = Op.getOperand(1);
14903   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14904   EVT VT = Op.getNode()->getValueType(0);
14905
14906   bool Is64Bit = Subtarget->is64Bit();
14907   MVT SPTy = getPointerTy(DAG.getDataLayout());
14908
14909   if (SplitStack) {
14910     MachineRegisterInfo &MRI = MF.getRegInfo();
14911
14912     if (Is64Bit) {
14913       // The 64 bit implementation of segmented stacks needs to clobber both r10
14914       // r11. This makes it impossible to use it along with nested parameters.
14915       const Function *F = MF.getFunction();
14916
14917       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14918            I != E; ++I)
14919         if (I->hasNestAttr())
14920           report_fatal_error("Cannot use segmented stacks with functions that "
14921                              "have nested arguments.");
14922     }
14923
14924     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14925     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14926     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14927     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14928                                 DAG.getRegister(Vreg, SPTy));
14929     SDValue Ops1[2] = { Value, Chain };
14930     return DAG.getMergeValues(Ops1, dl);
14931   } else {
14932     SDValue Flag;
14933     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14934
14935     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14936     Flag = Chain.getValue(1);
14937     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14938
14939     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14940
14941     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14942     unsigned SPReg = RegInfo->getStackRegister();
14943     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14944     Chain = SP.getValue(1);
14945
14946     if (Align) {
14947       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14948                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14949       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14950     }
14951
14952     SDValue Ops1[2] = { SP, Chain };
14953     return DAG.getMergeValues(Ops1, dl);
14954   }
14955 }
14956
14957 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14958   MachineFunction &MF = DAG.getMachineFunction();
14959   auto PtrVT = getPointerTy(MF.getDataLayout());
14960   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14961
14962   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14963   SDLoc DL(Op);
14964
14965   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14966     // vastart just stores the address of the VarArgsFrameIndex slot into the
14967     // memory location argument.
14968     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14969     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14970                         MachinePointerInfo(SV), false, false, 0);
14971   }
14972
14973   // __va_list_tag:
14974   //   gp_offset         (0 - 6 * 8)
14975   //   fp_offset         (48 - 48 + 8 * 16)
14976   //   overflow_arg_area (point to parameters coming in memory).
14977   //   reg_save_area
14978   SmallVector<SDValue, 8> MemOps;
14979   SDValue FIN = Op.getOperand(1);
14980   // Store gp_offset
14981   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14982                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14983                                                DL, MVT::i32),
14984                                FIN, MachinePointerInfo(SV), false, false, 0);
14985   MemOps.push_back(Store);
14986
14987   // Store fp_offset
14988   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14989   Store = DAG.getStore(Op.getOperand(0), DL,
14990                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14991                                        MVT::i32),
14992                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14993   MemOps.push_back(Store);
14994
14995   // Store ptr to overflow_arg_area
14996   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14997   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14998   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14999                        MachinePointerInfo(SV, 8),
15000                        false, false, 0);
15001   MemOps.push_back(Store);
15002
15003   // Store ptr to reg_save_area.
15004   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15005   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15006   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15007                        MachinePointerInfo(SV, 16), false, false, 0);
15008   MemOps.push_back(Store);
15009   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15010 }
15011
15012 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15013   assert(Subtarget->is64Bit() &&
15014          "LowerVAARG only handles 64-bit va_arg!");
15015   assert((Subtarget->isTargetLinux() ||
15016           Subtarget->isTargetDarwin()) &&
15017           "Unhandled target in LowerVAARG");
15018   assert(Op.getNode()->getNumOperands() == 4);
15019   SDValue Chain = Op.getOperand(0);
15020   SDValue SrcPtr = Op.getOperand(1);
15021   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15022   unsigned Align = Op.getConstantOperandVal(3);
15023   SDLoc dl(Op);
15024
15025   EVT ArgVT = Op.getNode()->getValueType(0);
15026   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15027   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15028   uint8_t ArgMode;
15029
15030   // Decide which area this value should be read from.
15031   // TODO: Implement the AMD64 ABI in its entirety. This simple
15032   // selection mechanism works only for the basic types.
15033   if (ArgVT == MVT::f80) {
15034     llvm_unreachable("va_arg for f80 not yet implemented");
15035   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15036     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15037   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15038     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15039   } else {
15040     llvm_unreachable("Unhandled argument type in LowerVAARG");
15041   }
15042
15043   if (ArgMode == 2) {
15044     // Sanity Check: Make sure using fp_offset makes sense.
15045     assert(!Subtarget->useSoftFloat() &&
15046            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15047                Attribute::NoImplicitFloat)) &&
15048            Subtarget->hasSSE1());
15049   }
15050
15051   // Insert VAARG_64 node into the DAG
15052   // VAARG_64 returns two values: Variable Argument Address, Chain
15053   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15054                        DAG.getConstant(ArgMode, dl, MVT::i8),
15055                        DAG.getConstant(Align, dl, MVT::i32)};
15056   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15057   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15058                                           VTs, InstOps, MVT::i64,
15059                                           MachinePointerInfo(SV),
15060                                           /*Align=*/0,
15061                                           /*Volatile=*/false,
15062                                           /*ReadMem=*/true,
15063                                           /*WriteMem=*/true);
15064   Chain = VAARG.getValue(1);
15065
15066   // Load the next argument and return it
15067   return DAG.getLoad(ArgVT, dl,
15068                      Chain,
15069                      VAARG,
15070                      MachinePointerInfo(),
15071                      false, false, false, 0);
15072 }
15073
15074 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15075                            SelectionDAG &DAG) {
15076   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15077   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15078   SDValue Chain = Op.getOperand(0);
15079   SDValue DstPtr = Op.getOperand(1);
15080   SDValue SrcPtr = Op.getOperand(2);
15081   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15082   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15083   SDLoc DL(Op);
15084
15085   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15086                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15087                        false, false,
15088                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15089 }
15090
15091 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15092 // amount is a constant. Takes immediate version of shift as input.
15093 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15094                                           SDValue SrcOp, uint64_t ShiftAmt,
15095                                           SelectionDAG &DAG) {
15096   MVT ElementType = VT.getVectorElementType();
15097
15098   // Fold this packed shift into its first operand if ShiftAmt is 0.
15099   if (ShiftAmt == 0)
15100     return SrcOp;
15101
15102   // Check for ShiftAmt >= element width
15103   if (ShiftAmt >= ElementType.getSizeInBits()) {
15104     if (Opc == X86ISD::VSRAI)
15105       ShiftAmt = ElementType.getSizeInBits() - 1;
15106     else
15107       return DAG.getConstant(0, dl, VT);
15108   }
15109
15110   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15111          && "Unknown target vector shift-by-constant node");
15112
15113   // Fold this packed vector shift into a build vector if SrcOp is a
15114   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15115   if (VT == SrcOp.getSimpleValueType() &&
15116       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15117     SmallVector<SDValue, 8> Elts;
15118     unsigned NumElts = SrcOp->getNumOperands();
15119     ConstantSDNode *ND;
15120
15121     switch(Opc) {
15122     default: llvm_unreachable(nullptr);
15123     case X86ISD::VSHLI:
15124       for (unsigned i=0; i!=NumElts; ++i) {
15125         SDValue CurrentOp = SrcOp->getOperand(i);
15126         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15127           Elts.push_back(CurrentOp);
15128           continue;
15129         }
15130         ND = cast<ConstantSDNode>(CurrentOp);
15131         const APInt &C = ND->getAPIntValue();
15132         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15133       }
15134       break;
15135     case X86ISD::VSRLI:
15136       for (unsigned i=0; i!=NumElts; ++i) {
15137         SDValue CurrentOp = SrcOp->getOperand(i);
15138         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15139           Elts.push_back(CurrentOp);
15140           continue;
15141         }
15142         ND = cast<ConstantSDNode>(CurrentOp);
15143         const APInt &C = ND->getAPIntValue();
15144         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15145       }
15146       break;
15147     case X86ISD::VSRAI:
15148       for (unsigned i=0; i!=NumElts; ++i) {
15149         SDValue CurrentOp = SrcOp->getOperand(i);
15150         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15151           Elts.push_back(CurrentOp);
15152           continue;
15153         }
15154         ND = cast<ConstantSDNode>(CurrentOp);
15155         const APInt &C = ND->getAPIntValue();
15156         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15157       }
15158       break;
15159     }
15160
15161     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15162   }
15163
15164   return DAG.getNode(Opc, dl, VT, SrcOp,
15165                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15166 }
15167
15168 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15169 // may or may not be a constant. Takes immediate version of shift as input.
15170 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15171                                    SDValue SrcOp, SDValue ShAmt,
15172                                    SelectionDAG &DAG) {
15173   MVT SVT = ShAmt.getSimpleValueType();
15174   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15175
15176   // Catch shift-by-constant.
15177   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15178     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15179                                       CShAmt->getZExtValue(), DAG);
15180
15181   // Change opcode to non-immediate version
15182   switch (Opc) {
15183     default: llvm_unreachable("Unknown target vector shift node");
15184     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15185     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15186     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15187   }
15188
15189   const X86Subtarget &Subtarget =
15190       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15191   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15192       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15193     // Let the shuffle legalizer expand this shift amount node.
15194     SDValue Op0 = ShAmt.getOperand(0);
15195     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15196     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15197   } else {
15198     // Need to build a vector containing shift amount.
15199     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15200     SmallVector<SDValue, 4> ShOps;
15201     ShOps.push_back(ShAmt);
15202     if (SVT == MVT::i32) {
15203       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15204       ShOps.push_back(DAG.getUNDEF(SVT));
15205     }
15206     ShOps.push_back(DAG.getUNDEF(SVT));
15207
15208     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15209     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15210   }
15211
15212   // The return type has to be a 128-bit type with the same element
15213   // type as the input type.
15214   MVT EltVT = VT.getVectorElementType();
15215   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15216
15217   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15218   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15219 }
15220
15221 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15222 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15223 /// necessary casting for \p Mask when lowering masking intrinsics.
15224 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15225                                     SDValue PreservedSrc,
15226                                     const X86Subtarget *Subtarget,
15227                                     SelectionDAG &DAG) {
15228     EVT VT = Op.getValueType();
15229     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15230                                   MVT::i1, VT.getVectorNumElements());
15231     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15232                                      Mask.getValueType().getSizeInBits());
15233     SDLoc dl(Op);
15234
15235     assert(MaskVT.isSimple() && "invalid mask type");
15236
15237     if (isAllOnes(Mask))
15238       return Op;
15239
15240     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15241     // are extracted by EXTRACT_SUBVECTOR.
15242     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15243                                 DAG.getBitcast(BitcastVT, Mask),
15244                                 DAG.getIntPtrConstant(0, dl));
15245
15246     switch (Op.getOpcode()) {
15247       default: break;
15248       case X86ISD::PCMPEQM:
15249       case X86ISD::PCMPGTM:
15250       case X86ISD::CMPM:
15251       case X86ISD::CMPMU:
15252         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15253     }
15254     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15255       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15256     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15257 }
15258
15259 /// \brief Creates an SDNode for a predicated scalar operation.
15260 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15261 /// The mask is comming as MVT::i8 and it should be truncated
15262 /// to MVT::i1 while lowering masking intrinsics.
15263 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15264 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15265 /// a scalar instruction.
15266 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15267                                     SDValue PreservedSrc,
15268                                     const X86Subtarget *Subtarget,
15269                                     SelectionDAG &DAG) {
15270     if (isAllOnes(Mask))
15271       return Op;
15272
15273     EVT VT = Op.getValueType();
15274     SDLoc dl(Op);
15275     // The mask should be of type MVT::i1
15276     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15277
15278     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15279       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15280     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15281 }
15282
15283 static int getSEHRegistrationNodeSize(const Function *Fn) {
15284   if (!Fn->hasPersonalityFn())
15285     report_fatal_error(
15286         "querying registration node size for function without personality");
15287   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15288   // WinEHStatePass for the full struct definition.
15289   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15290   case EHPersonality::MSVC_X86SEH: return 24;
15291   case EHPersonality::MSVC_CXX: return 16;
15292   default: break;
15293   }
15294   report_fatal_error("can only recover FP for MSVC EH personality functions");
15295 }
15296
15297 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15298 /// function or when returning to a parent frame after catching an exception, we
15299 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15300 /// Here's the math:
15301 ///   RegNodeBase = EntryEBP - RegNodeSize
15302 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15303 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15304 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15305 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15306                                    SDValue EntryEBP) {
15307   MachineFunction &MF = DAG.getMachineFunction();
15308   SDLoc dl;
15309
15310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15311   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15312
15313   // It's possible that the parent function no longer has a personality function
15314   // if the exceptional code was optimized away, in which case we just return
15315   // the incoming EBP.
15316   if (!Fn->hasPersonalityFn())
15317     return EntryEBP;
15318
15319   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15320
15321   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15322   // registration.
15323   MCSymbol *OffsetSym =
15324       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15325           GlobalValue::getRealLinkageName(Fn->getName()));
15326   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15327   SDValue RegNodeFrameOffset =
15328       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15329
15330   // RegNodeBase = EntryEBP - RegNodeSize
15331   // ParentFP = RegNodeBase - RegNodeFrameOffset
15332   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15333                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15334   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15335 }
15336
15337 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15338                                        SelectionDAG &DAG) {
15339   SDLoc dl(Op);
15340   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15341   EVT VT = Op.getValueType();
15342   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15343   if (IntrData) {
15344     switch(IntrData->Type) {
15345     case INTR_TYPE_1OP:
15346       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15347     case INTR_TYPE_2OP:
15348       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15349         Op.getOperand(2));
15350     case INTR_TYPE_3OP:
15351       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15352         Op.getOperand(2), Op.getOperand(3));
15353     case INTR_TYPE_4OP:
15354       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15355         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15356     case INTR_TYPE_1OP_MASK_RM: {
15357       SDValue Src = Op.getOperand(1);
15358       SDValue PassThru = Op.getOperand(2);
15359       SDValue Mask = Op.getOperand(3);
15360       SDValue RoundingMode;
15361       // We allways add rounding mode to the Node.
15362       // If the rounding mode is not specified, we add the 
15363       // "current direction" mode.
15364       if (Op.getNumOperands() == 4)
15365         RoundingMode =
15366           DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15367       else
15368         RoundingMode = Op.getOperand(4);
15369       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15370       if (IntrWithRoundingModeOpcode != 0)
15371         if (cast<ConstantSDNode>(RoundingMode)->getZExtValue() !=
15372             X86::STATIC_ROUNDING::CUR_DIRECTION)
15373           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15374                                       dl, Op.getValueType(), Src, RoundingMode),
15375                                       Mask, PassThru, Subtarget, DAG);
15376       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15377                                               RoundingMode),
15378                                   Mask, PassThru, Subtarget, DAG);
15379     }
15380     case INTR_TYPE_1OP_MASK: {
15381       SDValue Src = Op.getOperand(1);
15382       SDValue PassThru = Op.getOperand(2);
15383       SDValue Mask = Op.getOperand(3);
15384       // We add rounding mode to the Node when
15385       //   - RM Opcode is specified and
15386       //   - RM is not "current direction".
15387       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15388       if (IntrWithRoundingModeOpcode != 0) {
15389         SDValue Rnd = Op.getOperand(4);
15390         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15391         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15392           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15393                                       dl, Op.getValueType(),
15394                                       Src, Rnd),
15395                                       Mask, PassThru, Subtarget, DAG);
15396         }
15397       }
15398       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15399                                   Mask, PassThru, Subtarget, DAG);
15400     }
15401     case INTR_TYPE_SCALAR_MASK_RM: {
15402       SDValue Src1 = Op.getOperand(1);
15403       SDValue Src2 = Op.getOperand(2);
15404       SDValue Src0 = Op.getOperand(3);
15405       SDValue Mask = Op.getOperand(4);
15406       // There are 2 kinds of intrinsics in this group:
15407       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15408       // (2) With rounding mode and sae - 7 operands.
15409       if (Op.getNumOperands() == 6) {
15410         SDValue Sae  = Op.getOperand(5);
15411         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15412         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15413                                                 Sae),
15414                                     Mask, Src0, Subtarget, DAG);
15415       }
15416       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15417       SDValue RoundingMode  = Op.getOperand(5);
15418       SDValue Sae  = Op.getOperand(6);
15419       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15420                                               RoundingMode, Sae),
15421                                   Mask, Src0, Subtarget, DAG);
15422     }
15423     case INTR_TYPE_2OP_MASK: {
15424       SDValue Src1 = Op.getOperand(1);
15425       SDValue Src2 = Op.getOperand(2);
15426       SDValue PassThru = Op.getOperand(3);
15427       SDValue Mask = Op.getOperand(4);
15428       // We specify 2 possible opcodes for intrinsics with rounding modes.
15429       // First, we check if the intrinsic may have non-default rounding mode,
15430       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15431       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15432       if (IntrWithRoundingModeOpcode != 0) {
15433         SDValue Rnd = Op.getOperand(5);
15434         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15435         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15436           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15437                                       dl, Op.getValueType(),
15438                                       Src1, Src2, Rnd),
15439                                       Mask, PassThru, Subtarget, DAG);
15440         }
15441       }
15442       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15443                                               Src1,Src2),
15444                                   Mask, PassThru, Subtarget, DAG);
15445     }
15446     case INTR_TYPE_2OP_MASK_RM: {
15447       SDValue Src1 = Op.getOperand(1);
15448       SDValue Src2 = Op.getOperand(2);
15449       SDValue PassThru = Op.getOperand(3);
15450       SDValue Mask = Op.getOperand(4);
15451       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15452       // First, we check if the intrinsic have rounding mode (6 operands),
15453       // if not, we set rounding mode to "current".
15454       SDValue Rnd;
15455       if (Op.getNumOperands() == 6)
15456         Rnd = Op.getOperand(5);
15457       else
15458         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15459       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15460                                               Src1, Src2, Rnd),
15461                                   Mask, PassThru, Subtarget, DAG);
15462     }
15463     case INTR_TYPE_3OP_MASK_RM: {
15464       SDValue Src1 = Op.getOperand(1);
15465       SDValue Src2 = Op.getOperand(2);
15466       SDValue Imm = Op.getOperand(3);
15467       SDValue PassThru = Op.getOperand(4);
15468       SDValue Mask = Op.getOperand(5);
15469       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15470       // First, we check if the intrinsic have rounding mode (7 operands),
15471       // if not, we set rounding mode to "current".
15472       SDValue Rnd;
15473       if (Op.getNumOperands() == 7)
15474         Rnd = Op.getOperand(6);
15475       else
15476         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15477       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15478         Src1, Src2, Imm, Rnd),
15479         Mask, PassThru, Subtarget, DAG);
15480     }
15481     case INTR_TYPE_3OP_MASK: {
15482       SDValue Src1 = Op.getOperand(1);
15483       SDValue Src2 = Op.getOperand(2);
15484       SDValue Src3 = Op.getOperand(3);
15485       SDValue PassThru = Op.getOperand(4);
15486       SDValue Mask = Op.getOperand(5);
15487       // We specify 2 possible opcodes for intrinsics with rounding modes.
15488       // First, we check if the intrinsic may have non-default rounding mode,
15489       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15490       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15491       if (IntrWithRoundingModeOpcode != 0) {
15492         SDValue Rnd = Op.getOperand(6);
15493         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15494         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15495           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15496                                       dl, Op.getValueType(),
15497                                       Src1, Src2, Src3, Rnd),
15498                                       Mask, PassThru, Subtarget, DAG);
15499         }
15500       }
15501       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15502                                               Src1, Src2, Src3),
15503                                   Mask, PassThru, Subtarget, DAG);
15504     }
15505     case VPERM_3OP_MASKZ:
15506     case VPERM_3OP_MASK:
15507     case FMA_OP_MASK3:
15508     case FMA_OP_MASKZ:
15509     case FMA_OP_MASK: {
15510       SDValue Src1 = Op.getOperand(1);
15511       SDValue Src2 = Op.getOperand(2);
15512       SDValue Src3 = Op.getOperand(3);
15513       SDValue Mask = Op.getOperand(4);
15514       EVT VT = Op.getValueType();
15515       SDValue PassThru = SDValue();
15516
15517       // set PassThru element
15518       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15519         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15520       else if (IntrData->Type == FMA_OP_MASK3)
15521         PassThru = Src3;
15522       else
15523         PassThru = Src1;
15524
15525       // We specify 2 possible opcodes for intrinsics with rounding modes.
15526       // First, we check if the intrinsic may have non-default rounding mode,
15527       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15528       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15529       if (IntrWithRoundingModeOpcode != 0) {
15530         SDValue Rnd = Op.getOperand(5);
15531         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15532             X86::STATIC_ROUNDING::CUR_DIRECTION)
15533           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15534                                                   dl, Op.getValueType(),
15535                                                   Src1, Src2, Src3, Rnd),
15536                                       Mask, PassThru, Subtarget, DAG);
15537       }
15538       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15539                                               dl, Op.getValueType(),
15540                                               Src1, Src2, Src3),
15541                                   Mask, PassThru, Subtarget, DAG);
15542     }
15543     case CMP_MASK:
15544     case CMP_MASK_CC: {
15545       // Comparison intrinsics with masks.
15546       // Example of transformation:
15547       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15548       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15549       // (i8 (bitcast
15550       //   (v8i1 (insert_subvector undef,
15551       //           (v2i1 (and (PCMPEQM %a, %b),
15552       //                      (extract_subvector
15553       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15554       EVT VT = Op.getOperand(1).getValueType();
15555       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15556                                     VT.getVectorNumElements());
15557       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15558       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15559                                        Mask.getValueType().getSizeInBits());
15560       SDValue Cmp;
15561       if (IntrData->Type == CMP_MASK_CC) {
15562         SDValue CC = Op.getOperand(3);
15563         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15564         // We specify 2 possible opcodes for intrinsics with rounding modes.
15565         // First, we check if the intrinsic may have non-default rounding mode,
15566         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15567         if (IntrData->Opc1 != 0) {
15568           SDValue Rnd = Op.getOperand(5);
15569           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15570               X86::STATIC_ROUNDING::CUR_DIRECTION)
15571             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15572                               Op.getOperand(2), CC, Rnd);
15573         }
15574         //default rounding mode
15575         if(!Cmp.getNode())
15576             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15577                               Op.getOperand(2), CC);
15578
15579       } else {
15580         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15581         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15582                           Op.getOperand(2));
15583       }
15584       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15585                                              DAG.getTargetConstant(0, dl,
15586                                                                    MaskVT),
15587                                              Subtarget, DAG);
15588       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15589                                 DAG.getUNDEF(BitcastVT), CmpMask,
15590                                 DAG.getIntPtrConstant(0, dl));
15591       return DAG.getBitcast(Op.getValueType(), Res);
15592     }
15593     case COMI: { // Comparison intrinsics
15594       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15595       SDValue LHS = Op.getOperand(1);
15596       SDValue RHS = Op.getOperand(2);
15597       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15598       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15599       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15600       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15601                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15602       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15603     }
15604     case VSHIFT:
15605       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15606                                  Op.getOperand(1), Op.getOperand(2), DAG);
15607     case VSHIFT_MASK:
15608       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15609                                                       Op.getSimpleValueType(),
15610                                                       Op.getOperand(1),
15611                                                       Op.getOperand(2), DAG),
15612                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15613                                   DAG);
15614     case COMPRESS_EXPAND_IN_REG: {
15615       SDValue Mask = Op.getOperand(3);
15616       SDValue DataToCompress = Op.getOperand(1);
15617       SDValue PassThru = Op.getOperand(2);
15618       if (isAllOnes(Mask)) // return data as is
15619         return Op.getOperand(1);
15620
15621       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15622                                               DataToCompress),
15623                                   Mask, PassThru, Subtarget, DAG);
15624     }
15625     case BLEND: {
15626       SDValue Mask = Op.getOperand(3);
15627       EVT VT = Op.getValueType();
15628       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15629                                     VT.getVectorNumElements());
15630       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15631                                        Mask.getValueType().getSizeInBits());
15632       SDLoc dl(Op);
15633       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15634                                   DAG.getBitcast(BitcastVT, Mask),
15635                                   DAG.getIntPtrConstant(0, dl));
15636       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15637                          Op.getOperand(2));
15638     }
15639     default:
15640       break;
15641     }
15642   }
15643
15644   switch (IntNo) {
15645   default: return SDValue();    // Don't custom lower most intrinsics.
15646
15647   case Intrinsic::x86_avx2_permd:
15648   case Intrinsic::x86_avx2_permps:
15649     // Operands intentionally swapped. Mask is last operand to intrinsic,
15650     // but second operand for node/instruction.
15651     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15652                        Op.getOperand(2), Op.getOperand(1));
15653
15654   // ptest and testp intrinsics. The intrinsic these come from are designed to
15655   // return an integer value, not just an instruction so lower it to the ptest
15656   // or testp pattern and a setcc for the result.
15657   case Intrinsic::x86_sse41_ptestz:
15658   case Intrinsic::x86_sse41_ptestc:
15659   case Intrinsic::x86_sse41_ptestnzc:
15660   case Intrinsic::x86_avx_ptestz_256:
15661   case Intrinsic::x86_avx_ptestc_256:
15662   case Intrinsic::x86_avx_ptestnzc_256:
15663   case Intrinsic::x86_avx_vtestz_ps:
15664   case Intrinsic::x86_avx_vtestc_ps:
15665   case Intrinsic::x86_avx_vtestnzc_ps:
15666   case Intrinsic::x86_avx_vtestz_pd:
15667   case Intrinsic::x86_avx_vtestc_pd:
15668   case Intrinsic::x86_avx_vtestnzc_pd:
15669   case Intrinsic::x86_avx_vtestz_ps_256:
15670   case Intrinsic::x86_avx_vtestc_ps_256:
15671   case Intrinsic::x86_avx_vtestnzc_ps_256:
15672   case Intrinsic::x86_avx_vtestz_pd_256:
15673   case Intrinsic::x86_avx_vtestc_pd_256:
15674   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15675     bool IsTestPacked = false;
15676     unsigned X86CC;
15677     switch (IntNo) {
15678     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15679     case Intrinsic::x86_avx_vtestz_ps:
15680     case Intrinsic::x86_avx_vtestz_pd:
15681     case Intrinsic::x86_avx_vtestz_ps_256:
15682     case Intrinsic::x86_avx_vtestz_pd_256:
15683       IsTestPacked = true; // Fallthrough
15684     case Intrinsic::x86_sse41_ptestz:
15685     case Intrinsic::x86_avx_ptestz_256:
15686       // ZF = 1
15687       X86CC = X86::COND_E;
15688       break;
15689     case Intrinsic::x86_avx_vtestc_ps:
15690     case Intrinsic::x86_avx_vtestc_pd:
15691     case Intrinsic::x86_avx_vtestc_ps_256:
15692     case Intrinsic::x86_avx_vtestc_pd_256:
15693       IsTestPacked = true; // Fallthrough
15694     case Intrinsic::x86_sse41_ptestc:
15695     case Intrinsic::x86_avx_ptestc_256:
15696       // CF = 1
15697       X86CC = X86::COND_B;
15698       break;
15699     case Intrinsic::x86_avx_vtestnzc_ps:
15700     case Intrinsic::x86_avx_vtestnzc_pd:
15701     case Intrinsic::x86_avx_vtestnzc_ps_256:
15702     case Intrinsic::x86_avx_vtestnzc_pd_256:
15703       IsTestPacked = true; // Fallthrough
15704     case Intrinsic::x86_sse41_ptestnzc:
15705     case Intrinsic::x86_avx_ptestnzc_256:
15706       // ZF and CF = 0
15707       X86CC = X86::COND_A;
15708       break;
15709     }
15710
15711     SDValue LHS = Op.getOperand(1);
15712     SDValue RHS = Op.getOperand(2);
15713     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15714     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15715     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15716     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15717     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15718   }
15719   case Intrinsic::x86_avx512_kortestz_w:
15720   case Intrinsic::x86_avx512_kortestc_w: {
15721     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15722     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15723     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15724     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15725     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15726     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15727     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15728   }
15729
15730   case Intrinsic::x86_sse42_pcmpistria128:
15731   case Intrinsic::x86_sse42_pcmpestria128:
15732   case Intrinsic::x86_sse42_pcmpistric128:
15733   case Intrinsic::x86_sse42_pcmpestric128:
15734   case Intrinsic::x86_sse42_pcmpistrio128:
15735   case Intrinsic::x86_sse42_pcmpestrio128:
15736   case Intrinsic::x86_sse42_pcmpistris128:
15737   case Intrinsic::x86_sse42_pcmpestris128:
15738   case Intrinsic::x86_sse42_pcmpistriz128:
15739   case Intrinsic::x86_sse42_pcmpestriz128: {
15740     unsigned Opcode;
15741     unsigned X86CC;
15742     switch (IntNo) {
15743     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15744     case Intrinsic::x86_sse42_pcmpistria128:
15745       Opcode = X86ISD::PCMPISTRI;
15746       X86CC = X86::COND_A;
15747       break;
15748     case Intrinsic::x86_sse42_pcmpestria128:
15749       Opcode = X86ISD::PCMPESTRI;
15750       X86CC = X86::COND_A;
15751       break;
15752     case Intrinsic::x86_sse42_pcmpistric128:
15753       Opcode = X86ISD::PCMPISTRI;
15754       X86CC = X86::COND_B;
15755       break;
15756     case Intrinsic::x86_sse42_pcmpestric128:
15757       Opcode = X86ISD::PCMPESTRI;
15758       X86CC = X86::COND_B;
15759       break;
15760     case Intrinsic::x86_sse42_pcmpistrio128:
15761       Opcode = X86ISD::PCMPISTRI;
15762       X86CC = X86::COND_O;
15763       break;
15764     case Intrinsic::x86_sse42_pcmpestrio128:
15765       Opcode = X86ISD::PCMPESTRI;
15766       X86CC = X86::COND_O;
15767       break;
15768     case Intrinsic::x86_sse42_pcmpistris128:
15769       Opcode = X86ISD::PCMPISTRI;
15770       X86CC = X86::COND_S;
15771       break;
15772     case Intrinsic::x86_sse42_pcmpestris128:
15773       Opcode = X86ISD::PCMPESTRI;
15774       X86CC = X86::COND_S;
15775       break;
15776     case Intrinsic::x86_sse42_pcmpistriz128:
15777       Opcode = X86ISD::PCMPISTRI;
15778       X86CC = X86::COND_E;
15779       break;
15780     case Intrinsic::x86_sse42_pcmpestriz128:
15781       Opcode = X86ISD::PCMPESTRI;
15782       X86CC = X86::COND_E;
15783       break;
15784     }
15785     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15786     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15787     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15788     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15789                                 DAG.getConstant(X86CC, dl, MVT::i8),
15790                                 SDValue(PCMP.getNode(), 1));
15791     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15792   }
15793
15794   case Intrinsic::x86_sse42_pcmpistri128:
15795   case Intrinsic::x86_sse42_pcmpestri128: {
15796     unsigned Opcode;
15797     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15798       Opcode = X86ISD::PCMPISTRI;
15799     else
15800       Opcode = X86ISD::PCMPESTRI;
15801
15802     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15803     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15804     return DAG.getNode(Opcode, dl, VTs, NewOps);
15805   }
15806
15807   case Intrinsic::x86_seh_lsda: {
15808     // Compute the symbol for the LSDA. We know it'll get emitted later.
15809     MachineFunction &MF = DAG.getMachineFunction();
15810     SDValue Op1 = Op.getOperand(1);
15811     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15812     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15813         GlobalValue::getRealLinkageName(Fn->getName()));
15814
15815     // Generate a simple absolute symbol reference. This intrinsic is only
15816     // supported on 32-bit Windows, which isn't PIC.
15817     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15818     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15819   }
15820
15821   case Intrinsic::x86_seh_recoverfp: {
15822     SDValue FnOp = Op.getOperand(1);
15823     SDValue IncomingFPOp = Op.getOperand(2);
15824     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15825     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15826     if (!Fn)
15827       report_fatal_error(
15828           "llvm.x86.seh.recoverfp must take a function as the first argument");
15829     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15830   }
15831
15832   case Intrinsic::localaddress: {
15833     // Returns one of the stack, base, or frame pointer registers, depending on
15834     // which is used to reference local variables.
15835     MachineFunction &MF = DAG.getMachineFunction();
15836     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15837     unsigned Reg;
15838     if (RegInfo->hasBasePointer(MF))
15839       Reg = RegInfo->getBaseRegister();
15840     else // This function handles the SP or FP case.
15841       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15842     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15843   }
15844   }
15845 }
15846
15847 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15848                               SDValue Src, SDValue Mask, SDValue Base,
15849                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15850                               const X86Subtarget * Subtarget) {
15851   SDLoc dl(Op);
15852   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15853   if (!C)
15854     llvm_unreachable("Invalid scale type");
15855   unsigned ScaleVal = C->getZExtValue();
15856   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15857     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15858
15859   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15860   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15861                              Index.getSimpleValueType().getVectorNumElements());
15862   SDValue MaskInReg;
15863   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15864   if (MaskC)
15865     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15866   else {
15867     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15868                                      Mask.getValueType().getSizeInBits());
15869
15870     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15871     // are extracted by EXTRACT_SUBVECTOR.
15872     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15873                             DAG.getBitcast(BitcastVT, Mask),
15874                             DAG.getIntPtrConstant(0, dl));
15875   }
15876   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15877   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15878   SDValue Segment = DAG.getRegister(0, MVT::i32);
15879   if (Src.getOpcode() == ISD::UNDEF)
15880     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15881   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15882   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15883   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15884   return DAG.getMergeValues(RetOps, dl);
15885 }
15886
15887 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15888                                SDValue Src, SDValue Mask, SDValue Base,
15889                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15890   SDLoc dl(Op);
15891   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15892   if (!C)
15893     llvm_unreachable("Invalid scale type");
15894   unsigned ScaleVal = C->getZExtValue();
15895   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15896     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15897
15898   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15899   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15900   SDValue Segment = DAG.getRegister(0, MVT::i32);
15901   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15902                              Index.getSimpleValueType().getVectorNumElements());
15903   SDValue MaskInReg;
15904   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15905   if (MaskC)
15906     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15907   else {
15908     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15909                                      Mask.getValueType().getSizeInBits());
15910
15911     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15912     // are extracted by EXTRACT_SUBVECTOR.
15913     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15914                             DAG.getBitcast(BitcastVT, Mask),
15915                             DAG.getIntPtrConstant(0, dl));
15916   }
15917   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15918   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15919   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15920   return SDValue(Res, 1);
15921 }
15922
15923 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15924                                SDValue Mask, SDValue Base, SDValue Index,
15925                                SDValue ScaleOp, SDValue Chain) {
15926   SDLoc dl(Op);
15927   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15928   assert(C && "Invalid scale type");
15929   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15930   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15931   SDValue Segment = DAG.getRegister(0, MVT::i32);
15932   EVT MaskVT =
15933     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15934   SDValue MaskInReg;
15935   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15936   if (MaskC)
15937     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15938   else
15939     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15940   //SDVTList VTs = DAG.getVTList(MVT::Other);
15941   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15942   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15943   return SDValue(Res, 0);
15944 }
15945
15946 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15947 // read performance monitor counters (x86_rdpmc).
15948 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15949                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15950                               SmallVectorImpl<SDValue> &Results) {
15951   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15952   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15953   SDValue LO, HI;
15954
15955   // The ECX register is used to select the index of the performance counter
15956   // to read.
15957   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15958                                    N->getOperand(2));
15959   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15960
15961   // Reads the content of a 64-bit performance counter and returns it in the
15962   // registers EDX:EAX.
15963   if (Subtarget->is64Bit()) {
15964     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15965     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15966                             LO.getValue(2));
15967   } else {
15968     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15969     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15970                             LO.getValue(2));
15971   }
15972   Chain = HI.getValue(1);
15973
15974   if (Subtarget->is64Bit()) {
15975     // The EAX register is loaded with the low-order 32 bits. The EDX register
15976     // is loaded with the supported high-order bits of the counter.
15977     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15978                               DAG.getConstant(32, DL, MVT::i8));
15979     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15980     Results.push_back(Chain);
15981     return;
15982   }
15983
15984   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15985   SDValue Ops[] = { LO, HI };
15986   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15987   Results.push_back(Pair);
15988   Results.push_back(Chain);
15989 }
15990
15991 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15992 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15993 // also used to custom lower READCYCLECOUNTER nodes.
15994 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15995                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15996                               SmallVectorImpl<SDValue> &Results) {
15997   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15998   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15999   SDValue LO, HI;
16000
16001   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
16002   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
16003   // and the EAX register is loaded with the low-order 32 bits.
16004   if (Subtarget->is64Bit()) {
16005     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
16006     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
16007                             LO.getValue(2));
16008   } else {
16009     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
16010     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
16011                             LO.getValue(2));
16012   }
16013   SDValue Chain = HI.getValue(1);
16014
16015   if (Opcode == X86ISD::RDTSCP_DAG) {
16016     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
16017
16018     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
16019     // the ECX register. Add 'ecx' explicitly to the chain.
16020     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
16021                                      HI.getValue(2));
16022     // Explicitly store the content of ECX at the location passed in input
16023     // to the 'rdtscp' intrinsic.
16024     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
16025                          MachinePointerInfo(), false, false, 0);
16026   }
16027
16028   if (Subtarget->is64Bit()) {
16029     // The EDX register is loaded with the high-order 32 bits of the MSR, and
16030     // the EAX register is loaded with the low-order 32 bits.
16031     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
16032                               DAG.getConstant(32, DL, MVT::i8));
16033     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
16034     Results.push_back(Chain);
16035     return;
16036   }
16037
16038   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16039   SDValue Ops[] = { LO, HI };
16040   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16041   Results.push_back(Pair);
16042   Results.push_back(Chain);
16043 }
16044
16045 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16046                                      SelectionDAG &DAG) {
16047   SmallVector<SDValue, 2> Results;
16048   SDLoc DL(Op);
16049   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16050                           Results);
16051   return DAG.getMergeValues(Results, DL);
16052 }
16053
16054 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16055                                     SelectionDAG &DAG) {
16056   MachineFunction &MF = DAG.getMachineFunction();
16057   const Function *Fn = MF.getFunction();
16058   SDLoc dl(Op);
16059   SDValue Chain = Op.getOperand(0);
16060
16061   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16062          "using llvm.x86.seh.restoreframe requires a frame pointer");
16063
16064   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16065   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16066
16067   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16068   unsigned FrameReg =
16069       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16070   unsigned SPReg = RegInfo->getStackRegister();
16071   unsigned SlotSize = RegInfo->getSlotSize();
16072
16073   // Get incoming EBP.
16074   SDValue IncomingEBP =
16075       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16076
16077   // SP is saved in the first field of every registration node, so load
16078   // [EBP-RegNodeSize] into SP.
16079   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16080   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16081                                DAG.getConstant(-RegNodeSize, dl, VT));
16082   SDValue NewSP =
16083       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16084                   false, VT.getScalarSizeInBits() / 8);
16085   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16086
16087   if (!RegInfo->needsStackRealignment(MF)) {
16088     // Adjust EBP to point back to the original frame position.
16089     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16090     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16091   } else {
16092     assert(RegInfo->hasBasePointer(MF) &&
16093            "functions with Win32 EH must use frame or base pointer register");
16094
16095     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16096     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16097     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16098
16099     // Reload the spilled EBP value, now that the stack and base pointers are
16100     // set up.
16101     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16102     X86FI->setHasSEHFramePtrSave(true);
16103     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16104     X86FI->setSEHFramePtrSaveIndex(FI);
16105     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16106                                 MachinePointerInfo(), false, false, false,
16107                                 VT.getScalarSizeInBits() / 8);
16108     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16109   }
16110
16111   return Chain;
16112 }
16113
16114 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16115                                       SelectionDAG &DAG) {
16116   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16117
16118   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16119   if (!IntrData) {
16120     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16121       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16122     return SDValue();
16123   }
16124
16125   SDLoc dl(Op);
16126   switch(IntrData->Type) {
16127   default:
16128     llvm_unreachable("Unknown Intrinsic Type");
16129     break;
16130   case RDSEED:
16131   case RDRAND: {
16132     // Emit the node with the right value type.
16133     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16134     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16135
16136     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16137     // Otherwise return the value from Rand, which is always 0, casted to i32.
16138     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16139                       DAG.getConstant(1, dl, Op->getValueType(1)),
16140                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16141                       SDValue(Result.getNode(), 1) };
16142     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16143                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16144                                   Ops);
16145
16146     // Return { result, isValid, chain }.
16147     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16148                        SDValue(Result.getNode(), 2));
16149   }
16150   case GATHER: {
16151   //gather(v1, mask, index, base, scale);
16152     SDValue Chain = Op.getOperand(0);
16153     SDValue Src   = Op.getOperand(2);
16154     SDValue Base  = Op.getOperand(3);
16155     SDValue Index = Op.getOperand(4);
16156     SDValue Mask  = Op.getOperand(5);
16157     SDValue Scale = Op.getOperand(6);
16158     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16159                          Chain, Subtarget);
16160   }
16161   case SCATTER: {
16162   //scatter(base, mask, index, v1, scale);
16163     SDValue Chain = Op.getOperand(0);
16164     SDValue Base  = Op.getOperand(2);
16165     SDValue Mask  = Op.getOperand(3);
16166     SDValue Index = Op.getOperand(4);
16167     SDValue Src   = Op.getOperand(5);
16168     SDValue Scale = Op.getOperand(6);
16169     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16170                           Scale, Chain);
16171   }
16172   case PREFETCH: {
16173     SDValue Hint = Op.getOperand(6);
16174     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16175     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16176     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16177     SDValue Chain = Op.getOperand(0);
16178     SDValue Mask  = Op.getOperand(2);
16179     SDValue Index = Op.getOperand(3);
16180     SDValue Base  = Op.getOperand(4);
16181     SDValue Scale = Op.getOperand(5);
16182     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16183   }
16184   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16185   case RDTSC: {
16186     SmallVector<SDValue, 2> Results;
16187     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16188                             Results);
16189     return DAG.getMergeValues(Results, dl);
16190   }
16191   // Read Performance Monitoring Counters.
16192   case RDPMC: {
16193     SmallVector<SDValue, 2> Results;
16194     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16195     return DAG.getMergeValues(Results, dl);
16196   }
16197   // XTEST intrinsics.
16198   case XTEST: {
16199     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16200     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16201     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16202                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16203                                 InTrans);
16204     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16205     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16206                        Ret, SDValue(InTrans.getNode(), 1));
16207   }
16208   // ADC/ADCX/SBB
16209   case ADX: {
16210     SmallVector<SDValue, 2> Results;
16211     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16212     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16213     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16214                                 DAG.getConstant(-1, dl, MVT::i8));
16215     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16216                               Op.getOperand(4), GenCF.getValue(1));
16217     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16218                                  Op.getOperand(5), MachinePointerInfo(),
16219                                  false, false, 0);
16220     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16221                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16222                                 Res.getValue(1));
16223     Results.push_back(SetCC);
16224     Results.push_back(Store);
16225     return DAG.getMergeValues(Results, dl);
16226   }
16227   case COMPRESS_TO_MEM: {
16228     SDLoc dl(Op);
16229     SDValue Mask = Op.getOperand(4);
16230     SDValue DataToCompress = Op.getOperand(3);
16231     SDValue Addr = Op.getOperand(2);
16232     SDValue Chain = Op.getOperand(0);
16233
16234     EVT VT = DataToCompress.getValueType();
16235     if (isAllOnes(Mask)) // return just a store
16236       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16237                           MachinePointerInfo(), false, false,
16238                           VT.getScalarSizeInBits()/8);
16239
16240     SDValue Compressed =
16241       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16242                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16243     return DAG.getStore(Chain, dl, Compressed, Addr,
16244                         MachinePointerInfo(), false, false,
16245                         VT.getScalarSizeInBits()/8);
16246   }
16247   case EXPAND_FROM_MEM: {
16248     SDLoc dl(Op);
16249     SDValue Mask = Op.getOperand(4);
16250     SDValue PassThru = Op.getOperand(3);
16251     SDValue Addr = Op.getOperand(2);
16252     SDValue Chain = Op.getOperand(0);
16253     EVT VT = Op.getValueType();
16254
16255     if (isAllOnes(Mask)) // return just a load
16256       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16257                          false, VT.getScalarSizeInBits()/8);
16258
16259     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16260                                        false, false, false,
16261                                        VT.getScalarSizeInBits()/8);
16262
16263     SDValue Results[] = {
16264       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16265                            Mask, PassThru, Subtarget, DAG), Chain};
16266     return DAG.getMergeValues(Results, dl);
16267   }
16268   }
16269 }
16270
16271 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16272                                            SelectionDAG &DAG) const {
16273   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16274   MFI->setReturnAddressIsTaken(true);
16275
16276   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16277     return SDValue();
16278
16279   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16280   SDLoc dl(Op);
16281   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16282
16283   if (Depth > 0) {
16284     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16285     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16286     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16287     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16288                        DAG.getNode(ISD::ADD, dl, PtrVT,
16289                                    FrameAddr, Offset),
16290                        MachinePointerInfo(), false, false, false, 0);
16291   }
16292
16293   // Just load the return address.
16294   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16295   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16296                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16297 }
16298
16299 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16300   MachineFunction &MF = DAG.getMachineFunction();
16301   MachineFrameInfo *MFI = MF.getFrameInfo();
16302   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16303   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16304   EVT VT = Op.getValueType();
16305
16306   MFI->setFrameAddressIsTaken(true);
16307
16308   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16309     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16310     // is not possible to crawl up the stack without looking at the unwind codes
16311     // simultaneously.
16312     int FrameAddrIndex = FuncInfo->getFAIndex();
16313     if (!FrameAddrIndex) {
16314       // Set up a frame object for the return address.
16315       unsigned SlotSize = RegInfo->getSlotSize();
16316       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16317           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16318       FuncInfo->setFAIndex(FrameAddrIndex);
16319     }
16320     return DAG.getFrameIndex(FrameAddrIndex, VT);
16321   }
16322
16323   unsigned FrameReg =
16324       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16325   SDLoc dl(Op);  // FIXME probably not meaningful
16326   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16327   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16328           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16329          "Invalid Frame Register!");
16330   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16331   while (Depth--)
16332     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16333                             MachinePointerInfo(),
16334                             false, false, false, 0);
16335   return FrameAddr;
16336 }
16337
16338 // FIXME? Maybe this could be a TableGen attribute on some registers and
16339 // this table could be generated automatically from RegInfo.
16340 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16341                                               SelectionDAG &DAG) const {
16342   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16343   const MachineFunction &MF = DAG.getMachineFunction();
16344
16345   unsigned Reg = StringSwitch<unsigned>(RegName)
16346                        .Case("esp", X86::ESP)
16347                        .Case("rsp", X86::RSP)
16348                        .Case("ebp", X86::EBP)
16349                        .Case("rbp", X86::RBP)
16350                        .Default(0);
16351
16352   if (Reg == X86::EBP || Reg == X86::RBP) {
16353     if (!TFI.hasFP(MF))
16354       report_fatal_error("register " + StringRef(RegName) +
16355                          " is allocatable: function has no frame pointer");
16356 #ifndef NDEBUG
16357     else {
16358       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16359       unsigned FrameReg =
16360           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16361       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16362              "Invalid Frame Register!");
16363     }
16364 #endif
16365   }
16366
16367   if (Reg)
16368     return Reg;
16369
16370   report_fatal_error("Invalid register name global variable");
16371 }
16372
16373 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16374                                                      SelectionDAG &DAG) const {
16375   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16376   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16377 }
16378
16379 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16380   SDValue Chain     = Op.getOperand(0);
16381   SDValue Offset    = Op.getOperand(1);
16382   SDValue Handler   = Op.getOperand(2);
16383   SDLoc dl      (Op);
16384
16385   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16386   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16387   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16388   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16389           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16390          "Invalid Frame Register!");
16391   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16392   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16393
16394   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16395                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16396                                                        dl));
16397   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16398   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16399                        false, false, 0);
16400   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16401
16402   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16403                      DAG.getRegister(StoreAddrReg, PtrVT));
16404 }
16405
16406 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16407                                                SelectionDAG &DAG) const {
16408   SDLoc DL(Op);
16409   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16410                      DAG.getVTList(MVT::i32, MVT::Other),
16411                      Op.getOperand(0), Op.getOperand(1));
16412 }
16413
16414 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16415                                                 SelectionDAG &DAG) const {
16416   SDLoc DL(Op);
16417   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16418                      Op.getOperand(0), Op.getOperand(1));
16419 }
16420
16421 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16422   return Op.getOperand(0);
16423 }
16424
16425 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16426                                                 SelectionDAG &DAG) const {
16427   SDValue Root = Op.getOperand(0);
16428   SDValue Trmp = Op.getOperand(1); // trampoline
16429   SDValue FPtr = Op.getOperand(2); // nested function
16430   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16431   SDLoc dl (Op);
16432
16433   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16434   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16435
16436   if (Subtarget->is64Bit()) {
16437     SDValue OutChains[6];
16438
16439     // Large code-model.
16440     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16441     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16442
16443     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16444     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16445
16446     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16447
16448     // Load the pointer to the nested function into R11.
16449     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16450     SDValue Addr = Trmp;
16451     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16452                                 Addr, MachinePointerInfo(TrmpAddr),
16453                                 false, false, 0);
16454
16455     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16456                        DAG.getConstant(2, dl, MVT::i64));
16457     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16458                                 MachinePointerInfo(TrmpAddr, 2),
16459                                 false, false, 2);
16460
16461     // Load the 'nest' parameter value into R10.
16462     // R10 is specified in X86CallingConv.td
16463     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16464     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16465                        DAG.getConstant(10, dl, MVT::i64));
16466     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16467                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16468                                 false, false, 0);
16469
16470     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16471                        DAG.getConstant(12, dl, MVT::i64));
16472     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16473                                 MachinePointerInfo(TrmpAddr, 12),
16474                                 false, false, 2);
16475
16476     // Jump to the nested function.
16477     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16478     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16479                        DAG.getConstant(20, dl, MVT::i64));
16480     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16481                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16482                                 false, false, 0);
16483
16484     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16485     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16486                        DAG.getConstant(22, dl, MVT::i64));
16487     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16488                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16489                                 false, false, 0);
16490
16491     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16492   } else {
16493     const Function *Func =
16494       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16495     CallingConv::ID CC = Func->getCallingConv();
16496     unsigned NestReg;
16497
16498     switch (CC) {
16499     default:
16500       llvm_unreachable("Unsupported calling convention");
16501     case CallingConv::C:
16502     case CallingConv::X86_StdCall: {
16503       // Pass 'nest' parameter in ECX.
16504       // Must be kept in sync with X86CallingConv.td
16505       NestReg = X86::ECX;
16506
16507       // Check that ECX wasn't needed by an 'inreg' parameter.
16508       FunctionType *FTy = Func->getFunctionType();
16509       const AttributeSet &Attrs = Func->getAttributes();
16510
16511       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16512         unsigned InRegCount = 0;
16513         unsigned Idx = 1;
16514
16515         for (FunctionType::param_iterator I = FTy->param_begin(),
16516              E = FTy->param_end(); I != E; ++I, ++Idx)
16517           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16518             // FIXME: should only count parameters that are lowered to integers.
16519             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16520
16521         if (InRegCount > 2) {
16522           report_fatal_error("Nest register in use - reduce number of inreg"
16523                              " parameters!");
16524         }
16525       }
16526       break;
16527     }
16528     case CallingConv::X86_FastCall:
16529     case CallingConv::X86_ThisCall:
16530     case CallingConv::Fast:
16531       // Pass 'nest' parameter in EAX.
16532       // Must be kept in sync with X86CallingConv.td
16533       NestReg = X86::EAX;
16534       break;
16535     }
16536
16537     SDValue OutChains[4];
16538     SDValue Addr, Disp;
16539
16540     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16541                        DAG.getConstant(10, dl, MVT::i32));
16542     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16543
16544     // This is storing the opcode for MOV32ri.
16545     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16546     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16547     OutChains[0] = DAG.getStore(Root, dl,
16548                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16549                                 Trmp, MachinePointerInfo(TrmpAddr),
16550                                 false, false, 0);
16551
16552     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16553                        DAG.getConstant(1, dl, MVT::i32));
16554     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16555                                 MachinePointerInfo(TrmpAddr, 1),
16556                                 false, false, 1);
16557
16558     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16559     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16560                        DAG.getConstant(5, dl, MVT::i32));
16561     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16562                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16563                                 false, false, 1);
16564
16565     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16566                        DAG.getConstant(6, dl, MVT::i32));
16567     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16568                                 MachinePointerInfo(TrmpAddr, 6),
16569                                 false, false, 1);
16570
16571     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16572   }
16573 }
16574
16575 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16576                                             SelectionDAG &DAG) const {
16577   /*
16578    The rounding mode is in bits 11:10 of FPSR, and has the following
16579    settings:
16580      00 Round to nearest
16581      01 Round to -inf
16582      10 Round to +inf
16583      11 Round to 0
16584
16585   FLT_ROUNDS, on the other hand, expects the following:
16586     -1 Undefined
16587      0 Round to 0
16588      1 Round to nearest
16589      2 Round to +inf
16590      3 Round to -inf
16591
16592   To perform the conversion, we do:
16593     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16594   */
16595
16596   MachineFunction &MF = DAG.getMachineFunction();
16597   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16598   unsigned StackAlignment = TFI.getStackAlignment();
16599   MVT VT = Op.getSimpleValueType();
16600   SDLoc DL(Op);
16601
16602   // Save FP Control Word to stack slot
16603   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16604   SDValue StackSlot =
16605       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16606
16607   MachineMemOperand *MMO =
16608    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16609                            MachineMemOperand::MOStore, 2, 2);
16610
16611   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16612   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16613                                           DAG.getVTList(MVT::Other),
16614                                           Ops, MVT::i16, MMO);
16615
16616   // Load FP Control Word from stack slot
16617   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16618                             MachinePointerInfo(), false, false, false, 0);
16619
16620   // Transform as necessary
16621   SDValue CWD1 =
16622     DAG.getNode(ISD::SRL, DL, MVT::i16,
16623                 DAG.getNode(ISD::AND, DL, MVT::i16,
16624                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16625                 DAG.getConstant(11, DL, MVT::i8));
16626   SDValue CWD2 =
16627     DAG.getNode(ISD::SRL, DL, MVT::i16,
16628                 DAG.getNode(ISD::AND, DL, MVT::i16,
16629                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16630                 DAG.getConstant(9, DL, MVT::i8));
16631
16632   SDValue RetVal =
16633     DAG.getNode(ISD::AND, DL, MVT::i16,
16634                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16635                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16636                             DAG.getConstant(1, DL, MVT::i16)),
16637                 DAG.getConstant(3, DL, MVT::i16));
16638
16639   return DAG.getNode((VT.getSizeInBits() < 16 ?
16640                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16641 }
16642
16643 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16644   MVT VT = Op.getSimpleValueType();
16645   EVT OpVT = VT;
16646   unsigned NumBits = VT.getSizeInBits();
16647   SDLoc dl(Op);
16648
16649   Op = Op.getOperand(0);
16650   if (VT == MVT::i8) {
16651     // Zero extend to i32 since there is not an i8 bsr.
16652     OpVT = MVT::i32;
16653     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16654   }
16655
16656   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16657   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16658   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16659
16660   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16661   SDValue Ops[] = {
16662     Op,
16663     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16664     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16665     Op.getValue(1)
16666   };
16667   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16668
16669   // Finally xor with NumBits-1.
16670   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16671                    DAG.getConstant(NumBits - 1, dl, OpVT));
16672
16673   if (VT == MVT::i8)
16674     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16675   return Op;
16676 }
16677
16678 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16679   MVT VT = Op.getSimpleValueType();
16680   EVT OpVT = VT;
16681   unsigned NumBits = VT.getSizeInBits();
16682   SDLoc dl(Op);
16683
16684   Op = Op.getOperand(0);
16685   if (VT == MVT::i8) {
16686     // Zero extend to i32 since there is not an i8 bsr.
16687     OpVT = MVT::i32;
16688     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16689   }
16690
16691   // Issue a bsr (scan bits in reverse).
16692   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16693   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16694
16695   // And xor with NumBits-1.
16696   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16697                    DAG.getConstant(NumBits - 1, dl, OpVT));
16698
16699   if (VT == MVT::i8)
16700     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16701   return Op;
16702 }
16703
16704 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16705   MVT VT = Op.getSimpleValueType();
16706   unsigned NumBits = VT.getSizeInBits();
16707   SDLoc dl(Op);
16708   Op = Op.getOperand(0);
16709
16710   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16711   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16712   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16713
16714   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16715   SDValue Ops[] = {
16716     Op,
16717     DAG.getConstant(NumBits, dl, VT),
16718     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16719     Op.getValue(1)
16720   };
16721   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16722 }
16723
16724 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16725 // ones, and then concatenate the result back.
16726 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16727   MVT VT = Op.getSimpleValueType();
16728
16729   assert(VT.is256BitVector() && VT.isInteger() &&
16730          "Unsupported value type for operation");
16731
16732   unsigned NumElems = VT.getVectorNumElements();
16733   SDLoc dl(Op);
16734
16735   // Extract the LHS vectors
16736   SDValue LHS = Op.getOperand(0);
16737   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16738   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16739
16740   // Extract the RHS vectors
16741   SDValue RHS = Op.getOperand(1);
16742   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16743   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16744
16745   MVT EltVT = VT.getVectorElementType();
16746   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16747
16748   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16749                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16750                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16751 }
16752
16753 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16754   if (Op.getValueType() == MVT::i1)
16755     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16756                        Op.getOperand(0), Op.getOperand(1));
16757   assert(Op.getSimpleValueType().is256BitVector() &&
16758          Op.getSimpleValueType().isInteger() &&
16759          "Only handle AVX 256-bit vector integer operation");
16760   return Lower256IntArith(Op, DAG);
16761 }
16762
16763 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16764   if (Op.getValueType() == MVT::i1)
16765     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16766                        Op.getOperand(0), Op.getOperand(1));
16767   assert(Op.getSimpleValueType().is256BitVector() &&
16768          Op.getSimpleValueType().isInteger() &&
16769          "Only handle AVX 256-bit vector integer operation");
16770   return Lower256IntArith(Op, DAG);
16771 }
16772
16773 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16774                         SelectionDAG &DAG) {
16775   SDLoc dl(Op);
16776   MVT VT = Op.getSimpleValueType();
16777
16778   if (VT == MVT::i1)
16779     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16780
16781   // Decompose 256-bit ops into smaller 128-bit ops.
16782   if (VT.is256BitVector() && !Subtarget->hasInt256())
16783     return Lower256IntArith(Op, DAG);
16784
16785   SDValue A = Op.getOperand(0);
16786   SDValue B = Op.getOperand(1);
16787
16788   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16789   // pairs, multiply and truncate.
16790   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16791     if (Subtarget->hasInt256()) {
16792       if (VT == MVT::v32i8) {
16793         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16794         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16795         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16796         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16797         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16798         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16799         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16800         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16801                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16802                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16803       }
16804
16805       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16806       return DAG.getNode(
16807           ISD::TRUNCATE, dl, VT,
16808           DAG.getNode(ISD::MUL, dl, ExVT,
16809                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16810                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16811     }
16812
16813     assert(VT == MVT::v16i8 &&
16814            "Pre-AVX2 support only supports v16i8 multiplication");
16815     MVT ExVT = MVT::v8i16;
16816
16817     // Extract the lo parts and sign extend to i16
16818     SDValue ALo, BLo;
16819     if (Subtarget->hasSSE41()) {
16820       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16821       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16822     } else {
16823       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16824                               -1, 4, -1, 5, -1, 6, -1, 7};
16825       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16826       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16827       ALo = DAG.getBitcast(ExVT, ALo);
16828       BLo = DAG.getBitcast(ExVT, BLo);
16829       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16830       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16831     }
16832
16833     // Extract the hi parts and sign extend to i16
16834     SDValue AHi, BHi;
16835     if (Subtarget->hasSSE41()) {
16836       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16837                               -1, -1, -1, -1, -1, -1, -1, -1};
16838       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16839       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16840       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16841       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16842     } else {
16843       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16844                               -1, 12, -1, 13, -1, 14, -1, 15};
16845       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16846       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16847       AHi = DAG.getBitcast(ExVT, AHi);
16848       BHi = DAG.getBitcast(ExVT, BHi);
16849       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16850       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16851     }
16852
16853     // Multiply, mask the lower 8bits of the lo/hi results and pack
16854     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16855     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16856     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16857     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16858     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16859   }
16860
16861   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16862   if (VT == MVT::v4i32) {
16863     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16864            "Should not custom lower when pmuldq is available!");
16865
16866     // Extract the odd parts.
16867     static const int UnpackMask[] = { 1, -1, 3, -1 };
16868     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16869     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16870
16871     // Multiply the even parts.
16872     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16873     // Now multiply odd parts.
16874     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16875
16876     Evens = DAG.getBitcast(VT, Evens);
16877     Odds = DAG.getBitcast(VT, Odds);
16878
16879     // Merge the two vectors back together with a shuffle. This expands into 2
16880     // shuffles.
16881     static const int ShufMask[] = { 0, 4, 2, 6 };
16882     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16883   }
16884
16885   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16886          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16887
16888   //  Ahi = psrlqi(a, 32);
16889   //  Bhi = psrlqi(b, 32);
16890   //
16891   //  AloBlo = pmuludq(a, b);
16892   //  AloBhi = pmuludq(a, Bhi);
16893   //  AhiBlo = pmuludq(Ahi, b);
16894
16895   //  AloBhi = psllqi(AloBhi, 32);
16896   //  AhiBlo = psllqi(AhiBlo, 32);
16897   //  return AloBlo + AloBhi + AhiBlo;
16898
16899   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16900   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16901
16902   SDValue AhiBlo = Ahi;
16903   SDValue AloBhi = Bhi;
16904   // Bit cast to 32-bit vectors for MULUDQ
16905   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16906                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16907   A = DAG.getBitcast(MulVT, A);
16908   B = DAG.getBitcast(MulVT, B);
16909   Ahi = DAG.getBitcast(MulVT, Ahi);
16910   Bhi = DAG.getBitcast(MulVT, Bhi);
16911
16912   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16913   // After shifting right const values the result may be all-zero.
16914   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16915     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16916     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16917   }
16918   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16919     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16920     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16921   }
16922
16923   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16924   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16925 }
16926
16927 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16928   assert(Subtarget->isTargetWin64() && "Unexpected target");
16929   EVT VT = Op.getValueType();
16930   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16931          "Unexpected return type for lowering");
16932
16933   RTLIB::Libcall LC;
16934   bool isSigned;
16935   switch (Op->getOpcode()) {
16936   default: llvm_unreachable("Unexpected request for libcall!");
16937   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16938   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16939   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16940   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16941   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16942   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16943   }
16944
16945   SDLoc dl(Op);
16946   SDValue InChain = DAG.getEntryNode();
16947
16948   TargetLowering::ArgListTy Args;
16949   TargetLowering::ArgListEntry Entry;
16950   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16951     EVT ArgVT = Op->getOperand(i).getValueType();
16952     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16953            "Unexpected argument type for lowering");
16954     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16955     Entry.Node = StackPtr;
16956     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16957                            false, false, 16);
16958     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16959     Entry.Ty = PointerType::get(ArgTy,0);
16960     Entry.isSExt = false;
16961     Entry.isZExt = false;
16962     Args.push_back(Entry);
16963   }
16964
16965   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16966                                          getPointerTy(DAG.getDataLayout()));
16967
16968   TargetLowering::CallLoweringInfo CLI(DAG);
16969   CLI.setDebugLoc(dl).setChain(InChain)
16970     .setCallee(getLibcallCallingConv(LC),
16971                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16972                Callee, std::move(Args), 0)
16973     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16974
16975   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16976   return DAG.getBitcast(VT, CallInfo.first);
16977 }
16978
16979 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16980                              SelectionDAG &DAG) {
16981   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16982   EVT VT = Op0.getValueType();
16983   SDLoc dl(Op);
16984
16985   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16986          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16987
16988   // PMULxD operations multiply each even value (starting at 0) of LHS with
16989   // the related value of RHS and produce a widen result.
16990   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16991   // => <2 x i64> <ae|cg>
16992   //
16993   // In other word, to have all the results, we need to perform two PMULxD:
16994   // 1. one with the even values.
16995   // 2. one with the odd values.
16996   // To achieve #2, with need to place the odd values at an even position.
16997   //
16998   // Place the odd value at an even position (basically, shift all values 1
16999   // step to the left):
17000   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
17001   // <a|b|c|d> => <b|undef|d|undef>
17002   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
17003   // <e|f|g|h> => <f|undef|h|undef>
17004   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
17005
17006   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
17007   // ints.
17008   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
17009   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
17010   unsigned Opcode =
17011       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
17012   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
17013   // => <2 x i64> <ae|cg>
17014   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
17015   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
17016   // => <2 x i64> <bf|dh>
17017   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
17018
17019   // Shuffle it back into the right order.
17020   SDValue Highs, Lows;
17021   if (VT == MVT::v8i32) {
17022     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
17023     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17024     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
17025     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17026   } else {
17027     const int HighMask[] = {1, 5, 3, 7};
17028     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
17029     const int LowMask[] = {0, 4, 2, 6};
17030     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
17031   }
17032
17033   // If we have a signed multiply but no PMULDQ fix up the high parts of a
17034   // unsigned multiply.
17035   if (IsSigned && !Subtarget->hasSSE41()) {
17036     SDValue ShAmt = DAG.getConstant(
17037         31, dl,
17038         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17039     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17040                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17041     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17042                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17043
17044     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17045     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17046   }
17047
17048   // The first result of MUL_LOHI is actually the low value, followed by the
17049   // high value.
17050   SDValue Ops[] = {Lows, Highs};
17051   return DAG.getMergeValues(Ops, dl);
17052 }
17053
17054 // Return true if the required (according to Opcode) shift-imm form is natively
17055 // supported by the Subtarget
17056 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17057                                         unsigned Opcode) {
17058   if (VT.getScalarSizeInBits() < 16)
17059     return false;
17060
17061   if (VT.is512BitVector() &&
17062       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17063     return true;
17064
17065   bool LShift = VT.is128BitVector() ||
17066     (VT.is256BitVector() && Subtarget->hasInt256());
17067
17068   bool AShift = LShift && (Subtarget->hasVLX() ||
17069     (VT != MVT::v2i64 && VT != MVT::v4i64));
17070   return (Opcode == ISD::SRA) ? AShift : LShift;
17071 }
17072
17073 // The shift amount is a variable, but it is the same for all vector lanes.
17074 // These instructions are defined together with shift-immediate.
17075 static
17076 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17077                                       unsigned Opcode) {
17078   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17079 }
17080
17081 // Return true if the required (according to Opcode) variable-shift form is
17082 // natively supported by the Subtarget
17083 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17084                                     unsigned Opcode) {
17085
17086   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17087     return false;
17088
17089   // vXi16 supported only on AVX-512, BWI
17090   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17091     return false;
17092
17093   if (VT.is512BitVector() || Subtarget->hasVLX())
17094     return true;
17095
17096   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17097   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17098   return (Opcode == ISD::SRA) ? AShift : LShift;
17099 }
17100
17101 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17102                                          const X86Subtarget *Subtarget) {
17103   MVT VT = Op.getSimpleValueType();
17104   SDLoc dl(Op);
17105   SDValue R = Op.getOperand(0);
17106   SDValue Amt = Op.getOperand(1);
17107
17108   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17109     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17110
17111   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17112     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17113     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17114     SDValue Ex = DAG.getBitcast(ExVT, R);
17115
17116     if (ShiftAmt >= 32) {
17117       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17118       SDValue Upper =
17119           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17120       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17121                                                  ShiftAmt - 32, DAG);
17122       if (VT == MVT::v2i64)
17123         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17124       if (VT == MVT::v4i64)
17125         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17126                                   {9, 1, 11, 3, 13, 5, 15, 7});
17127     } else {
17128       // SRA upper i32, SHL whole i64 and select lower i32.
17129       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17130                                                  ShiftAmt, DAG);
17131       SDValue Lower =
17132           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17133       Lower = DAG.getBitcast(ExVT, Lower);
17134       if (VT == MVT::v2i64)
17135         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17136       if (VT == MVT::v4i64)
17137         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17138                                   {8, 1, 10, 3, 12, 5, 14, 7});
17139     }
17140     return DAG.getBitcast(VT, Ex);
17141   };
17142
17143   // Optimize shl/srl/sra with constant shift amount.
17144   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17145     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17146       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17147
17148       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17149         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17150
17151       // i64 SRA needs to be performed as partial shifts.
17152       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17153           Op.getOpcode() == ISD::SRA)
17154         return ArithmeticShiftRight64(ShiftAmt);
17155
17156       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17157         unsigned NumElts = VT.getVectorNumElements();
17158         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17159
17160         if (Op.getOpcode() == ISD::SHL) {
17161           // Simple i8 add case
17162           if (ShiftAmt == 1)
17163             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17164
17165           // Make a large shift.
17166           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17167                                                    R, ShiftAmt, DAG);
17168           SHL = DAG.getBitcast(VT, SHL);
17169           // Zero out the rightmost bits.
17170           SmallVector<SDValue, 32> V(
17171               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17172           return DAG.getNode(ISD::AND, dl, VT, SHL,
17173                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17174         }
17175         if (Op.getOpcode() == ISD::SRL) {
17176           // Make a large shift.
17177           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17178                                                    R, ShiftAmt, DAG);
17179           SRL = DAG.getBitcast(VT, SRL);
17180           // Zero out the leftmost bits.
17181           SmallVector<SDValue, 32> V(
17182               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17183           return DAG.getNode(ISD::AND, dl, VT, SRL,
17184                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17185         }
17186         if (Op.getOpcode() == ISD::SRA) {
17187           if (ShiftAmt == 7) {
17188             // R s>> 7  ===  R s< 0
17189             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17190             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17191           }
17192
17193           // R s>> a === ((R u>> a) ^ m) - m
17194           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17195           SmallVector<SDValue, 32> V(NumElts,
17196                                      DAG.getConstant(128 >> ShiftAmt, dl,
17197                                                      MVT::i8));
17198           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17199           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17200           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17201           return Res;
17202         }
17203         llvm_unreachable("Unknown shift opcode.");
17204       }
17205     }
17206   }
17207
17208   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17209   if (!Subtarget->is64Bit() &&
17210       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17211       Amt.getOpcode() == ISD::BITCAST &&
17212       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17213     Amt = Amt.getOperand(0);
17214     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17215                      VT.getVectorNumElements();
17216     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17217     uint64_t ShiftAmt = 0;
17218     for (unsigned i = 0; i != Ratio; ++i) {
17219       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17220       if (!C)
17221         return SDValue();
17222       // 6 == Log2(64)
17223       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17224     }
17225     // Check remaining shift amounts.
17226     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17227       uint64_t ShAmt = 0;
17228       for (unsigned j = 0; j != Ratio; ++j) {
17229         ConstantSDNode *C =
17230           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17231         if (!C)
17232           return SDValue();
17233         // 6 == Log2(64)
17234         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17235       }
17236       if (ShAmt != ShiftAmt)
17237         return SDValue();
17238     }
17239
17240     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17241       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17242
17243     if (Op.getOpcode() == ISD::SRA)
17244       return ArithmeticShiftRight64(ShiftAmt);
17245   }
17246
17247   return SDValue();
17248 }
17249
17250 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17251                                         const X86Subtarget* Subtarget) {
17252   MVT VT = Op.getSimpleValueType();
17253   SDLoc dl(Op);
17254   SDValue R = Op.getOperand(0);
17255   SDValue Amt = Op.getOperand(1);
17256
17257   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17258     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17259
17260   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17261     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17262
17263   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17264     SDValue BaseShAmt;
17265     EVT EltVT = VT.getVectorElementType();
17266
17267     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17268       // Check if this build_vector node is doing a splat.
17269       // If so, then set BaseShAmt equal to the splat value.
17270       BaseShAmt = BV->getSplatValue();
17271       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17272         BaseShAmt = SDValue();
17273     } else {
17274       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17275         Amt = Amt.getOperand(0);
17276
17277       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17278       if (SVN && SVN->isSplat()) {
17279         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17280         SDValue InVec = Amt.getOperand(0);
17281         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17282           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17283                  "Unexpected shuffle index found!");
17284           BaseShAmt = InVec.getOperand(SplatIdx);
17285         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17286            if (ConstantSDNode *C =
17287                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17288              if (C->getZExtValue() == SplatIdx)
17289                BaseShAmt = InVec.getOperand(1);
17290            }
17291         }
17292
17293         if (!BaseShAmt)
17294           // Avoid introducing an extract element from a shuffle.
17295           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17296                                   DAG.getIntPtrConstant(SplatIdx, dl));
17297       }
17298     }
17299
17300     if (BaseShAmt.getNode()) {
17301       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17302       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17303         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17304       else if (EltVT.bitsLT(MVT::i32))
17305         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17306
17307       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17308     }
17309   }
17310
17311   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17312   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17313       Amt.getOpcode() == ISD::BITCAST &&
17314       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17315     Amt = Amt.getOperand(0);
17316     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17317                      VT.getVectorNumElements();
17318     std::vector<SDValue> Vals(Ratio);
17319     for (unsigned i = 0; i != Ratio; ++i)
17320       Vals[i] = Amt.getOperand(i);
17321     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17322       for (unsigned j = 0; j != Ratio; ++j)
17323         if (Vals[j] != Amt.getOperand(i + j))
17324           return SDValue();
17325     }
17326
17327     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17328       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17329   }
17330   return SDValue();
17331 }
17332
17333 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17334                           SelectionDAG &DAG) {
17335   MVT VT = Op.getSimpleValueType();
17336   SDLoc dl(Op);
17337   SDValue R = Op.getOperand(0);
17338   SDValue Amt = Op.getOperand(1);
17339
17340   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17341   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17342
17343   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17344     return V;
17345
17346   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17347       return V;
17348
17349   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17350     return Op;
17351
17352   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17353   // shifts per-lane and then shuffle the partial results back together.
17354   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17355     // Splat the shift amounts so the scalar shifts above will catch it.
17356     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17357     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17358     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17359     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17360     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17361   }
17362
17363   // If possible, lower this packed shift into a vector multiply instead of
17364   // expanding it into a sequence of scalar shifts.
17365   // Do this only if the vector shift count is a constant build_vector.
17366   if (Op.getOpcode() == ISD::SHL &&
17367       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17368        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17369       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17370     SmallVector<SDValue, 8> Elts;
17371     EVT SVT = VT.getScalarType();
17372     unsigned SVTBits = SVT.getSizeInBits();
17373     const APInt &One = APInt(SVTBits, 1);
17374     unsigned NumElems = VT.getVectorNumElements();
17375
17376     for (unsigned i=0; i !=NumElems; ++i) {
17377       SDValue Op = Amt->getOperand(i);
17378       if (Op->getOpcode() == ISD::UNDEF) {
17379         Elts.push_back(Op);
17380         continue;
17381       }
17382
17383       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17384       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17385       uint64_t ShAmt = C.getZExtValue();
17386       if (ShAmt >= SVTBits) {
17387         Elts.push_back(DAG.getUNDEF(SVT));
17388         continue;
17389       }
17390       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17391     }
17392     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17393     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17394   }
17395
17396   // Lower SHL with variable shift amount.
17397   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17398     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17399
17400     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17401                      DAG.getConstant(0x3f800000U, dl, VT));
17402     Op = DAG.getBitcast(MVT::v4f32, Op);
17403     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17404     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17405   }
17406
17407   // If possible, lower this shift as a sequence of two shifts by
17408   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17409   // Example:
17410   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17411   //
17412   // Could be rewritten as:
17413   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17414   //
17415   // The advantage is that the two shifts from the example would be
17416   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17417   // the vector shift into four scalar shifts plus four pairs of vector
17418   // insert/extract.
17419   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17420       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17421     unsigned TargetOpcode = X86ISD::MOVSS;
17422     bool CanBeSimplified;
17423     // The splat value for the first packed shift (the 'X' from the example).
17424     SDValue Amt1 = Amt->getOperand(0);
17425     // The splat value for the second packed shift (the 'Y' from the example).
17426     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17427                                         Amt->getOperand(2);
17428
17429     // See if it is possible to replace this node with a sequence of
17430     // two shifts followed by a MOVSS/MOVSD
17431     if (VT == MVT::v4i32) {
17432       // Check if it is legal to use a MOVSS.
17433       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17434                         Amt2 == Amt->getOperand(3);
17435       if (!CanBeSimplified) {
17436         // Otherwise, check if we can still simplify this node using a MOVSD.
17437         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17438                           Amt->getOperand(2) == Amt->getOperand(3);
17439         TargetOpcode = X86ISD::MOVSD;
17440         Amt2 = Amt->getOperand(2);
17441       }
17442     } else {
17443       // Do similar checks for the case where the machine value type
17444       // is MVT::v8i16.
17445       CanBeSimplified = Amt1 == Amt->getOperand(1);
17446       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17447         CanBeSimplified = Amt2 == Amt->getOperand(i);
17448
17449       if (!CanBeSimplified) {
17450         TargetOpcode = X86ISD::MOVSD;
17451         CanBeSimplified = true;
17452         Amt2 = Amt->getOperand(4);
17453         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17454           CanBeSimplified = Amt1 == Amt->getOperand(i);
17455         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17456           CanBeSimplified = Amt2 == Amt->getOperand(j);
17457       }
17458     }
17459
17460     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17461         isa<ConstantSDNode>(Amt2)) {
17462       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17463       EVT CastVT = MVT::v4i32;
17464       SDValue Splat1 =
17465         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17466       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17467       SDValue Splat2 =
17468         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17469       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17470       if (TargetOpcode == X86ISD::MOVSD)
17471         CastVT = MVT::v2i64;
17472       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17473       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17474       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17475                                             BitCast1, DAG);
17476       return DAG.getBitcast(VT, Result);
17477     }
17478   }
17479
17480   // v4i32 Non Uniform Shifts.
17481   // If the shift amount is constant we can shift each lane using the SSE2
17482   // immediate shifts, else we need to zero-extend each lane to the lower i64
17483   // and shift using the SSE2 variable shifts.
17484   // The separate results can then be blended together.
17485   if (VT == MVT::v4i32) {
17486     unsigned Opc = Op.getOpcode();
17487     SDValue Amt0, Amt1, Amt2, Amt3;
17488     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17489       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17490       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17491       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17492       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17493     } else {
17494       // ISD::SHL is handled above but we include it here for completeness.
17495       switch (Opc) {
17496       default:
17497         llvm_unreachable("Unknown target vector shift node");
17498       case ISD::SHL:
17499         Opc = X86ISD::VSHL;
17500         break;
17501       case ISD::SRL:
17502         Opc = X86ISD::VSRL;
17503         break;
17504       case ISD::SRA:
17505         Opc = X86ISD::VSRA;
17506         break;
17507       }
17508       // The SSE2 shifts use the lower i64 as the same shift amount for
17509       // all lanes and the upper i64 is ignored. These shuffle masks
17510       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17511       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17512       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17513       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17514       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17515       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17516     }
17517
17518     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17519     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17520     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17521     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17522     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17523     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17524     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17525   }
17526
17527   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17528     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17529     unsigned ShiftOpcode = Op->getOpcode();
17530
17531     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17532       // On SSE41 targets we make use of the fact that VSELECT lowers
17533       // to PBLENDVB which selects bytes based just on the sign bit.
17534       if (Subtarget->hasSSE41()) {
17535         V0 = DAG.getBitcast(VT, V0);
17536         V1 = DAG.getBitcast(VT, V1);
17537         Sel = DAG.getBitcast(VT, Sel);
17538         return DAG.getBitcast(SelVT,
17539                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17540       }
17541       // On pre-SSE41 targets we test for the sign bit by comparing to
17542       // zero - a negative value will set all bits of the lanes to true
17543       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17544       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17545       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17546       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17547     };
17548
17549     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17550     // We can safely do this using i16 shifts as we're only interested in
17551     // the 3 lower bits of each byte.
17552     Amt = DAG.getBitcast(ExtVT, Amt);
17553     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17554     Amt = DAG.getBitcast(VT, Amt);
17555
17556     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17557       // r = VSELECT(r, shift(r, 4), a);
17558       SDValue M =
17559           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17560       R = SignBitSelect(VT, Amt, M, R);
17561
17562       // a += a
17563       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17564
17565       // r = VSELECT(r, shift(r, 2), a);
17566       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17567       R = SignBitSelect(VT, Amt, M, R);
17568
17569       // a += a
17570       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17571
17572       // return VSELECT(r, shift(r, 1), a);
17573       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17574       R = SignBitSelect(VT, Amt, M, R);
17575       return R;
17576     }
17577
17578     if (Op->getOpcode() == ISD::SRA) {
17579       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17580       // so we can correctly sign extend. We don't care what happens to the
17581       // lower byte.
17582       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17583       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17584       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17585       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17586       ALo = DAG.getBitcast(ExtVT, ALo);
17587       AHi = DAG.getBitcast(ExtVT, AHi);
17588       RLo = DAG.getBitcast(ExtVT, RLo);
17589       RHi = DAG.getBitcast(ExtVT, RHi);
17590
17591       // r = VSELECT(r, shift(r, 4), a);
17592       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17593                                 DAG.getConstant(4, dl, ExtVT));
17594       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17595                                 DAG.getConstant(4, dl, ExtVT));
17596       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17597       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17598
17599       // a += a
17600       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17601       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17602
17603       // r = VSELECT(r, shift(r, 2), a);
17604       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17605                         DAG.getConstant(2, dl, ExtVT));
17606       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17607                         DAG.getConstant(2, dl, ExtVT));
17608       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17609       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17610
17611       // a += a
17612       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17613       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17614
17615       // r = VSELECT(r, shift(r, 1), a);
17616       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17617                         DAG.getConstant(1, dl, ExtVT));
17618       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17619                         DAG.getConstant(1, dl, ExtVT));
17620       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17621       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17622
17623       // Logical shift the result back to the lower byte, leaving a zero upper
17624       // byte
17625       // meaning that we can safely pack with PACKUSWB.
17626       RLo =
17627           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17628       RHi =
17629           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17630       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17631     }
17632   }
17633
17634   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17635   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17636   // solution better.
17637   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17638     MVT ExtVT = MVT::v8i32;
17639     unsigned ExtOpc =
17640         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17641     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17642     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17643     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17644                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17645   }
17646
17647   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17648     MVT ExtVT = MVT::v8i32;
17649     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17650     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17651     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17652     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17653     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17654     ALo = DAG.getBitcast(ExtVT, ALo);
17655     AHi = DAG.getBitcast(ExtVT, AHi);
17656     RLo = DAG.getBitcast(ExtVT, RLo);
17657     RHi = DAG.getBitcast(ExtVT, RHi);
17658     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17659     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17660     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17661     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17662     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17663   }
17664
17665   if (VT == MVT::v8i16) {
17666     unsigned ShiftOpcode = Op->getOpcode();
17667
17668     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17669       // On SSE41 targets we make use of the fact that VSELECT lowers
17670       // to PBLENDVB which selects bytes based just on the sign bit.
17671       if (Subtarget->hasSSE41()) {
17672         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17673         V0 = DAG.getBitcast(ExtVT, V0);
17674         V1 = DAG.getBitcast(ExtVT, V1);
17675         Sel = DAG.getBitcast(ExtVT, Sel);
17676         return DAG.getBitcast(
17677             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17678       }
17679       // On pre-SSE41 targets we splat the sign bit - a negative value will
17680       // set all bits of the lanes to true and VSELECT uses that in
17681       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17682       SDValue C =
17683           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17684       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17685     };
17686
17687     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17688     if (Subtarget->hasSSE41()) {
17689       // On SSE41 targets we need to replicate the shift mask in both
17690       // bytes for PBLENDVB.
17691       Amt = DAG.getNode(
17692           ISD::OR, dl, VT,
17693           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17694           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17695     } else {
17696       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17697     }
17698
17699     // r = VSELECT(r, shift(r, 8), a);
17700     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17701     R = SignBitSelect(Amt, M, R);
17702
17703     // a += a
17704     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17705
17706     // r = VSELECT(r, shift(r, 4), a);
17707     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17708     R = SignBitSelect(Amt, M, R);
17709
17710     // a += a
17711     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17712
17713     // r = VSELECT(r, shift(r, 2), a);
17714     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17715     R = SignBitSelect(Amt, M, R);
17716
17717     // a += a
17718     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17719
17720     // return VSELECT(r, shift(r, 1), a);
17721     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17722     R = SignBitSelect(Amt, M, R);
17723     return R;
17724   }
17725
17726   // Decompose 256-bit shifts into smaller 128-bit shifts.
17727   if (VT.is256BitVector()) {
17728     unsigned NumElems = VT.getVectorNumElements();
17729     MVT EltVT = VT.getVectorElementType();
17730     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17731
17732     // Extract the two vectors
17733     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17734     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17735
17736     // Recreate the shift amount vectors
17737     SDValue Amt1, Amt2;
17738     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17739       // Constant shift amount
17740       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17741       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17742       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17743
17744       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17745       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17746     } else {
17747       // Variable shift amount
17748       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17749       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17750     }
17751
17752     // Issue new vector shifts for the smaller types
17753     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17754     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17755
17756     // Concatenate the result back
17757     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17758   }
17759
17760   return SDValue();
17761 }
17762
17763 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17764   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17765   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17766   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17767   // has only one use.
17768   SDNode *N = Op.getNode();
17769   SDValue LHS = N->getOperand(0);
17770   SDValue RHS = N->getOperand(1);
17771   unsigned BaseOp = 0;
17772   unsigned Cond = 0;
17773   SDLoc DL(Op);
17774   switch (Op.getOpcode()) {
17775   default: llvm_unreachable("Unknown ovf instruction!");
17776   case ISD::SADDO:
17777     // A subtract of one will be selected as a INC. Note that INC doesn't
17778     // set CF, so we can't do this for UADDO.
17779     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17780       if (C->isOne()) {
17781         BaseOp = X86ISD::INC;
17782         Cond = X86::COND_O;
17783         break;
17784       }
17785     BaseOp = X86ISD::ADD;
17786     Cond = X86::COND_O;
17787     break;
17788   case ISD::UADDO:
17789     BaseOp = X86ISD::ADD;
17790     Cond = X86::COND_B;
17791     break;
17792   case ISD::SSUBO:
17793     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17794     // set CF, so we can't do this for USUBO.
17795     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17796       if (C->isOne()) {
17797         BaseOp = X86ISD::DEC;
17798         Cond = X86::COND_O;
17799         break;
17800       }
17801     BaseOp = X86ISD::SUB;
17802     Cond = X86::COND_O;
17803     break;
17804   case ISD::USUBO:
17805     BaseOp = X86ISD::SUB;
17806     Cond = X86::COND_B;
17807     break;
17808   case ISD::SMULO:
17809     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17810     Cond = X86::COND_O;
17811     break;
17812   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17813     if (N->getValueType(0) == MVT::i8) {
17814       BaseOp = X86ISD::UMUL8;
17815       Cond = X86::COND_O;
17816       break;
17817     }
17818     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17819                                  MVT::i32);
17820     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17821
17822     SDValue SetCC =
17823       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17824                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17825                   SDValue(Sum.getNode(), 2));
17826
17827     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17828   }
17829   }
17830
17831   // Also sets EFLAGS.
17832   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17833   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17834
17835   SDValue SetCC =
17836     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17837                 DAG.getConstant(Cond, DL, MVT::i32),
17838                 SDValue(Sum.getNode(), 1));
17839
17840   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17841 }
17842
17843 /// Returns true if the operand type is exactly twice the native width, and
17844 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17845 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17846 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17847 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17848   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17849
17850   if (OpWidth == 64)
17851     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17852   else if (OpWidth == 128)
17853     return Subtarget->hasCmpxchg16b();
17854   else
17855     return false;
17856 }
17857
17858 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17859   return needsCmpXchgNb(SI->getValueOperand()->getType());
17860 }
17861
17862 // Note: this turns large loads into lock cmpxchg8b/16b.
17863 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17864 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17865   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17866   return needsCmpXchgNb(PTy->getElementType());
17867 }
17868
17869 TargetLoweringBase::AtomicRMWExpansionKind
17870 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17871   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17872   const Type *MemType = AI->getType();
17873
17874   // If the operand is too big, we must see if cmpxchg8/16b is available
17875   // and default to library calls otherwise.
17876   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17877     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17878                                    : AtomicRMWExpansionKind::None;
17879   }
17880
17881   AtomicRMWInst::BinOp Op = AI->getOperation();
17882   switch (Op) {
17883   default:
17884     llvm_unreachable("Unknown atomic operation");
17885   case AtomicRMWInst::Xchg:
17886   case AtomicRMWInst::Add:
17887   case AtomicRMWInst::Sub:
17888     // It's better to use xadd, xsub or xchg for these in all cases.
17889     return AtomicRMWExpansionKind::None;
17890   case AtomicRMWInst::Or:
17891   case AtomicRMWInst::And:
17892   case AtomicRMWInst::Xor:
17893     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17894     // prefix to a normal instruction for these operations.
17895     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17896                             : AtomicRMWExpansionKind::None;
17897   case AtomicRMWInst::Nand:
17898   case AtomicRMWInst::Max:
17899   case AtomicRMWInst::Min:
17900   case AtomicRMWInst::UMax:
17901   case AtomicRMWInst::UMin:
17902     // These always require a non-trivial set of data operations on x86. We must
17903     // use a cmpxchg loop.
17904     return AtomicRMWExpansionKind::CmpXChg;
17905   }
17906 }
17907
17908 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17909   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17910   // no-sse2). There isn't any reason to disable it if the target processor
17911   // supports it.
17912   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17913 }
17914
17915 LoadInst *
17916 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17917   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17918   const Type *MemType = AI->getType();
17919   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17920   // there is no benefit in turning such RMWs into loads, and it is actually
17921   // harmful as it introduces a mfence.
17922   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17923     return nullptr;
17924
17925   auto Builder = IRBuilder<>(AI);
17926   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17927   auto SynchScope = AI->getSynchScope();
17928   // We must restrict the ordering to avoid generating loads with Release or
17929   // ReleaseAcquire orderings.
17930   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17931   auto Ptr = AI->getPointerOperand();
17932
17933   // Before the load we need a fence. Here is an example lifted from
17934   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17935   // is required:
17936   // Thread 0:
17937   //   x.store(1, relaxed);
17938   //   r1 = y.fetch_add(0, release);
17939   // Thread 1:
17940   //   y.fetch_add(42, acquire);
17941   //   r2 = x.load(relaxed);
17942   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17943   // lowered to just a load without a fence. A mfence flushes the store buffer,
17944   // making the optimization clearly correct.
17945   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17946   // otherwise, we might be able to be more agressive on relaxed idempotent
17947   // rmw. In practice, they do not look useful, so we don't try to be
17948   // especially clever.
17949   if (SynchScope == SingleThread)
17950     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17951     // the IR level, so we must wrap it in an intrinsic.
17952     return nullptr;
17953
17954   if (!hasMFENCE(*Subtarget))
17955     // FIXME: it might make sense to use a locked operation here but on a
17956     // different cache-line to prevent cache-line bouncing. In practice it
17957     // is probably a small win, and x86 processors without mfence are rare
17958     // enough that we do not bother.
17959     return nullptr;
17960
17961   Function *MFence =
17962       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17963   Builder.CreateCall(MFence, {});
17964
17965   // Finally we can emit the atomic load.
17966   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17967           AI->getType()->getPrimitiveSizeInBits());
17968   Loaded->setAtomic(Order, SynchScope);
17969   AI->replaceAllUsesWith(Loaded);
17970   AI->eraseFromParent();
17971   return Loaded;
17972 }
17973
17974 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17975                                  SelectionDAG &DAG) {
17976   SDLoc dl(Op);
17977   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17978     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17979   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17980     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17981
17982   // The only fence that needs an instruction is a sequentially-consistent
17983   // cross-thread fence.
17984   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17985     if (hasMFENCE(*Subtarget))
17986       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17987
17988     SDValue Chain = Op.getOperand(0);
17989     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17990     SDValue Ops[] = {
17991       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17992       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17993       DAG.getRegister(0, MVT::i32),            // Index
17994       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17995       DAG.getRegister(0, MVT::i32),            // Segment.
17996       Zero,
17997       Chain
17998     };
17999     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
18000     return SDValue(Res, 0);
18001   }
18002
18003   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
18004   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
18005 }
18006
18007 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
18008                              SelectionDAG &DAG) {
18009   MVT T = Op.getSimpleValueType();
18010   SDLoc DL(Op);
18011   unsigned Reg = 0;
18012   unsigned size = 0;
18013   switch(T.SimpleTy) {
18014   default: llvm_unreachable("Invalid value type!");
18015   case MVT::i8:  Reg = X86::AL;  size = 1; break;
18016   case MVT::i16: Reg = X86::AX;  size = 2; break;
18017   case MVT::i32: Reg = X86::EAX; size = 4; break;
18018   case MVT::i64:
18019     assert(Subtarget->is64Bit() && "Node not type legal!");
18020     Reg = X86::RAX; size = 8;
18021     break;
18022   }
18023   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
18024                                   Op.getOperand(2), SDValue());
18025   SDValue Ops[] = { cpIn.getValue(0),
18026                     Op.getOperand(1),
18027                     Op.getOperand(3),
18028                     DAG.getTargetConstant(size, DL, MVT::i8),
18029                     cpIn.getValue(1) };
18030   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18031   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
18032   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
18033                                            Ops, T, MMO);
18034
18035   SDValue cpOut =
18036     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18037   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18038                                       MVT::i32, cpOut.getValue(2));
18039   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18040                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18041                                 EFLAGS);
18042
18043   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18044   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18045   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18046   return SDValue();
18047 }
18048
18049 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18050                             SelectionDAG &DAG) {
18051   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18052   MVT DstVT = Op.getSimpleValueType();
18053
18054   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18055     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18056     if (DstVT != MVT::f64)
18057       // This conversion needs to be expanded.
18058       return SDValue();
18059
18060     SDValue InVec = Op->getOperand(0);
18061     SDLoc dl(Op);
18062     unsigned NumElts = SrcVT.getVectorNumElements();
18063     EVT SVT = SrcVT.getVectorElementType();
18064
18065     // Widen the vector in input in the case of MVT::v2i32.
18066     // Example: from MVT::v2i32 to MVT::v4i32.
18067     SmallVector<SDValue, 16> Elts;
18068     for (unsigned i = 0, e = NumElts; i != e; ++i)
18069       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18070                                  DAG.getIntPtrConstant(i, dl)));
18071
18072     // Explicitly mark the extra elements as Undef.
18073     Elts.append(NumElts, DAG.getUNDEF(SVT));
18074
18075     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18076     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18077     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18078     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18079                        DAG.getIntPtrConstant(0, dl));
18080   }
18081
18082   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18083          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18084   assert((DstVT == MVT::i64 ||
18085           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18086          "Unexpected custom BITCAST");
18087   // i64 <=> MMX conversions are Legal.
18088   if (SrcVT==MVT::i64 && DstVT.isVector())
18089     return Op;
18090   if (DstVT==MVT::i64 && SrcVT.isVector())
18091     return Op;
18092   // MMX <=> MMX conversions are Legal.
18093   if (SrcVT.isVector() && DstVT.isVector())
18094     return Op;
18095   // All other conversions need to be expanded.
18096   return SDValue();
18097 }
18098
18099 /// Compute the horizontal sum of bytes in V for the elements of VT.
18100 ///
18101 /// Requires V to be a byte vector and VT to be an integer vector type with
18102 /// wider elements than V's type. The width of the elements of VT determines
18103 /// how many bytes of V are summed horizontally to produce each element of the
18104 /// result.
18105 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18106                                       const X86Subtarget *Subtarget,
18107                                       SelectionDAG &DAG) {
18108   SDLoc DL(V);
18109   MVT ByteVecVT = V.getSimpleValueType();
18110   MVT EltVT = VT.getVectorElementType();
18111   int NumElts = VT.getVectorNumElements();
18112   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18113          "Expected value to have byte element type.");
18114   assert(EltVT != MVT::i8 &&
18115          "Horizontal byte sum only makes sense for wider elements!");
18116   unsigned VecSize = VT.getSizeInBits();
18117   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18118
18119   // PSADBW instruction horizontally add all bytes and leave the result in i64
18120   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18121   if (EltVT == MVT::i64) {
18122     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18123     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18124     return DAG.getBitcast(VT, V);
18125   }
18126
18127   if (EltVT == MVT::i32) {
18128     // We unpack the low half and high half into i32s interleaved with zeros so
18129     // that we can use PSADBW to horizontally sum them. The most useful part of
18130     // this is that it lines up the results of two PSADBW instructions to be
18131     // two v2i64 vectors which concatenated are the 4 population counts. We can
18132     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18133     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18134     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18135     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18136
18137     // Do the horizontal sums into two v2i64s.
18138     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18139     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18140                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18141     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18142                        DAG.getBitcast(ByteVecVT, High), Zeros);
18143
18144     // Merge them together.
18145     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18146     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18147                     DAG.getBitcast(ShortVecVT, Low),
18148                     DAG.getBitcast(ShortVecVT, High));
18149
18150     return DAG.getBitcast(VT, V);
18151   }
18152
18153   // The only element type left is i16.
18154   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18155
18156   // To obtain pop count for each i16 element starting from the pop count for
18157   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18158   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18159   // directly supported.
18160   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18161   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18162   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18163   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18164                   DAG.getBitcast(ByteVecVT, V));
18165   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18166 }
18167
18168 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18169                                         const X86Subtarget *Subtarget,
18170                                         SelectionDAG &DAG) {
18171   MVT VT = Op.getSimpleValueType();
18172   MVT EltVT = VT.getVectorElementType();
18173   unsigned VecSize = VT.getSizeInBits();
18174
18175   // Implement a lookup table in register by using an algorithm based on:
18176   // http://wm.ite.pl/articles/sse-popcount.html
18177   //
18178   // The general idea is that every lower byte nibble in the input vector is an
18179   // index into a in-register pre-computed pop count table. We then split up the
18180   // input vector in two new ones: (1) a vector with only the shifted-right
18181   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18182   // masked out higher ones) for each byte. PSHUB is used separately with both
18183   // to index the in-register table. Next, both are added and the result is a
18184   // i8 vector where each element contains the pop count for input byte.
18185   //
18186   // To obtain the pop count for elements != i8, we follow up with the same
18187   // approach and use additional tricks as described below.
18188   //
18189   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18190                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18191                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18192                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18193
18194   int NumByteElts = VecSize / 8;
18195   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18196   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18197   SmallVector<SDValue, 16> LUTVec;
18198   for (int i = 0; i < NumByteElts; ++i)
18199     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18200   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18201   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18202                                   DAG.getConstant(0x0F, DL, MVT::i8));
18203   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18204
18205   // High nibbles
18206   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18207   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18208   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18209
18210   // Low nibbles
18211   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18212
18213   // The input vector is used as the shuffle mask that index elements into the
18214   // LUT. After counting low and high nibbles, add the vector to obtain the
18215   // final pop count per i8 element.
18216   SDValue HighPopCnt =
18217       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18218   SDValue LowPopCnt =
18219       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18220   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18221
18222   if (EltVT == MVT::i8)
18223     return PopCnt;
18224
18225   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18226 }
18227
18228 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18229                                        const X86Subtarget *Subtarget,
18230                                        SelectionDAG &DAG) {
18231   MVT VT = Op.getSimpleValueType();
18232   assert(VT.is128BitVector() &&
18233          "Only 128-bit vector bitmath lowering supported.");
18234
18235   int VecSize = VT.getSizeInBits();
18236   MVT EltVT = VT.getVectorElementType();
18237   int Len = EltVT.getSizeInBits();
18238
18239   // This is the vectorized version of the "best" algorithm from
18240   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18241   // with a minor tweak to use a series of adds + shifts instead of vector
18242   // multiplications. Implemented for all integer vector types. We only use
18243   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18244   // much faster, even faster than using native popcnt instructions.
18245
18246   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18247     MVT VT = V.getSimpleValueType();
18248     SmallVector<SDValue, 32> Shifters(
18249         VT.getVectorNumElements(),
18250         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18251     return DAG.getNode(OpCode, DL, VT, V,
18252                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18253   };
18254   auto GetMask = [&](SDValue V, APInt Mask) {
18255     MVT VT = V.getSimpleValueType();
18256     SmallVector<SDValue, 32> Masks(
18257         VT.getVectorNumElements(),
18258         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18259     return DAG.getNode(ISD::AND, DL, VT, V,
18260                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18261   };
18262
18263   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18264   // x86, so set the SRL type to have elements at least i16 wide. This is
18265   // correct because all of our SRLs are followed immediately by a mask anyways
18266   // that handles any bits that sneak into the high bits of the byte elements.
18267   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18268
18269   SDValue V = Op;
18270
18271   // v = v - ((v >> 1) & 0x55555555...)
18272   SDValue Srl =
18273       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18274   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18275   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18276
18277   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18278   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18279   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18280   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18281   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18282
18283   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18284   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18285   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18286   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18287
18288   // At this point, V contains the byte-wise population count, and we are
18289   // merely doing a horizontal sum if necessary to get the wider element
18290   // counts.
18291   if (EltVT == MVT::i8)
18292     return V;
18293
18294   return LowerHorizontalByteSum(
18295       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18296       DAG);
18297 }
18298
18299 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18300                                 SelectionDAG &DAG) {
18301   MVT VT = Op.getSimpleValueType();
18302   // FIXME: Need to add AVX-512 support here!
18303   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18304          "Unknown CTPOP type to handle");
18305   SDLoc DL(Op.getNode());
18306   SDValue Op0 = Op.getOperand(0);
18307
18308   if (!Subtarget->hasSSSE3()) {
18309     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18310     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18311     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18312   }
18313
18314   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18315     unsigned NumElems = VT.getVectorNumElements();
18316
18317     // Extract each 128-bit vector, compute pop count and concat the result.
18318     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18319     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18320
18321     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18322                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18323                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18324   }
18325
18326   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18327 }
18328
18329 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18330                           SelectionDAG &DAG) {
18331   assert(Op.getValueType().isVector() &&
18332          "We only do custom lowering for vector population count.");
18333   return LowerVectorCTPOP(Op, Subtarget, DAG);
18334 }
18335
18336 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18337   SDNode *Node = Op.getNode();
18338   SDLoc dl(Node);
18339   EVT T = Node->getValueType(0);
18340   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18341                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18342   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18343                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18344                        Node->getOperand(0),
18345                        Node->getOperand(1), negOp,
18346                        cast<AtomicSDNode>(Node)->getMemOperand(),
18347                        cast<AtomicSDNode>(Node)->getOrdering(),
18348                        cast<AtomicSDNode>(Node)->getSynchScope());
18349 }
18350
18351 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18352   SDNode *Node = Op.getNode();
18353   SDLoc dl(Node);
18354   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18355
18356   // Convert seq_cst store -> xchg
18357   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18358   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18359   //        (The only way to get a 16-byte store is cmpxchg16b)
18360   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18361   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18362       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18363     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18364                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18365                                  Node->getOperand(0),
18366                                  Node->getOperand(1), Node->getOperand(2),
18367                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18368                                  cast<AtomicSDNode>(Node)->getOrdering(),
18369                                  cast<AtomicSDNode>(Node)->getSynchScope());
18370     return Swap.getValue(1);
18371   }
18372   // Other atomic stores have a simple pattern.
18373   return Op;
18374 }
18375
18376 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18377   EVT VT = Op.getNode()->getSimpleValueType(0);
18378
18379   // Let legalize expand this if it isn't a legal type yet.
18380   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18381     return SDValue();
18382
18383   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18384
18385   unsigned Opc;
18386   bool ExtraOp = false;
18387   switch (Op.getOpcode()) {
18388   default: llvm_unreachable("Invalid code");
18389   case ISD::ADDC: Opc = X86ISD::ADD; break;
18390   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18391   case ISD::SUBC: Opc = X86ISD::SUB; break;
18392   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18393   }
18394
18395   if (!ExtraOp)
18396     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18397                        Op.getOperand(1));
18398   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18399                      Op.getOperand(1), Op.getOperand(2));
18400 }
18401
18402 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18403                             SelectionDAG &DAG) {
18404   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18405
18406   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18407   // which returns the values as { float, float } (in XMM0) or
18408   // { double, double } (which is returned in XMM0, XMM1).
18409   SDLoc dl(Op);
18410   SDValue Arg = Op.getOperand(0);
18411   EVT ArgVT = Arg.getValueType();
18412   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18413
18414   TargetLowering::ArgListTy Args;
18415   TargetLowering::ArgListEntry Entry;
18416
18417   Entry.Node = Arg;
18418   Entry.Ty = ArgTy;
18419   Entry.isSExt = false;
18420   Entry.isZExt = false;
18421   Args.push_back(Entry);
18422
18423   bool isF64 = ArgVT == MVT::f64;
18424   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18425   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18426   // the results are returned via SRet in memory.
18427   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18428   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18429   SDValue Callee =
18430       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18431
18432   Type *RetTy = isF64
18433     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18434     : (Type*)VectorType::get(ArgTy, 4);
18435
18436   TargetLowering::CallLoweringInfo CLI(DAG);
18437   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18438     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18439
18440   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18441
18442   if (isF64)
18443     // Returned in xmm0 and xmm1.
18444     return CallResult.first;
18445
18446   // Returned in bits 0:31 and 32:64 xmm0.
18447   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18448                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18449   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18450                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18451   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18452   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18453 }
18454
18455 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18456                              SelectionDAG &DAG) {
18457   assert(Subtarget->hasAVX512() &&
18458          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18459
18460   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18461   EVT VT = N->getValue().getValueType();
18462   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18463   SDLoc dl(Op);
18464
18465   // X86 scatter kills mask register, so its type should be added to
18466   // the list of return values
18467   if (N->getNumValues() == 1) {
18468     SDValue Index = N->getIndex();
18469     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18470         !Index.getValueType().is512BitVector())
18471       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18472
18473     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18474     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18475                       N->getOperand(3), Index };
18476
18477     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18478     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18479     return SDValue(NewScatter.getNode(), 0);
18480   }
18481   return Op;
18482 }
18483
18484 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18485                             SelectionDAG &DAG) {
18486   assert(Subtarget->hasAVX512() &&
18487          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18488
18489   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18490   EVT VT = Op.getValueType();
18491   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18492   SDLoc dl(Op);
18493
18494   SDValue Index = N->getIndex();
18495   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18496       !Index.getValueType().is512BitVector()) {
18497     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18498     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18499                       N->getOperand(3), Index };
18500     DAG.UpdateNodeOperands(N, Ops);
18501   }
18502   return Op;
18503 }
18504
18505 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18506                                                     SelectionDAG &DAG) const {
18507   // TODO: Eventually, the lowering of these nodes should be informed by or
18508   // deferred to the GC strategy for the function in which they appear. For
18509   // now, however, they must be lowered to something. Since they are logically
18510   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18511   // require special handling for these nodes), lower them as literal NOOPs for
18512   // the time being.
18513   SmallVector<SDValue, 2> Ops;
18514
18515   Ops.push_back(Op.getOperand(0));
18516   if (Op->getGluedNode())
18517     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18518
18519   SDLoc OpDL(Op);
18520   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18521   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18522
18523   return NOOP;
18524 }
18525
18526 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18527                                                   SelectionDAG &DAG) const {
18528   // TODO: Eventually, the lowering of these nodes should be informed by or
18529   // deferred to the GC strategy for the function in which they appear. For
18530   // now, however, they must be lowered to something. Since they are logically
18531   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18532   // require special handling for these nodes), lower them as literal NOOPs for
18533   // the time being.
18534   SmallVector<SDValue, 2> Ops;
18535
18536   Ops.push_back(Op.getOperand(0));
18537   if (Op->getGluedNode())
18538     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18539
18540   SDLoc OpDL(Op);
18541   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18542   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18543
18544   return NOOP;
18545 }
18546
18547 /// LowerOperation - Provide custom lowering hooks for some operations.
18548 ///
18549 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18550   switch (Op.getOpcode()) {
18551   default: llvm_unreachable("Should not custom lower this!");
18552   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18553   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18554     return LowerCMP_SWAP(Op, Subtarget, DAG);
18555   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18556   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18557   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18558   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18559   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18560   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18561   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18562   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18563   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18564   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18565   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18566   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18567   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18568   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18569   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18570   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18571   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18572   case ISD::SHL_PARTS:
18573   case ISD::SRA_PARTS:
18574   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18575   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18576   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18577   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18578   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18579   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18580   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18581   case ISD::SIGN_EXTEND_VECTOR_INREG:
18582     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18583   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18584   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18585   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18586   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18587   case ISD::FABS:
18588   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18589   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18590   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18591   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18592   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18593   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18594   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18595   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18596   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18597   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18598   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18599   case ISD::INTRINSIC_VOID:
18600   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18601   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18602   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18603   case ISD::FRAME_TO_ARGS_OFFSET:
18604                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18605   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18606   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18607   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18608   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18609   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18610   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18611   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18612   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18613   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18614   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18615   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18616   case ISD::UMUL_LOHI:
18617   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18618   case ISD::SRA:
18619   case ISD::SRL:
18620   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18621   case ISD::SADDO:
18622   case ISD::UADDO:
18623   case ISD::SSUBO:
18624   case ISD::USUBO:
18625   case ISD::SMULO:
18626   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18627   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18628   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18629   case ISD::ADDC:
18630   case ISD::ADDE:
18631   case ISD::SUBC:
18632   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18633   case ISD::ADD:                return LowerADD(Op, DAG);
18634   case ISD::SUB:                return LowerSUB(Op, DAG);
18635   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18636   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18637   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18638   case ISD::GC_TRANSITION_START:
18639                                 return LowerGC_TRANSITION_START(Op, DAG);
18640   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18641   }
18642 }
18643
18644 /// ReplaceNodeResults - Replace a node with an illegal result type
18645 /// with a new node built out of custom code.
18646 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18647                                            SmallVectorImpl<SDValue>&Results,
18648                                            SelectionDAG &DAG) const {
18649   SDLoc dl(N);
18650   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18651   switch (N->getOpcode()) {
18652   default:
18653     llvm_unreachable("Do not know how to custom type legalize this operation!");
18654   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18655   case X86ISD::FMINC:
18656   case X86ISD::FMIN:
18657   case X86ISD::FMAXC:
18658   case X86ISD::FMAX: {
18659     EVT VT = N->getValueType(0);
18660     if (VT != MVT::v2f32)
18661       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18662     SDValue UNDEF = DAG.getUNDEF(VT);
18663     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18664                               N->getOperand(0), UNDEF);
18665     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18666                               N->getOperand(1), UNDEF);
18667     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18668     return;
18669   }
18670   case ISD::SIGN_EXTEND_INREG:
18671   case ISD::ADDC:
18672   case ISD::ADDE:
18673   case ISD::SUBC:
18674   case ISD::SUBE:
18675     // We don't want to expand or promote these.
18676     return;
18677   case ISD::SDIV:
18678   case ISD::UDIV:
18679   case ISD::SREM:
18680   case ISD::UREM:
18681   case ISD::SDIVREM:
18682   case ISD::UDIVREM: {
18683     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18684     Results.push_back(V);
18685     return;
18686   }
18687   case ISD::FP_TO_SINT:
18688     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18689     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18690     if (N->getOperand(0).getValueType() == MVT::f16)
18691       break;
18692     // fallthrough
18693   case ISD::FP_TO_UINT: {
18694     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18695
18696     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18697       return;
18698
18699     std::pair<SDValue,SDValue> Vals =
18700         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18701     SDValue FIST = Vals.first, StackSlot = Vals.second;
18702     if (FIST.getNode()) {
18703       EVT VT = N->getValueType(0);
18704       // Return a load from the stack slot.
18705       if (StackSlot.getNode())
18706         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18707                                       MachinePointerInfo(),
18708                                       false, false, false, 0));
18709       else
18710         Results.push_back(FIST);
18711     }
18712     return;
18713   }
18714   case ISD::UINT_TO_FP: {
18715     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18716     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18717         N->getValueType(0) != MVT::v2f32)
18718       return;
18719     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18720                                  N->getOperand(0));
18721     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18722                                      MVT::f64);
18723     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18724     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18725                              DAG.getBitcast(MVT::v2i64, VBias));
18726     Or = DAG.getBitcast(MVT::v2f64, Or);
18727     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18728     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18729     return;
18730   }
18731   case ISD::FP_ROUND: {
18732     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18733         return;
18734     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18735     Results.push_back(V);
18736     return;
18737   }
18738   case ISD::FP_EXTEND: {
18739     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18740     // No other ValueType for FP_EXTEND should reach this point.
18741     assert(N->getValueType(0) == MVT::v2f32 &&
18742            "Do not know how to legalize this Node");
18743     return;
18744   }
18745   case ISD::INTRINSIC_W_CHAIN: {
18746     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18747     switch (IntNo) {
18748     default : llvm_unreachable("Do not know how to custom type "
18749                                "legalize this intrinsic operation!");
18750     case Intrinsic::x86_rdtsc:
18751       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18752                                      Results);
18753     case Intrinsic::x86_rdtscp:
18754       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18755                                      Results);
18756     case Intrinsic::x86_rdpmc:
18757       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18758     }
18759   }
18760   case ISD::READCYCLECOUNTER: {
18761     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18762                                    Results);
18763   }
18764   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18765     EVT T = N->getValueType(0);
18766     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18767     bool Regs64bit = T == MVT::i128;
18768     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18769     SDValue cpInL, cpInH;
18770     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18771                         DAG.getConstant(0, dl, HalfT));
18772     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18773                         DAG.getConstant(1, dl, HalfT));
18774     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18775                              Regs64bit ? X86::RAX : X86::EAX,
18776                              cpInL, SDValue());
18777     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18778                              Regs64bit ? X86::RDX : X86::EDX,
18779                              cpInH, cpInL.getValue(1));
18780     SDValue swapInL, swapInH;
18781     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18782                           DAG.getConstant(0, dl, HalfT));
18783     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18784                           DAG.getConstant(1, dl, HalfT));
18785     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18786                                Regs64bit ? X86::RBX : X86::EBX,
18787                                swapInL, cpInH.getValue(1));
18788     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18789                                Regs64bit ? X86::RCX : X86::ECX,
18790                                swapInH, swapInL.getValue(1));
18791     SDValue Ops[] = { swapInH.getValue(0),
18792                       N->getOperand(1),
18793                       swapInH.getValue(1) };
18794     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18795     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18796     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18797                                   X86ISD::LCMPXCHG8_DAG;
18798     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18799     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18800                                         Regs64bit ? X86::RAX : X86::EAX,
18801                                         HalfT, Result.getValue(1));
18802     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18803                                         Regs64bit ? X86::RDX : X86::EDX,
18804                                         HalfT, cpOutL.getValue(2));
18805     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18806
18807     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18808                                         MVT::i32, cpOutH.getValue(2));
18809     SDValue Success =
18810         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18811                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18812     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18813
18814     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18815     Results.push_back(Success);
18816     Results.push_back(EFLAGS.getValue(1));
18817     return;
18818   }
18819   case ISD::ATOMIC_SWAP:
18820   case ISD::ATOMIC_LOAD_ADD:
18821   case ISD::ATOMIC_LOAD_SUB:
18822   case ISD::ATOMIC_LOAD_AND:
18823   case ISD::ATOMIC_LOAD_OR:
18824   case ISD::ATOMIC_LOAD_XOR:
18825   case ISD::ATOMIC_LOAD_NAND:
18826   case ISD::ATOMIC_LOAD_MIN:
18827   case ISD::ATOMIC_LOAD_MAX:
18828   case ISD::ATOMIC_LOAD_UMIN:
18829   case ISD::ATOMIC_LOAD_UMAX:
18830   case ISD::ATOMIC_LOAD: {
18831     // Delegate to generic TypeLegalization. Situations we can really handle
18832     // should have already been dealt with by AtomicExpandPass.cpp.
18833     break;
18834   }
18835   case ISD::BITCAST: {
18836     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18837     EVT DstVT = N->getValueType(0);
18838     EVT SrcVT = N->getOperand(0)->getValueType(0);
18839
18840     if (SrcVT != MVT::f64 ||
18841         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18842       return;
18843
18844     unsigned NumElts = DstVT.getVectorNumElements();
18845     EVT SVT = DstVT.getVectorElementType();
18846     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18847     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18848                                    MVT::v2f64, N->getOperand(0));
18849     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18850
18851     if (ExperimentalVectorWideningLegalization) {
18852       // If we are legalizing vectors by widening, we already have the desired
18853       // legal vector type, just return it.
18854       Results.push_back(ToVecInt);
18855       return;
18856     }
18857
18858     SmallVector<SDValue, 8> Elts;
18859     for (unsigned i = 0, e = NumElts; i != e; ++i)
18860       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18861                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18862
18863     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18864   }
18865   }
18866 }
18867
18868 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18869   switch ((X86ISD::NodeType)Opcode) {
18870   case X86ISD::FIRST_NUMBER:       break;
18871   case X86ISD::BSF:                return "X86ISD::BSF";
18872   case X86ISD::BSR:                return "X86ISD::BSR";
18873   case X86ISD::SHLD:               return "X86ISD::SHLD";
18874   case X86ISD::SHRD:               return "X86ISD::SHRD";
18875   case X86ISD::FAND:               return "X86ISD::FAND";
18876   case X86ISD::FANDN:              return "X86ISD::FANDN";
18877   case X86ISD::FOR:                return "X86ISD::FOR";
18878   case X86ISD::FXOR:               return "X86ISD::FXOR";
18879   case X86ISD::FILD:               return "X86ISD::FILD";
18880   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18881   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18882   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18883   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18884   case X86ISD::FLD:                return "X86ISD::FLD";
18885   case X86ISD::FST:                return "X86ISD::FST";
18886   case X86ISD::CALL:               return "X86ISD::CALL";
18887   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18888   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18889   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18890   case X86ISD::BT:                 return "X86ISD::BT";
18891   case X86ISD::CMP:                return "X86ISD::CMP";
18892   case X86ISD::COMI:               return "X86ISD::COMI";
18893   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18894   case X86ISD::CMPM:               return "X86ISD::CMPM";
18895   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18896   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18897   case X86ISD::SETCC:              return "X86ISD::SETCC";
18898   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18899   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18900   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18901   case X86ISD::CMOV:               return "X86ISD::CMOV";
18902   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18903   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18904   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18905   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18906   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18907   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18908   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18909   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18910   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18911   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18912   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18913   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18914   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18915   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18916   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18917   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18918   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18919   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18920   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18921   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18922   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18923   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18924   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18925   case X86ISD::HADD:               return "X86ISD::HADD";
18926   case X86ISD::HSUB:               return "X86ISD::HSUB";
18927   case X86ISD::FHADD:              return "X86ISD::FHADD";
18928   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18929   case X86ISD::ABS:                return "X86ISD::ABS";
18930   case X86ISD::FMAX:               return "X86ISD::FMAX";
18931   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18932   case X86ISD::FMIN:               return "X86ISD::FMIN";
18933   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18934   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18935   case X86ISD::FMINC:              return "X86ISD::FMINC";
18936   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18937   case X86ISD::FRCP:               return "X86ISD::FRCP";
18938   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18939   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18940   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18941   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18942   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18943   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18944   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18945   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18946   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18947   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18948   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18949   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18950   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18951   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18952   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18953   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18954   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18955   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18956   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18957   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18958   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18959   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18960   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18961   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18962   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
18963   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18964   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18965   case X86ISD::VSHL:               return "X86ISD::VSHL";
18966   case X86ISD::VSRL:               return "X86ISD::VSRL";
18967   case X86ISD::VSRA:               return "X86ISD::VSRA";
18968   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18969   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18970   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18971   case X86ISD::CMPP:               return "X86ISD::CMPP";
18972   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18973   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18974   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18975   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18976   case X86ISD::ADD:                return "X86ISD::ADD";
18977   case X86ISD::SUB:                return "X86ISD::SUB";
18978   case X86ISD::ADC:                return "X86ISD::ADC";
18979   case X86ISD::SBB:                return "X86ISD::SBB";
18980   case X86ISD::SMUL:               return "X86ISD::SMUL";
18981   case X86ISD::UMUL:               return "X86ISD::UMUL";
18982   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18983   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18984   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18985   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18986   case X86ISD::INC:                return "X86ISD::INC";
18987   case X86ISD::DEC:                return "X86ISD::DEC";
18988   case X86ISD::OR:                 return "X86ISD::OR";
18989   case X86ISD::XOR:                return "X86ISD::XOR";
18990   case X86ISD::AND:                return "X86ISD::AND";
18991   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18992   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18993   case X86ISD::PTEST:              return "X86ISD::PTEST";
18994   case X86ISD::TESTP:              return "X86ISD::TESTP";
18995   case X86ISD::TESTM:              return "X86ISD::TESTM";
18996   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18997   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18998   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18999   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
19000   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
19001   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
19002   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
19003   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
19004   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
19005   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
19006   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
19007   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
19008   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
19009   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
19010   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
19011   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
19012   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
19013   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
19014   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
19015   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
19016   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
19017   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
19018   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
19019   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
19020   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
19021   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
19022   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
19023   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
19024   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
19025   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
19026   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
19027   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
19028   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
19029   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
19030   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
19031   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
19032   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
19033   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
19034   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19035   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19036   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19037   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19038   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19039   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19040   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19041   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19042   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19043   case X86ISD::SAHF:               return "X86ISD::SAHF";
19044   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19045   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19046   case X86ISD::VPMADDUBSW:         return "X86ISD::VPMADDUBSW";
19047   case X86ISD::VPMADDWD:           return "X86ISD::VPMADDWD";
19048   case X86ISD::FMADD:              return "X86ISD::FMADD";
19049   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19050   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19051   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19052   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19053   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19054   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19055   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19056   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19057   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19058   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19059   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19060   case X86ISD::VRNDSCALE:          return "X86ISD::VRNDSCALE";
19061   case X86ISD::VREDUCE:            return "X86ISD::VREDUCE";
19062   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19063   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19064   case X86ISD::XTEST:              return "X86ISD::XTEST";
19065   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19066   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19067   case X86ISD::SELECT:             return "X86ISD::SELECT";
19068   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19069   case X86ISD::RCP28:              return "X86ISD::RCP28";
19070   case X86ISD::EXP2:               return "X86ISD::EXP2";
19071   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19072   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19073   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19074   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19075   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19076   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19077   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19078   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19079   case X86ISD::ADDS:               return "X86ISD::ADDS";
19080   case X86ISD::SUBS:               return "X86ISD::SUBS";
19081   case X86ISD::AVG:                return "X86ISD::AVG";
19082   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19083   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19084   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19085   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19086   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19087   }
19088   return nullptr;
19089 }
19090
19091 // isLegalAddressingMode - Return true if the addressing mode represented
19092 // by AM is legal for this target, for a load/store of the specified type.
19093 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19094                                               const AddrMode &AM, Type *Ty,
19095                                               unsigned AS) const {
19096   // X86 supports extremely general addressing modes.
19097   CodeModel::Model M = getTargetMachine().getCodeModel();
19098   Reloc::Model R = getTargetMachine().getRelocationModel();
19099
19100   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19101   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19102     return false;
19103
19104   if (AM.BaseGV) {
19105     unsigned GVFlags =
19106       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19107
19108     // If a reference to this global requires an extra load, we can't fold it.
19109     if (isGlobalStubReference(GVFlags))
19110       return false;
19111
19112     // If BaseGV requires a register for the PIC base, we cannot also have a
19113     // BaseReg specified.
19114     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19115       return false;
19116
19117     // If lower 4G is not available, then we must use rip-relative addressing.
19118     if ((M != CodeModel::Small || R != Reloc::Static) &&
19119         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19120       return false;
19121   }
19122
19123   switch (AM.Scale) {
19124   case 0:
19125   case 1:
19126   case 2:
19127   case 4:
19128   case 8:
19129     // These scales always work.
19130     break;
19131   case 3:
19132   case 5:
19133   case 9:
19134     // These scales are formed with basereg+scalereg.  Only accept if there is
19135     // no basereg yet.
19136     if (AM.HasBaseReg)
19137       return false;
19138     break;
19139   default:  // Other stuff never works.
19140     return false;
19141   }
19142
19143   return true;
19144 }
19145
19146 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19147   unsigned Bits = Ty->getScalarSizeInBits();
19148
19149   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19150   // particularly cheaper than those without.
19151   if (Bits == 8)
19152     return false;
19153
19154   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19155   // variable shifts just as cheap as scalar ones.
19156   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19157     return false;
19158
19159   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19160   // fully general vector.
19161   return true;
19162 }
19163
19164 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19165   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19166     return false;
19167   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19168   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19169   return NumBits1 > NumBits2;
19170 }
19171
19172 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19173   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19174     return false;
19175
19176   if (!isTypeLegal(EVT::getEVT(Ty1)))
19177     return false;
19178
19179   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19180
19181   // Assuming the caller doesn't have a zeroext or signext return parameter,
19182   // truncation all the way down to i1 is valid.
19183   return true;
19184 }
19185
19186 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19187   return isInt<32>(Imm);
19188 }
19189
19190 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19191   // Can also use sub to handle negated immediates.
19192   return isInt<32>(Imm);
19193 }
19194
19195 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19196   if (!VT1.isInteger() || !VT2.isInteger())
19197     return false;
19198   unsigned NumBits1 = VT1.getSizeInBits();
19199   unsigned NumBits2 = VT2.getSizeInBits();
19200   return NumBits1 > NumBits2;
19201 }
19202
19203 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19204   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19205   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19206 }
19207
19208 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19209   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19210   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19211 }
19212
19213 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19214   EVT VT1 = Val.getValueType();
19215   if (isZExtFree(VT1, VT2))
19216     return true;
19217
19218   if (Val.getOpcode() != ISD::LOAD)
19219     return false;
19220
19221   if (!VT1.isSimple() || !VT1.isInteger() ||
19222       !VT2.isSimple() || !VT2.isInteger())
19223     return false;
19224
19225   switch (VT1.getSimpleVT().SimpleTy) {
19226   default: break;
19227   case MVT::i8:
19228   case MVT::i16:
19229   case MVT::i32:
19230     // X86 has 8, 16, and 32-bit zero-extending loads.
19231     return true;
19232   }
19233
19234   return false;
19235 }
19236
19237 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19238
19239 bool
19240 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19241   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19242     return false;
19243
19244   VT = VT.getScalarType();
19245
19246   if (!VT.isSimple())
19247     return false;
19248
19249   switch (VT.getSimpleVT().SimpleTy) {
19250   case MVT::f32:
19251   case MVT::f64:
19252     return true;
19253   default:
19254     break;
19255   }
19256
19257   return false;
19258 }
19259
19260 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19261   // i16 instructions are longer (0x66 prefix) and potentially slower.
19262   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19263 }
19264
19265 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19266 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19267 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19268 /// are assumed to be legal.
19269 bool
19270 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19271                                       EVT VT) const {
19272   if (!VT.isSimple())
19273     return false;
19274
19275   // Not for i1 vectors
19276   if (VT.getScalarType() == MVT::i1)
19277     return false;
19278
19279   // Very little shuffling can be done for 64-bit vectors right now.
19280   if (VT.getSizeInBits() == 64)
19281     return false;
19282
19283   // We only care that the types being shuffled are legal. The lowering can
19284   // handle any possible shuffle mask that results.
19285   return isTypeLegal(VT.getSimpleVT());
19286 }
19287
19288 bool
19289 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19290                                           EVT VT) const {
19291   // Just delegate to the generic legality, clear masks aren't special.
19292   return isShuffleMaskLegal(Mask, VT);
19293 }
19294
19295 //===----------------------------------------------------------------------===//
19296 //                           X86 Scheduler Hooks
19297 //===----------------------------------------------------------------------===//
19298
19299 /// Utility function to emit xbegin specifying the start of an RTM region.
19300 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19301                                      const TargetInstrInfo *TII) {
19302   DebugLoc DL = MI->getDebugLoc();
19303
19304   const BasicBlock *BB = MBB->getBasicBlock();
19305   MachineFunction::iterator I = MBB;
19306   ++I;
19307
19308   // For the v = xbegin(), we generate
19309   //
19310   // thisMBB:
19311   //  xbegin sinkMBB
19312   //
19313   // mainMBB:
19314   //  eax = -1
19315   //
19316   // sinkMBB:
19317   //  v = eax
19318
19319   MachineBasicBlock *thisMBB = MBB;
19320   MachineFunction *MF = MBB->getParent();
19321   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19322   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19323   MF->insert(I, mainMBB);
19324   MF->insert(I, sinkMBB);
19325
19326   // Transfer the remainder of BB and its successor edges to sinkMBB.
19327   sinkMBB->splice(sinkMBB->begin(), MBB,
19328                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19329   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19330
19331   // thisMBB:
19332   //  xbegin sinkMBB
19333   //  # fallthrough to mainMBB
19334   //  # abortion to sinkMBB
19335   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19336   thisMBB->addSuccessor(mainMBB);
19337   thisMBB->addSuccessor(sinkMBB);
19338
19339   // mainMBB:
19340   //  EAX = -1
19341   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19342   mainMBB->addSuccessor(sinkMBB);
19343
19344   // sinkMBB:
19345   // EAX is live into the sinkMBB
19346   sinkMBB->addLiveIn(X86::EAX);
19347   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19348           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19349     .addReg(X86::EAX);
19350
19351   MI->eraseFromParent();
19352   return sinkMBB;
19353 }
19354
19355 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19356 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19357 // in the .td file.
19358 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19359                                        const TargetInstrInfo *TII) {
19360   unsigned Opc;
19361   switch (MI->getOpcode()) {
19362   default: llvm_unreachable("illegal opcode!");
19363   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19364   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19365   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19366   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19367   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19368   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19369   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19370   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19371   }
19372
19373   DebugLoc dl = MI->getDebugLoc();
19374   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19375
19376   unsigned NumArgs = MI->getNumOperands();
19377   for (unsigned i = 1; i < NumArgs; ++i) {
19378     MachineOperand &Op = MI->getOperand(i);
19379     if (!(Op.isReg() && Op.isImplicit()))
19380       MIB.addOperand(Op);
19381   }
19382   if (MI->hasOneMemOperand())
19383     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19384
19385   BuildMI(*BB, MI, dl,
19386     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19387     .addReg(X86::XMM0);
19388
19389   MI->eraseFromParent();
19390   return BB;
19391 }
19392
19393 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19394 // defs in an instruction pattern
19395 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19396                                        const TargetInstrInfo *TII) {
19397   unsigned Opc;
19398   switch (MI->getOpcode()) {
19399   default: llvm_unreachable("illegal opcode!");
19400   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19401   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19402   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19403   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19404   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19405   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19406   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19407   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19408   }
19409
19410   DebugLoc dl = MI->getDebugLoc();
19411   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19412
19413   unsigned NumArgs = MI->getNumOperands(); // remove the results
19414   for (unsigned i = 1; i < NumArgs; ++i) {
19415     MachineOperand &Op = MI->getOperand(i);
19416     if (!(Op.isReg() && Op.isImplicit()))
19417       MIB.addOperand(Op);
19418   }
19419   if (MI->hasOneMemOperand())
19420     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19421
19422   BuildMI(*BB, MI, dl,
19423     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19424     .addReg(X86::ECX);
19425
19426   MI->eraseFromParent();
19427   return BB;
19428 }
19429
19430 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19431                                       const X86Subtarget *Subtarget) {
19432   DebugLoc dl = MI->getDebugLoc();
19433   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19434   // Address into RAX/EAX, other two args into ECX, EDX.
19435   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19436   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19437   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19438   for (int i = 0; i < X86::AddrNumOperands; ++i)
19439     MIB.addOperand(MI->getOperand(i));
19440
19441   unsigned ValOps = X86::AddrNumOperands;
19442   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19443     .addReg(MI->getOperand(ValOps).getReg());
19444   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19445     .addReg(MI->getOperand(ValOps+1).getReg());
19446
19447   // The instruction doesn't actually take any operands though.
19448   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19449
19450   MI->eraseFromParent(); // The pseudo is gone now.
19451   return BB;
19452 }
19453
19454 MachineBasicBlock *
19455 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19456                                                  MachineBasicBlock *MBB) const {
19457   // Emit va_arg instruction on X86-64.
19458
19459   // Operands to this pseudo-instruction:
19460   // 0  ) Output        : destination address (reg)
19461   // 1-5) Input         : va_list address (addr, i64mem)
19462   // 6  ) ArgSize       : Size (in bytes) of vararg type
19463   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19464   // 8  ) Align         : Alignment of type
19465   // 9  ) EFLAGS (implicit-def)
19466
19467   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19468   static_assert(X86::AddrNumOperands == 5,
19469                 "VAARG_64 assumes 5 address operands");
19470
19471   unsigned DestReg = MI->getOperand(0).getReg();
19472   MachineOperand &Base = MI->getOperand(1);
19473   MachineOperand &Scale = MI->getOperand(2);
19474   MachineOperand &Index = MI->getOperand(3);
19475   MachineOperand &Disp = MI->getOperand(4);
19476   MachineOperand &Segment = MI->getOperand(5);
19477   unsigned ArgSize = MI->getOperand(6).getImm();
19478   unsigned ArgMode = MI->getOperand(7).getImm();
19479   unsigned Align = MI->getOperand(8).getImm();
19480
19481   // Memory Reference
19482   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19483   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19484   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19485
19486   // Machine Information
19487   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19488   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19489   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19490   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19491   DebugLoc DL = MI->getDebugLoc();
19492
19493   // struct va_list {
19494   //   i32   gp_offset
19495   //   i32   fp_offset
19496   //   i64   overflow_area (address)
19497   //   i64   reg_save_area (address)
19498   // }
19499   // sizeof(va_list) = 24
19500   // alignment(va_list) = 8
19501
19502   unsigned TotalNumIntRegs = 6;
19503   unsigned TotalNumXMMRegs = 8;
19504   bool UseGPOffset = (ArgMode == 1);
19505   bool UseFPOffset = (ArgMode == 2);
19506   unsigned MaxOffset = TotalNumIntRegs * 8 +
19507                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19508
19509   /* Align ArgSize to a multiple of 8 */
19510   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19511   bool NeedsAlign = (Align > 8);
19512
19513   MachineBasicBlock *thisMBB = MBB;
19514   MachineBasicBlock *overflowMBB;
19515   MachineBasicBlock *offsetMBB;
19516   MachineBasicBlock *endMBB;
19517
19518   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19519   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19520   unsigned OffsetReg = 0;
19521
19522   if (!UseGPOffset && !UseFPOffset) {
19523     // If we only pull from the overflow region, we don't create a branch.
19524     // We don't need to alter control flow.
19525     OffsetDestReg = 0; // unused
19526     OverflowDestReg = DestReg;
19527
19528     offsetMBB = nullptr;
19529     overflowMBB = thisMBB;
19530     endMBB = thisMBB;
19531   } else {
19532     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19533     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19534     // If not, pull from overflow_area. (branch to overflowMBB)
19535     //
19536     //       thisMBB
19537     //         |     .
19538     //         |        .
19539     //     offsetMBB   overflowMBB
19540     //         |        .
19541     //         |     .
19542     //        endMBB
19543
19544     // Registers for the PHI in endMBB
19545     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19546     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19547
19548     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19549     MachineFunction *MF = MBB->getParent();
19550     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19551     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19552     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19553
19554     MachineFunction::iterator MBBIter = MBB;
19555     ++MBBIter;
19556
19557     // Insert the new basic blocks
19558     MF->insert(MBBIter, offsetMBB);
19559     MF->insert(MBBIter, overflowMBB);
19560     MF->insert(MBBIter, endMBB);
19561
19562     // Transfer the remainder of MBB and its successor edges to endMBB.
19563     endMBB->splice(endMBB->begin(), thisMBB,
19564                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19565     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19566
19567     // Make offsetMBB and overflowMBB successors of thisMBB
19568     thisMBB->addSuccessor(offsetMBB);
19569     thisMBB->addSuccessor(overflowMBB);
19570
19571     // endMBB is a successor of both offsetMBB and overflowMBB
19572     offsetMBB->addSuccessor(endMBB);
19573     overflowMBB->addSuccessor(endMBB);
19574
19575     // Load the offset value into a register
19576     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19577     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19578       .addOperand(Base)
19579       .addOperand(Scale)
19580       .addOperand(Index)
19581       .addDisp(Disp, UseFPOffset ? 4 : 0)
19582       .addOperand(Segment)
19583       .setMemRefs(MMOBegin, MMOEnd);
19584
19585     // Check if there is enough room left to pull this argument.
19586     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19587       .addReg(OffsetReg)
19588       .addImm(MaxOffset + 8 - ArgSizeA8);
19589
19590     // Branch to "overflowMBB" if offset >= max
19591     // Fall through to "offsetMBB" otherwise
19592     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19593       .addMBB(overflowMBB);
19594   }
19595
19596   // In offsetMBB, emit code to use the reg_save_area.
19597   if (offsetMBB) {
19598     assert(OffsetReg != 0);
19599
19600     // Read the reg_save_area address.
19601     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19602     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19603       .addOperand(Base)
19604       .addOperand(Scale)
19605       .addOperand(Index)
19606       .addDisp(Disp, 16)
19607       .addOperand(Segment)
19608       .setMemRefs(MMOBegin, MMOEnd);
19609
19610     // Zero-extend the offset
19611     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19612       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19613         .addImm(0)
19614         .addReg(OffsetReg)
19615         .addImm(X86::sub_32bit);
19616
19617     // Add the offset to the reg_save_area to get the final address.
19618     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19619       .addReg(OffsetReg64)
19620       .addReg(RegSaveReg);
19621
19622     // Compute the offset for the next argument
19623     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19624     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19625       .addReg(OffsetReg)
19626       .addImm(UseFPOffset ? 16 : 8);
19627
19628     // Store it back into the va_list.
19629     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19630       .addOperand(Base)
19631       .addOperand(Scale)
19632       .addOperand(Index)
19633       .addDisp(Disp, UseFPOffset ? 4 : 0)
19634       .addOperand(Segment)
19635       .addReg(NextOffsetReg)
19636       .setMemRefs(MMOBegin, MMOEnd);
19637
19638     // Jump to endMBB
19639     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19640       .addMBB(endMBB);
19641   }
19642
19643   //
19644   // Emit code to use overflow area
19645   //
19646
19647   // Load the overflow_area address into a register.
19648   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19649   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19650     .addOperand(Base)
19651     .addOperand(Scale)
19652     .addOperand(Index)
19653     .addDisp(Disp, 8)
19654     .addOperand(Segment)
19655     .setMemRefs(MMOBegin, MMOEnd);
19656
19657   // If we need to align it, do so. Otherwise, just copy the address
19658   // to OverflowDestReg.
19659   if (NeedsAlign) {
19660     // Align the overflow address
19661     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19662     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19663
19664     // aligned_addr = (addr + (align-1)) & ~(align-1)
19665     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19666       .addReg(OverflowAddrReg)
19667       .addImm(Align-1);
19668
19669     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19670       .addReg(TmpReg)
19671       .addImm(~(uint64_t)(Align-1));
19672   } else {
19673     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19674       .addReg(OverflowAddrReg);
19675   }
19676
19677   // Compute the next overflow address after this argument.
19678   // (the overflow address should be kept 8-byte aligned)
19679   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19680   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19681     .addReg(OverflowDestReg)
19682     .addImm(ArgSizeA8);
19683
19684   // Store the new overflow address.
19685   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19686     .addOperand(Base)
19687     .addOperand(Scale)
19688     .addOperand(Index)
19689     .addDisp(Disp, 8)
19690     .addOperand(Segment)
19691     .addReg(NextAddrReg)
19692     .setMemRefs(MMOBegin, MMOEnd);
19693
19694   // If we branched, emit the PHI to the front of endMBB.
19695   if (offsetMBB) {
19696     BuildMI(*endMBB, endMBB->begin(), DL,
19697             TII->get(X86::PHI), DestReg)
19698       .addReg(OffsetDestReg).addMBB(offsetMBB)
19699       .addReg(OverflowDestReg).addMBB(overflowMBB);
19700   }
19701
19702   // Erase the pseudo instruction
19703   MI->eraseFromParent();
19704
19705   return endMBB;
19706 }
19707
19708 MachineBasicBlock *
19709 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19710                                                  MachineInstr *MI,
19711                                                  MachineBasicBlock *MBB) const {
19712   // Emit code to save XMM registers to the stack. The ABI says that the
19713   // number of registers to save is given in %al, so it's theoretically
19714   // possible to do an indirect jump trick to avoid saving all of them,
19715   // however this code takes a simpler approach and just executes all
19716   // of the stores if %al is non-zero. It's less code, and it's probably
19717   // easier on the hardware branch predictor, and stores aren't all that
19718   // expensive anyway.
19719
19720   // Create the new basic blocks. One block contains all the XMM stores,
19721   // and one block is the final destination regardless of whether any
19722   // stores were performed.
19723   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19724   MachineFunction *F = MBB->getParent();
19725   MachineFunction::iterator MBBIter = MBB;
19726   ++MBBIter;
19727   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19728   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19729   F->insert(MBBIter, XMMSaveMBB);
19730   F->insert(MBBIter, EndMBB);
19731
19732   // Transfer the remainder of MBB and its successor edges to EndMBB.
19733   EndMBB->splice(EndMBB->begin(), MBB,
19734                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19735   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19736
19737   // The original block will now fall through to the XMM save block.
19738   MBB->addSuccessor(XMMSaveMBB);
19739   // The XMMSaveMBB will fall through to the end block.
19740   XMMSaveMBB->addSuccessor(EndMBB);
19741
19742   // Now add the instructions.
19743   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19744   DebugLoc DL = MI->getDebugLoc();
19745
19746   unsigned CountReg = MI->getOperand(0).getReg();
19747   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19748   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19749
19750   if (!Subtarget->isTargetWin64()) {
19751     // If %al is 0, branch around the XMM save block.
19752     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19753     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19754     MBB->addSuccessor(EndMBB);
19755   }
19756
19757   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19758   // that was just emitted, but clearly shouldn't be "saved".
19759   assert((MI->getNumOperands() <= 3 ||
19760           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19761           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19762          && "Expected last argument to be EFLAGS");
19763   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19764   // In the XMM save block, save all the XMM argument registers.
19765   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19766     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19767     MachineMemOperand *MMO =
19768       F->getMachineMemOperand(
19769           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19770         MachineMemOperand::MOStore,
19771         /*Size=*/16, /*Align=*/16);
19772     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19773       .addFrameIndex(RegSaveFrameIndex)
19774       .addImm(/*Scale=*/1)
19775       .addReg(/*IndexReg=*/0)
19776       .addImm(/*Disp=*/Offset)
19777       .addReg(/*Segment=*/0)
19778       .addReg(MI->getOperand(i).getReg())
19779       .addMemOperand(MMO);
19780   }
19781
19782   MI->eraseFromParent();   // The pseudo instruction is gone now.
19783
19784   return EndMBB;
19785 }
19786
19787 // The EFLAGS operand of SelectItr might be missing a kill marker
19788 // because there were multiple uses of EFLAGS, and ISel didn't know
19789 // which to mark. Figure out whether SelectItr should have had a
19790 // kill marker, and set it if it should. Returns the correct kill
19791 // marker value.
19792 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19793                                      MachineBasicBlock* BB,
19794                                      const TargetRegisterInfo* TRI) {
19795   // Scan forward through BB for a use/def of EFLAGS.
19796   MachineBasicBlock::iterator miI(std::next(SelectItr));
19797   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19798     const MachineInstr& mi = *miI;
19799     if (mi.readsRegister(X86::EFLAGS))
19800       return false;
19801     if (mi.definesRegister(X86::EFLAGS))
19802       break; // Should have kill-flag - update below.
19803   }
19804
19805   // If we hit the end of the block, check whether EFLAGS is live into a
19806   // successor.
19807   if (miI == BB->end()) {
19808     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19809                                           sEnd = BB->succ_end();
19810          sItr != sEnd; ++sItr) {
19811       MachineBasicBlock* succ = *sItr;
19812       if (succ->isLiveIn(X86::EFLAGS))
19813         return false;
19814     }
19815   }
19816
19817   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19818   // out. SelectMI should have a kill flag on EFLAGS.
19819   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19820   return true;
19821 }
19822
19823 MachineBasicBlock *
19824 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19825                                      MachineBasicBlock *BB) const {
19826   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19827   DebugLoc DL = MI->getDebugLoc();
19828
19829   // To "insert" a SELECT_CC instruction, we actually have to insert the
19830   // diamond control-flow pattern.  The incoming instruction knows the
19831   // destination vreg to set, the condition code register to branch on, the
19832   // true/false values to select between, and a branch opcode to use.
19833   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19834   MachineFunction::iterator It = BB;
19835   ++It;
19836
19837   //  thisMBB:
19838   //  ...
19839   //   TrueVal = ...
19840   //   cmpTY ccX, r1, r2
19841   //   bCC copy1MBB
19842   //   fallthrough --> copy0MBB
19843   MachineBasicBlock *thisMBB = BB;
19844   MachineFunction *F = BB->getParent();
19845
19846   // We also lower double CMOVs:
19847   //   (CMOV (CMOV F, T, cc1), T, cc2)
19848   // to two successives branches.  For that, we look for another CMOV as the
19849   // following instruction.
19850   //
19851   // Without this, we would add a PHI between the two jumps, which ends up
19852   // creating a few copies all around. For instance, for
19853   //
19854   //    (sitofp (zext (fcmp une)))
19855   //
19856   // we would generate:
19857   //
19858   //         ucomiss %xmm1, %xmm0
19859   //         movss  <1.0f>, %xmm0
19860   //         movaps  %xmm0, %xmm1
19861   //         jne     .LBB5_2
19862   //         xorps   %xmm1, %xmm1
19863   // .LBB5_2:
19864   //         jp      .LBB5_4
19865   //         movaps  %xmm1, %xmm0
19866   // .LBB5_4:
19867   //         retq
19868   //
19869   // because this custom-inserter would have generated:
19870   //
19871   //   A
19872   //   | \
19873   //   |  B
19874   //   | /
19875   //   C
19876   //   | \
19877   //   |  D
19878   //   | /
19879   //   E
19880   //
19881   // A: X = ...; Y = ...
19882   // B: empty
19883   // C: Z = PHI [X, A], [Y, B]
19884   // D: empty
19885   // E: PHI [X, C], [Z, D]
19886   //
19887   // If we lower both CMOVs in a single step, we can instead generate:
19888   //
19889   //   A
19890   //   | \
19891   //   |  C
19892   //   | /|
19893   //   |/ |
19894   //   |  |
19895   //   |  D
19896   //   | /
19897   //   E
19898   //
19899   // A: X = ...; Y = ...
19900   // D: empty
19901   // E: PHI [X, A], [X, C], [Y, D]
19902   //
19903   // Which, in our sitofp/fcmp example, gives us something like:
19904   //
19905   //         ucomiss %xmm1, %xmm0
19906   //         movss  <1.0f>, %xmm0
19907   //         jne     .LBB5_4
19908   //         jp      .LBB5_4
19909   //         xorps   %xmm0, %xmm0
19910   // .LBB5_4:
19911   //         retq
19912   //
19913   MachineInstr *NextCMOV = nullptr;
19914   MachineBasicBlock::iterator NextMIIt =
19915       std::next(MachineBasicBlock::iterator(MI));
19916   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19917       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19918       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19919     NextCMOV = &*NextMIIt;
19920
19921   MachineBasicBlock *jcc1MBB = nullptr;
19922
19923   // If we have a double CMOV, we lower it to two successive branches to
19924   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19925   if (NextCMOV) {
19926     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19927     F->insert(It, jcc1MBB);
19928     jcc1MBB->addLiveIn(X86::EFLAGS);
19929   }
19930
19931   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19932   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19933   F->insert(It, copy0MBB);
19934   F->insert(It, sinkMBB);
19935
19936   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19937   // live into the sink and copy blocks.
19938   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19939
19940   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19941   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19942       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19943     copy0MBB->addLiveIn(X86::EFLAGS);
19944     sinkMBB->addLiveIn(X86::EFLAGS);
19945   }
19946
19947   // Transfer the remainder of BB and its successor edges to sinkMBB.
19948   sinkMBB->splice(sinkMBB->begin(), BB,
19949                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19950   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19951
19952   // Add the true and fallthrough blocks as its successors.
19953   if (NextCMOV) {
19954     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19955     BB->addSuccessor(jcc1MBB);
19956
19957     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19958     // jump to the sinkMBB.
19959     jcc1MBB->addSuccessor(copy0MBB);
19960     jcc1MBB->addSuccessor(sinkMBB);
19961   } else {
19962     BB->addSuccessor(copy0MBB);
19963   }
19964
19965   // The true block target of the first (or only) branch is always sinkMBB.
19966   BB->addSuccessor(sinkMBB);
19967
19968   // Create the conditional branch instruction.
19969   unsigned Opc =
19970     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19971   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19972
19973   if (NextCMOV) {
19974     unsigned Opc2 = X86::GetCondBranchFromCond(
19975         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19976     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19977   }
19978
19979   //  copy0MBB:
19980   //   %FalseValue = ...
19981   //   # fallthrough to sinkMBB
19982   copy0MBB->addSuccessor(sinkMBB);
19983
19984   //  sinkMBB:
19985   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19986   //  ...
19987   MachineInstrBuilder MIB =
19988       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19989               MI->getOperand(0).getReg())
19990           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19991           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19992
19993   // If we have a double CMOV, the second Jcc provides the same incoming
19994   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19995   if (NextCMOV) {
19996     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19997     // Copy the PHI result to the register defined by the second CMOV.
19998     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19999             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
20000         .addReg(MI->getOperand(0).getReg());
20001     NextCMOV->eraseFromParent();
20002   }
20003
20004   MI->eraseFromParent();   // The pseudo instruction is gone now.
20005   return sinkMBB;
20006 }
20007
20008 MachineBasicBlock *
20009 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
20010                                         MachineBasicBlock *BB) const {
20011   MachineFunction *MF = BB->getParent();
20012   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20013   DebugLoc DL = MI->getDebugLoc();
20014   const BasicBlock *LLVM_BB = BB->getBasicBlock();
20015
20016   assert(MF->shouldSplitStack());
20017
20018   const bool Is64Bit = Subtarget->is64Bit();
20019   const bool IsLP64 = Subtarget->isTarget64BitLP64();
20020
20021   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
20022   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
20023
20024   // BB:
20025   //  ... [Till the alloca]
20026   // If stacklet is not large enough, jump to mallocMBB
20027   //
20028   // bumpMBB:
20029   //  Allocate by subtracting from RSP
20030   //  Jump to continueMBB
20031   //
20032   // mallocMBB:
20033   //  Allocate by call to runtime
20034   //
20035   // continueMBB:
20036   //  ...
20037   //  [rest of original BB]
20038   //
20039
20040   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20041   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20042   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20043
20044   MachineRegisterInfo &MRI = MF->getRegInfo();
20045   const TargetRegisterClass *AddrRegClass =
20046       getRegClassFor(getPointerTy(MF->getDataLayout()));
20047
20048   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20049     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20050     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20051     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20052     sizeVReg = MI->getOperand(1).getReg(),
20053     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20054
20055   MachineFunction::iterator MBBIter = BB;
20056   ++MBBIter;
20057
20058   MF->insert(MBBIter, bumpMBB);
20059   MF->insert(MBBIter, mallocMBB);
20060   MF->insert(MBBIter, continueMBB);
20061
20062   continueMBB->splice(continueMBB->begin(), BB,
20063                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20064   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20065
20066   // Add code to the main basic block to check if the stack limit has been hit,
20067   // and if so, jump to mallocMBB otherwise to bumpMBB.
20068   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20069   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20070     .addReg(tmpSPVReg).addReg(sizeVReg);
20071   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20072     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20073     .addReg(SPLimitVReg);
20074   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20075
20076   // bumpMBB simply decreases the stack pointer, since we know the current
20077   // stacklet has enough space.
20078   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20079     .addReg(SPLimitVReg);
20080   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20081     .addReg(SPLimitVReg);
20082   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20083
20084   // Calls into a routine in libgcc to allocate more space from the heap.
20085   const uint32_t *RegMask =
20086       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20087   if (IsLP64) {
20088     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20089       .addReg(sizeVReg);
20090     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20091       .addExternalSymbol("__morestack_allocate_stack_space")
20092       .addRegMask(RegMask)
20093       .addReg(X86::RDI, RegState::Implicit)
20094       .addReg(X86::RAX, RegState::ImplicitDefine);
20095   } else if (Is64Bit) {
20096     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20097       .addReg(sizeVReg);
20098     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20099       .addExternalSymbol("__morestack_allocate_stack_space")
20100       .addRegMask(RegMask)
20101       .addReg(X86::EDI, RegState::Implicit)
20102       .addReg(X86::EAX, RegState::ImplicitDefine);
20103   } else {
20104     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20105       .addImm(12);
20106     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20107     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20108       .addExternalSymbol("__morestack_allocate_stack_space")
20109       .addRegMask(RegMask)
20110       .addReg(X86::EAX, RegState::ImplicitDefine);
20111   }
20112
20113   if (!Is64Bit)
20114     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20115       .addImm(16);
20116
20117   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20118     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20119   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20120
20121   // Set up the CFG correctly.
20122   BB->addSuccessor(bumpMBB);
20123   BB->addSuccessor(mallocMBB);
20124   mallocMBB->addSuccessor(continueMBB);
20125   bumpMBB->addSuccessor(continueMBB);
20126
20127   // Take care of the PHI nodes.
20128   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20129           MI->getOperand(0).getReg())
20130     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20131     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20132
20133   // Delete the original pseudo instruction.
20134   MI->eraseFromParent();
20135
20136   // And we're done.
20137   return continueMBB;
20138 }
20139
20140 MachineBasicBlock *
20141 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20142                                         MachineBasicBlock *BB) const {
20143   DebugLoc DL = MI->getDebugLoc();
20144
20145   assert(!Subtarget->isTargetMachO());
20146
20147   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20148                                                     DL);
20149
20150   MI->eraseFromParent();   // The pseudo instruction is gone now.
20151   return BB;
20152 }
20153
20154 MachineBasicBlock *
20155 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20156                                       MachineBasicBlock *BB) const {
20157   // This is pretty easy.  We're taking the value that we received from
20158   // our load from the relocation, sticking it in either RDI (x86-64)
20159   // or EAX and doing an indirect call.  The return value will then
20160   // be in the normal return register.
20161   MachineFunction *F = BB->getParent();
20162   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20163   DebugLoc DL = MI->getDebugLoc();
20164
20165   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20166   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20167
20168   // Get a register mask for the lowered call.
20169   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20170   // proper register mask.
20171   const uint32_t *RegMask =
20172       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20173   if (Subtarget->is64Bit()) {
20174     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20175                                       TII->get(X86::MOV64rm), X86::RDI)
20176     .addReg(X86::RIP)
20177     .addImm(0).addReg(0)
20178     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20179                       MI->getOperand(3).getTargetFlags())
20180     .addReg(0);
20181     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20182     addDirectMem(MIB, X86::RDI);
20183     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20184   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20185     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20186                                       TII->get(X86::MOV32rm), X86::EAX)
20187     .addReg(0)
20188     .addImm(0).addReg(0)
20189     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20190                       MI->getOperand(3).getTargetFlags())
20191     .addReg(0);
20192     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20193     addDirectMem(MIB, X86::EAX);
20194     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20195   } else {
20196     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20197                                       TII->get(X86::MOV32rm), X86::EAX)
20198     .addReg(TII->getGlobalBaseReg(F))
20199     .addImm(0).addReg(0)
20200     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20201                       MI->getOperand(3).getTargetFlags())
20202     .addReg(0);
20203     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20204     addDirectMem(MIB, X86::EAX);
20205     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20206   }
20207
20208   MI->eraseFromParent(); // The pseudo instruction is gone now.
20209   return BB;
20210 }
20211
20212 MachineBasicBlock *
20213 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20214                                     MachineBasicBlock *MBB) const {
20215   DebugLoc DL = MI->getDebugLoc();
20216   MachineFunction *MF = MBB->getParent();
20217   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20218   MachineRegisterInfo &MRI = MF->getRegInfo();
20219
20220   const BasicBlock *BB = MBB->getBasicBlock();
20221   MachineFunction::iterator I = MBB;
20222   ++I;
20223
20224   // Memory Reference
20225   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20226   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20227
20228   unsigned DstReg;
20229   unsigned MemOpndSlot = 0;
20230
20231   unsigned CurOp = 0;
20232
20233   DstReg = MI->getOperand(CurOp++).getReg();
20234   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20235   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20236   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20237   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20238
20239   MemOpndSlot = CurOp;
20240
20241   MVT PVT = getPointerTy(MF->getDataLayout());
20242   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20243          "Invalid Pointer Size!");
20244
20245   // For v = setjmp(buf), we generate
20246   //
20247   // thisMBB:
20248   //  buf[LabelOffset] = restoreMBB
20249   //  SjLjSetup restoreMBB
20250   //
20251   // mainMBB:
20252   //  v_main = 0
20253   //
20254   // sinkMBB:
20255   //  v = phi(main, restore)
20256   //
20257   // restoreMBB:
20258   //  if base pointer being used, load it from frame
20259   //  v_restore = 1
20260
20261   MachineBasicBlock *thisMBB = MBB;
20262   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20263   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20264   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20265   MF->insert(I, mainMBB);
20266   MF->insert(I, sinkMBB);
20267   MF->push_back(restoreMBB);
20268
20269   MachineInstrBuilder MIB;
20270
20271   // Transfer the remainder of BB and its successor edges to sinkMBB.
20272   sinkMBB->splice(sinkMBB->begin(), MBB,
20273                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20274   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20275
20276   // thisMBB:
20277   unsigned PtrStoreOpc = 0;
20278   unsigned LabelReg = 0;
20279   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20280   Reloc::Model RM = MF->getTarget().getRelocationModel();
20281   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20282                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20283
20284   // Prepare IP either in reg or imm.
20285   if (!UseImmLabel) {
20286     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20287     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20288     LabelReg = MRI.createVirtualRegister(PtrRC);
20289     if (Subtarget->is64Bit()) {
20290       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20291               .addReg(X86::RIP)
20292               .addImm(0)
20293               .addReg(0)
20294               .addMBB(restoreMBB)
20295               .addReg(0);
20296     } else {
20297       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20298       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20299               .addReg(XII->getGlobalBaseReg(MF))
20300               .addImm(0)
20301               .addReg(0)
20302               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20303               .addReg(0);
20304     }
20305   } else
20306     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20307   // Store IP
20308   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20309   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20310     if (i == X86::AddrDisp)
20311       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20312     else
20313       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20314   }
20315   if (!UseImmLabel)
20316     MIB.addReg(LabelReg);
20317   else
20318     MIB.addMBB(restoreMBB);
20319   MIB.setMemRefs(MMOBegin, MMOEnd);
20320   // Setup
20321   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20322           .addMBB(restoreMBB);
20323
20324   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20325   MIB.addRegMask(RegInfo->getNoPreservedMask());
20326   thisMBB->addSuccessor(mainMBB);
20327   thisMBB->addSuccessor(restoreMBB);
20328
20329   // mainMBB:
20330   //  EAX = 0
20331   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20332   mainMBB->addSuccessor(sinkMBB);
20333
20334   // sinkMBB:
20335   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20336           TII->get(X86::PHI), DstReg)
20337     .addReg(mainDstReg).addMBB(mainMBB)
20338     .addReg(restoreDstReg).addMBB(restoreMBB);
20339
20340   // restoreMBB:
20341   if (RegInfo->hasBasePointer(*MF)) {
20342     const bool Uses64BitFramePtr =
20343         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20344     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20345     X86FI->setRestoreBasePointer(MF);
20346     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20347     unsigned BasePtr = RegInfo->getBaseRegister();
20348     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20349     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20350                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20351       .setMIFlag(MachineInstr::FrameSetup);
20352   }
20353   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20354   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20355   restoreMBB->addSuccessor(sinkMBB);
20356
20357   MI->eraseFromParent();
20358   return sinkMBB;
20359 }
20360
20361 MachineBasicBlock *
20362 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20363                                      MachineBasicBlock *MBB) const {
20364   DebugLoc DL = MI->getDebugLoc();
20365   MachineFunction *MF = MBB->getParent();
20366   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20367   MachineRegisterInfo &MRI = MF->getRegInfo();
20368
20369   // Memory Reference
20370   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20371   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20372
20373   MVT PVT = getPointerTy(MF->getDataLayout());
20374   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20375          "Invalid Pointer Size!");
20376
20377   const TargetRegisterClass *RC =
20378     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20379   unsigned Tmp = MRI.createVirtualRegister(RC);
20380   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20381   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20382   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20383   unsigned SP = RegInfo->getStackRegister();
20384
20385   MachineInstrBuilder MIB;
20386
20387   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20388   const int64_t SPOffset = 2 * PVT.getStoreSize();
20389
20390   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20391   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20392
20393   // Reload FP
20394   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20395   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20396     MIB.addOperand(MI->getOperand(i));
20397   MIB.setMemRefs(MMOBegin, MMOEnd);
20398   // Reload IP
20399   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20400   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20401     if (i == X86::AddrDisp)
20402       MIB.addDisp(MI->getOperand(i), LabelOffset);
20403     else
20404       MIB.addOperand(MI->getOperand(i));
20405   }
20406   MIB.setMemRefs(MMOBegin, MMOEnd);
20407   // Reload SP
20408   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20409   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20410     if (i == X86::AddrDisp)
20411       MIB.addDisp(MI->getOperand(i), SPOffset);
20412     else
20413       MIB.addOperand(MI->getOperand(i));
20414   }
20415   MIB.setMemRefs(MMOBegin, MMOEnd);
20416   // Jump
20417   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20418
20419   MI->eraseFromParent();
20420   return MBB;
20421 }
20422
20423 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20424 // accumulator loops. Writing back to the accumulator allows the coalescer
20425 // to remove extra copies in the loop.
20426 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20427 MachineBasicBlock *
20428 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20429                                  MachineBasicBlock *MBB) const {
20430   MachineOperand &AddendOp = MI->getOperand(3);
20431
20432   // Bail out early if the addend isn't a register - we can't switch these.
20433   if (!AddendOp.isReg())
20434     return MBB;
20435
20436   MachineFunction &MF = *MBB->getParent();
20437   MachineRegisterInfo &MRI = MF.getRegInfo();
20438
20439   // Check whether the addend is defined by a PHI:
20440   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20441   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20442   if (!AddendDef.isPHI())
20443     return MBB;
20444
20445   // Look for the following pattern:
20446   // loop:
20447   //   %addend = phi [%entry, 0], [%loop, %result]
20448   //   ...
20449   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20450
20451   // Replace with:
20452   //   loop:
20453   //   %addend = phi [%entry, 0], [%loop, %result]
20454   //   ...
20455   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20456
20457   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20458     assert(AddendDef.getOperand(i).isReg());
20459     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20460     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20461     if (&PHISrcInst == MI) {
20462       // Found a matching instruction.
20463       unsigned NewFMAOpc = 0;
20464       switch (MI->getOpcode()) {
20465         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20466         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20467         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20468         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20469         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20470         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20471         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20472         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20473         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20474         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20475         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20476         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20477         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20478         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20479         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20480         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20481         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20482         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20483         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20484         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20485
20486         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20487         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20488         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20489         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20490         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20491         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20492         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20493         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20494         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20495         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20496         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20497         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20498         default: llvm_unreachable("Unrecognized FMA variant.");
20499       }
20500
20501       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20502       MachineInstrBuilder MIB =
20503         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20504         .addOperand(MI->getOperand(0))
20505         .addOperand(MI->getOperand(3))
20506         .addOperand(MI->getOperand(2))
20507         .addOperand(MI->getOperand(1));
20508       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20509       MI->eraseFromParent();
20510     }
20511   }
20512
20513   return MBB;
20514 }
20515
20516 MachineBasicBlock *
20517 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20518                                                MachineBasicBlock *BB) const {
20519   switch (MI->getOpcode()) {
20520   default: llvm_unreachable("Unexpected instr type to insert");
20521   case X86::TAILJMPd64:
20522   case X86::TAILJMPr64:
20523   case X86::TAILJMPm64:
20524   case X86::TAILJMPd64_REX:
20525   case X86::TAILJMPr64_REX:
20526   case X86::TAILJMPm64_REX:
20527     llvm_unreachable("TAILJMP64 would not be touched here.");
20528   case X86::TCRETURNdi64:
20529   case X86::TCRETURNri64:
20530   case X86::TCRETURNmi64:
20531     return BB;
20532   case X86::WIN_ALLOCA:
20533     return EmitLoweredWinAlloca(MI, BB);
20534   case X86::SEG_ALLOCA_32:
20535   case X86::SEG_ALLOCA_64:
20536     return EmitLoweredSegAlloca(MI, BB);
20537   case X86::TLSCall_32:
20538   case X86::TLSCall_64:
20539     return EmitLoweredTLSCall(MI, BB);
20540   case X86::CMOV_GR8:
20541   case X86::CMOV_FR32:
20542   case X86::CMOV_FR64:
20543   case X86::CMOV_V4F32:
20544   case X86::CMOV_V2F64:
20545   case X86::CMOV_V2I64:
20546   case X86::CMOV_V8F32:
20547   case X86::CMOV_V4F64:
20548   case X86::CMOV_V4I64:
20549   case X86::CMOV_V16F32:
20550   case X86::CMOV_V8F64:
20551   case X86::CMOV_V8I64:
20552   case X86::CMOV_GR16:
20553   case X86::CMOV_GR32:
20554   case X86::CMOV_RFP32:
20555   case X86::CMOV_RFP64:
20556   case X86::CMOV_RFP80:
20557   case X86::CMOV_V8I1:
20558   case X86::CMOV_V16I1:
20559   case X86::CMOV_V32I1:
20560   case X86::CMOV_V64I1:
20561     return EmitLoweredSelect(MI, BB);
20562
20563   case X86::FP32_TO_INT16_IN_MEM:
20564   case X86::FP32_TO_INT32_IN_MEM:
20565   case X86::FP32_TO_INT64_IN_MEM:
20566   case X86::FP64_TO_INT16_IN_MEM:
20567   case X86::FP64_TO_INT32_IN_MEM:
20568   case X86::FP64_TO_INT64_IN_MEM:
20569   case X86::FP80_TO_INT16_IN_MEM:
20570   case X86::FP80_TO_INT32_IN_MEM:
20571   case X86::FP80_TO_INT64_IN_MEM: {
20572     MachineFunction *F = BB->getParent();
20573     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20574     DebugLoc DL = MI->getDebugLoc();
20575
20576     // Change the floating point control register to use "round towards zero"
20577     // mode when truncating to an integer value.
20578     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20579     addFrameReference(BuildMI(*BB, MI, DL,
20580                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20581
20582     // Load the old value of the high byte of the control word...
20583     unsigned OldCW =
20584       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20585     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20586                       CWFrameIdx);
20587
20588     // Set the high part to be round to zero...
20589     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20590       .addImm(0xC7F);
20591
20592     // Reload the modified control word now...
20593     addFrameReference(BuildMI(*BB, MI, DL,
20594                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20595
20596     // Restore the memory image of control word to original value
20597     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20598       .addReg(OldCW);
20599
20600     // Get the X86 opcode to use.
20601     unsigned Opc;
20602     switch (MI->getOpcode()) {
20603     default: llvm_unreachable("illegal opcode!");
20604     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20605     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20606     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20607     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20608     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20609     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20610     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20611     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20612     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20613     }
20614
20615     X86AddressMode AM;
20616     MachineOperand &Op = MI->getOperand(0);
20617     if (Op.isReg()) {
20618       AM.BaseType = X86AddressMode::RegBase;
20619       AM.Base.Reg = Op.getReg();
20620     } else {
20621       AM.BaseType = X86AddressMode::FrameIndexBase;
20622       AM.Base.FrameIndex = Op.getIndex();
20623     }
20624     Op = MI->getOperand(1);
20625     if (Op.isImm())
20626       AM.Scale = Op.getImm();
20627     Op = MI->getOperand(2);
20628     if (Op.isImm())
20629       AM.IndexReg = Op.getImm();
20630     Op = MI->getOperand(3);
20631     if (Op.isGlobal()) {
20632       AM.GV = Op.getGlobal();
20633     } else {
20634       AM.Disp = Op.getImm();
20635     }
20636     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20637                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20638
20639     // Reload the original control word now.
20640     addFrameReference(BuildMI(*BB, MI, DL,
20641                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20642
20643     MI->eraseFromParent();   // The pseudo instruction is gone now.
20644     return BB;
20645   }
20646     // String/text processing lowering.
20647   case X86::PCMPISTRM128REG:
20648   case X86::VPCMPISTRM128REG:
20649   case X86::PCMPISTRM128MEM:
20650   case X86::VPCMPISTRM128MEM:
20651   case X86::PCMPESTRM128REG:
20652   case X86::VPCMPESTRM128REG:
20653   case X86::PCMPESTRM128MEM:
20654   case X86::VPCMPESTRM128MEM:
20655     assert(Subtarget->hasSSE42() &&
20656            "Target must have SSE4.2 or AVX features enabled");
20657     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20658
20659   // String/text processing lowering.
20660   case X86::PCMPISTRIREG:
20661   case X86::VPCMPISTRIREG:
20662   case X86::PCMPISTRIMEM:
20663   case X86::VPCMPISTRIMEM:
20664   case X86::PCMPESTRIREG:
20665   case X86::VPCMPESTRIREG:
20666   case X86::PCMPESTRIMEM:
20667   case X86::VPCMPESTRIMEM:
20668     assert(Subtarget->hasSSE42() &&
20669            "Target must have SSE4.2 or AVX features enabled");
20670     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20671
20672   // Thread synchronization.
20673   case X86::MONITOR:
20674     return EmitMonitor(MI, BB, Subtarget);
20675
20676   // xbegin
20677   case X86::XBEGIN:
20678     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20679
20680   case X86::VASTART_SAVE_XMM_REGS:
20681     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20682
20683   case X86::VAARG_64:
20684     return EmitVAARG64WithCustomInserter(MI, BB);
20685
20686   case X86::EH_SjLj_SetJmp32:
20687   case X86::EH_SjLj_SetJmp64:
20688     return emitEHSjLjSetJmp(MI, BB);
20689
20690   case X86::EH_SjLj_LongJmp32:
20691   case X86::EH_SjLj_LongJmp64:
20692     return emitEHSjLjLongJmp(MI, BB);
20693
20694   case TargetOpcode::STATEPOINT:
20695     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20696     // this point in the process.  We diverge later.
20697     return emitPatchPoint(MI, BB);
20698
20699   case TargetOpcode::STACKMAP:
20700   case TargetOpcode::PATCHPOINT:
20701     return emitPatchPoint(MI, BB);
20702
20703   case X86::VFMADDPDr213r:
20704   case X86::VFMADDPSr213r:
20705   case X86::VFMADDSDr213r:
20706   case X86::VFMADDSSr213r:
20707   case X86::VFMSUBPDr213r:
20708   case X86::VFMSUBPSr213r:
20709   case X86::VFMSUBSDr213r:
20710   case X86::VFMSUBSSr213r:
20711   case X86::VFNMADDPDr213r:
20712   case X86::VFNMADDPSr213r:
20713   case X86::VFNMADDSDr213r:
20714   case X86::VFNMADDSSr213r:
20715   case X86::VFNMSUBPDr213r:
20716   case X86::VFNMSUBPSr213r:
20717   case X86::VFNMSUBSDr213r:
20718   case X86::VFNMSUBSSr213r:
20719   case X86::VFMADDSUBPDr213r:
20720   case X86::VFMADDSUBPSr213r:
20721   case X86::VFMSUBADDPDr213r:
20722   case X86::VFMSUBADDPSr213r:
20723   case X86::VFMADDPDr213rY:
20724   case X86::VFMADDPSr213rY:
20725   case X86::VFMSUBPDr213rY:
20726   case X86::VFMSUBPSr213rY:
20727   case X86::VFNMADDPDr213rY:
20728   case X86::VFNMADDPSr213rY:
20729   case X86::VFNMSUBPDr213rY:
20730   case X86::VFNMSUBPSr213rY:
20731   case X86::VFMADDSUBPDr213rY:
20732   case X86::VFMADDSUBPSr213rY:
20733   case X86::VFMSUBADDPDr213rY:
20734   case X86::VFMSUBADDPSr213rY:
20735     return emitFMA3Instr(MI, BB);
20736   }
20737 }
20738
20739 //===----------------------------------------------------------------------===//
20740 //                           X86 Optimization Hooks
20741 //===----------------------------------------------------------------------===//
20742
20743 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20744                                                       APInt &KnownZero,
20745                                                       APInt &KnownOne,
20746                                                       const SelectionDAG &DAG,
20747                                                       unsigned Depth) const {
20748   unsigned BitWidth = KnownZero.getBitWidth();
20749   unsigned Opc = Op.getOpcode();
20750   assert((Opc >= ISD::BUILTIN_OP_END ||
20751           Opc == ISD::INTRINSIC_WO_CHAIN ||
20752           Opc == ISD::INTRINSIC_W_CHAIN ||
20753           Opc == ISD::INTRINSIC_VOID) &&
20754          "Should use MaskedValueIsZero if you don't know whether Op"
20755          " is a target node!");
20756
20757   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20758   switch (Opc) {
20759   default: break;
20760   case X86ISD::ADD:
20761   case X86ISD::SUB:
20762   case X86ISD::ADC:
20763   case X86ISD::SBB:
20764   case X86ISD::SMUL:
20765   case X86ISD::UMUL:
20766   case X86ISD::INC:
20767   case X86ISD::DEC:
20768   case X86ISD::OR:
20769   case X86ISD::XOR:
20770   case X86ISD::AND:
20771     // These nodes' second result is a boolean.
20772     if (Op.getResNo() == 0)
20773       break;
20774     // Fallthrough
20775   case X86ISD::SETCC:
20776     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20777     break;
20778   case ISD::INTRINSIC_WO_CHAIN: {
20779     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20780     unsigned NumLoBits = 0;
20781     switch (IntId) {
20782     default: break;
20783     case Intrinsic::x86_sse_movmsk_ps:
20784     case Intrinsic::x86_avx_movmsk_ps_256:
20785     case Intrinsic::x86_sse2_movmsk_pd:
20786     case Intrinsic::x86_avx_movmsk_pd_256:
20787     case Intrinsic::x86_mmx_pmovmskb:
20788     case Intrinsic::x86_sse2_pmovmskb_128:
20789     case Intrinsic::x86_avx2_pmovmskb: {
20790       // High bits of movmskp{s|d}, pmovmskb are known zero.
20791       switch (IntId) {
20792         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20793         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20794         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20795         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20796         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20797         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20798         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20799         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20800       }
20801       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20802       break;
20803     }
20804     }
20805     break;
20806   }
20807   }
20808 }
20809
20810 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20811   SDValue Op,
20812   const SelectionDAG &,
20813   unsigned Depth) const {
20814   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20815   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20816     return Op.getValueType().getScalarType().getSizeInBits();
20817
20818   // Fallback case.
20819   return 1;
20820 }
20821
20822 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20823 /// node is a GlobalAddress + offset.
20824 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20825                                        const GlobalValue* &GA,
20826                                        int64_t &Offset) const {
20827   if (N->getOpcode() == X86ISD::Wrapper) {
20828     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20829       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20830       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20831       return true;
20832     }
20833   }
20834   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20835 }
20836
20837 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20838 /// same as extracting the high 128-bit part of 256-bit vector and then
20839 /// inserting the result into the low part of a new 256-bit vector
20840 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20841   EVT VT = SVOp->getValueType(0);
20842   unsigned NumElems = VT.getVectorNumElements();
20843
20844   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20845   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20846     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20847         SVOp->getMaskElt(j) >= 0)
20848       return false;
20849
20850   return true;
20851 }
20852
20853 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20854 /// same as extracting the low 128-bit part of 256-bit vector and then
20855 /// inserting the result into the high part of a new 256-bit vector
20856 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20857   EVT VT = SVOp->getValueType(0);
20858   unsigned NumElems = VT.getVectorNumElements();
20859
20860   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20861   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20862     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20863         SVOp->getMaskElt(j) >= 0)
20864       return false;
20865
20866   return true;
20867 }
20868
20869 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20870 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20871                                         TargetLowering::DAGCombinerInfo &DCI,
20872                                         const X86Subtarget* Subtarget) {
20873   SDLoc dl(N);
20874   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20875   SDValue V1 = SVOp->getOperand(0);
20876   SDValue V2 = SVOp->getOperand(1);
20877   EVT VT = SVOp->getValueType(0);
20878   unsigned NumElems = VT.getVectorNumElements();
20879
20880   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20881       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20882     //
20883     //                   0,0,0,...
20884     //                      |
20885     //    V      UNDEF    BUILD_VECTOR    UNDEF
20886     //     \      /           \           /
20887     //  CONCAT_VECTOR         CONCAT_VECTOR
20888     //         \                  /
20889     //          \                /
20890     //          RESULT: V + zero extended
20891     //
20892     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20893         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20894         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20895       return SDValue();
20896
20897     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20898       return SDValue();
20899
20900     // To match the shuffle mask, the first half of the mask should
20901     // be exactly the first vector, and all the rest a splat with the
20902     // first element of the second one.
20903     for (unsigned i = 0; i != NumElems/2; ++i)
20904       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20905           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20906         return SDValue();
20907
20908     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20909     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20910       if (Ld->hasNUsesOfValue(1, 0)) {
20911         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20912         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20913         SDValue ResNode =
20914           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20915                                   Ld->getMemoryVT(),
20916                                   Ld->getPointerInfo(),
20917                                   Ld->getAlignment(),
20918                                   false/*isVolatile*/, true/*ReadMem*/,
20919                                   false/*WriteMem*/);
20920
20921         // Make sure the newly-created LOAD is in the same position as Ld in
20922         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20923         // and update uses of Ld's output chain to use the TokenFactor.
20924         if (Ld->hasAnyUseOfValue(1)) {
20925           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20926                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20927           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20928           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20929                                  SDValue(ResNode.getNode(), 1));
20930         }
20931
20932         return DAG.getBitcast(VT, ResNode);
20933       }
20934     }
20935
20936     // Emit a zeroed vector and insert the desired subvector on its
20937     // first half.
20938     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20939     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20940     return DCI.CombineTo(N, InsV);
20941   }
20942
20943   //===--------------------------------------------------------------------===//
20944   // Combine some shuffles into subvector extracts and inserts:
20945   //
20946
20947   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20948   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20949     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20950     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20951     return DCI.CombineTo(N, InsV);
20952   }
20953
20954   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20955   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20956     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20957     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20958     return DCI.CombineTo(N, InsV);
20959   }
20960
20961   return SDValue();
20962 }
20963
20964 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20965 /// possible.
20966 ///
20967 /// This is the leaf of the recursive combinine below. When we have found some
20968 /// chain of single-use x86 shuffle instructions and accumulated the combined
20969 /// shuffle mask represented by them, this will try to pattern match that mask
20970 /// into either a single instruction if there is a special purpose instruction
20971 /// for this operation, or into a PSHUFB instruction which is a fully general
20972 /// instruction but should only be used to replace chains over a certain depth.
20973 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20974                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20975                                    TargetLowering::DAGCombinerInfo &DCI,
20976                                    const X86Subtarget *Subtarget) {
20977   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20978
20979   // Find the operand that enters the chain. Note that multiple uses are OK
20980   // here, we're not going to remove the operand we find.
20981   SDValue Input = Op.getOperand(0);
20982   while (Input.getOpcode() == ISD::BITCAST)
20983     Input = Input.getOperand(0);
20984
20985   MVT VT = Input.getSimpleValueType();
20986   MVT RootVT = Root.getSimpleValueType();
20987   SDLoc DL(Root);
20988
20989   // Just remove no-op shuffle masks.
20990   if (Mask.size() == 1) {
20991     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20992                   /*AddTo*/ true);
20993     return true;
20994   }
20995
20996   // Use the float domain if the operand type is a floating point type.
20997   bool FloatDomain = VT.isFloatingPoint();
20998
20999   // For floating point shuffles, we don't have free copies in the shuffle
21000   // instructions or the ability to load as part of the instruction, so
21001   // canonicalize their shuffles to UNPCK or MOV variants.
21002   //
21003   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
21004   // vectors because it can have a load folded into it that UNPCK cannot. This
21005   // doesn't preclude something switching to the shorter encoding post-RA.
21006   //
21007   // FIXME: Should teach these routines about AVX vector widths.
21008   if (FloatDomain && VT.getSizeInBits() == 128) {
21009     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
21010       bool Lo = Mask.equals({0, 0});
21011       unsigned Shuffle;
21012       MVT ShuffleVT;
21013       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
21014       // is no slower than UNPCKLPD but has the option to fold the input operand
21015       // into even an unaligned memory load.
21016       if (Lo && Subtarget->hasSSE3()) {
21017         Shuffle = X86ISD::MOVDDUP;
21018         ShuffleVT = MVT::v2f64;
21019       } else {
21020         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
21021         // than the UNPCK variants.
21022         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
21023         ShuffleVT = MVT::v4f32;
21024       }
21025       if (Depth == 1 && Root->getOpcode() == Shuffle)
21026         return false; // Nothing to do!
21027       Op = DAG.getBitcast(ShuffleVT, Input);
21028       DCI.AddToWorklist(Op.getNode());
21029       if (Shuffle == X86ISD::MOVDDUP)
21030         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21031       else
21032         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21033       DCI.AddToWorklist(Op.getNode());
21034       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21035                     /*AddTo*/ true);
21036       return true;
21037     }
21038     if (Subtarget->hasSSE3() &&
21039         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21040       bool Lo = Mask.equals({0, 0, 2, 2});
21041       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21042       MVT ShuffleVT = MVT::v4f32;
21043       if (Depth == 1 && Root->getOpcode() == Shuffle)
21044         return false; // Nothing to do!
21045       Op = DAG.getBitcast(ShuffleVT, Input);
21046       DCI.AddToWorklist(Op.getNode());
21047       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21048       DCI.AddToWorklist(Op.getNode());
21049       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21050                     /*AddTo*/ true);
21051       return true;
21052     }
21053     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21054       bool Lo = Mask.equals({0, 0, 1, 1});
21055       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21056       MVT ShuffleVT = MVT::v4f32;
21057       if (Depth == 1 && Root->getOpcode() == Shuffle)
21058         return false; // Nothing to do!
21059       Op = DAG.getBitcast(ShuffleVT, Input);
21060       DCI.AddToWorklist(Op.getNode());
21061       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21062       DCI.AddToWorklist(Op.getNode());
21063       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21064                     /*AddTo*/ true);
21065       return true;
21066     }
21067   }
21068
21069   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21070   // variants as none of these have single-instruction variants that are
21071   // superior to the UNPCK formulation.
21072   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21073       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21074        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21075        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21076        Mask.equals(
21077            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21078     bool Lo = Mask[0] == 0;
21079     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21080     if (Depth == 1 && Root->getOpcode() == Shuffle)
21081       return false; // Nothing to do!
21082     MVT ShuffleVT;
21083     switch (Mask.size()) {
21084     case 8:
21085       ShuffleVT = MVT::v8i16;
21086       break;
21087     case 16:
21088       ShuffleVT = MVT::v16i8;
21089       break;
21090     default:
21091       llvm_unreachable("Impossible mask size!");
21092     };
21093     Op = DAG.getBitcast(ShuffleVT, Input);
21094     DCI.AddToWorklist(Op.getNode());
21095     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21096     DCI.AddToWorklist(Op.getNode());
21097     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21098                   /*AddTo*/ true);
21099     return true;
21100   }
21101
21102   // Don't try to re-form single instruction chains under any circumstances now
21103   // that we've done encoding canonicalization for them.
21104   if (Depth < 2)
21105     return false;
21106
21107   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21108   // can replace them with a single PSHUFB instruction profitably. Intel's
21109   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21110   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21111   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21112     SmallVector<SDValue, 16> PSHUFBMask;
21113     int NumBytes = VT.getSizeInBits() / 8;
21114     int Ratio = NumBytes / Mask.size();
21115     for (int i = 0; i < NumBytes; ++i) {
21116       if (Mask[i / Ratio] == SM_SentinelUndef) {
21117         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21118         continue;
21119       }
21120       int M = Mask[i / Ratio] != SM_SentinelZero
21121                   ? Ratio * Mask[i / Ratio] + i % Ratio
21122                   : 255;
21123       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21124     }
21125     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21126     Op = DAG.getBitcast(ByteVT, Input);
21127     DCI.AddToWorklist(Op.getNode());
21128     SDValue PSHUFBMaskOp =
21129         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21130     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21131     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21132     DCI.AddToWorklist(Op.getNode());
21133     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21134                   /*AddTo*/ true);
21135     return true;
21136   }
21137
21138   // Failed to find any combines.
21139   return false;
21140 }
21141
21142 /// \brief Fully generic combining of x86 shuffle instructions.
21143 ///
21144 /// This should be the last combine run over the x86 shuffle instructions. Once
21145 /// they have been fully optimized, this will recursively consider all chains
21146 /// of single-use shuffle instructions, build a generic model of the cumulative
21147 /// shuffle operation, and check for simpler instructions which implement this
21148 /// operation. We use this primarily for two purposes:
21149 ///
21150 /// 1) Collapse generic shuffles to specialized single instructions when
21151 ///    equivalent. In most cases, this is just an encoding size win, but
21152 ///    sometimes we will collapse multiple generic shuffles into a single
21153 ///    special-purpose shuffle.
21154 /// 2) Look for sequences of shuffle instructions with 3 or more total
21155 ///    instructions, and replace them with the slightly more expensive SSSE3
21156 ///    PSHUFB instruction if available. We do this as the last combining step
21157 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21158 ///    a suitable short sequence of other instructions. The PHUFB will either
21159 ///    use a register or have to read from memory and so is slightly (but only
21160 ///    slightly) more expensive than the other shuffle instructions.
21161 ///
21162 /// Because this is inherently a quadratic operation (for each shuffle in
21163 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21164 /// This should never be an issue in practice as the shuffle lowering doesn't
21165 /// produce sequences of more than 8 instructions.
21166 ///
21167 /// FIXME: We will currently miss some cases where the redundant shuffling
21168 /// would simplify under the threshold for PSHUFB formation because of
21169 /// combine-ordering. To fix this, we should do the redundant instruction
21170 /// combining in this recursive walk.
21171 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21172                                           ArrayRef<int> RootMask,
21173                                           int Depth, bool HasPSHUFB,
21174                                           SelectionDAG &DAG,
21175                                           TargetLowering::DAGCombinerInfo &DCI,
21176                                           const X86Subtarget *Subtarget) {
21177   // Bound the depth of our recursive combine because this is ultimately
21178   // quadratic in nature.
21179   if (Depth > 8)
21180     return false;
21181
21182   // Directly rip through bitcasts to find the underlying operand.
21183   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21184     Op = Op.getOperand(0);
21185
21186   MVT VT = Op.getSimpleValueType();
21187   if (!VT.isVector())
21188     return false; // Bail if we hit a non-vector.
21189
21190   assert(Root.getSimpleValueType().isVector() &&
21191          "Shuffles operate on vector types!");
21192   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21193          "Can only combine shuffles of the same vector register size.");
21194
21195   if (!isTargetShuffle(Op.getOpcode()))
21196     return false;
21197   SmallVector<int, 16> OpMask;
21198   bool IsUnary;
21199   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21200   // We only can combine unary shuffles which we can decode the mask for.
21201   if (!HaveMask || !IsUnary)
21202     return false;
21203
21204   assert(VT.getVectorNumElements() == OpMask.size() &&
21205          "Different mask size from vector size!");
21206   assert(((RootMask.size() > OpMask.size() &&
21207            RootMask.size() % OpMask.size() == 0) ||
21208           (OpMask.size() > RootMask.size() &&
21209            OpMask.size() % RootMask.size() == 0) ||
21210           OpMask.size() == RootMask.size()) &&
21211          "The smaller number of elements must divide the larger.");
21212   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21213   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21214   assert(((RootRatio == 1 && OpRatio == 1) ||
21215           (RootRatio == 1) != (OpRatio == 1)) &&
21216          "Must not have a ratio for both incoming and op masks!");
21217
21218   SmallVector<int, 16> Mask;
21219   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21220
21221   // Merge this shuffle operation's mask into our accumulated mask. Note that
21222   // this shuffle's mask will be the first applied to the input, followed by the
21223   // root mask to get us all the way to the root value arrangement. The reason
21224   // for this order is that we are recursing up the operation chain.
21225   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21226     int RootIdx = i / RootRatio;
21227     if (RootMask[RootIdx] < 0) {
21228       // This is a zero or undef lane, we're done.
21229       Mask.push_back(RootMask[RootIdx]);
21230       continue;
21231     }
21232
21233     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21234     int OpIdx = RootMaskedIdx / OpRatio;
21235     if (OpMask[OpIdx] < 0) {
21236       // The incoming lanes are zero or undef, it doesn't matter which ones we
21237       // are using.
21238       Mask.push_back(OpMask[OpIdx]);
21239       continue;
21240     }
21241
21242     // Ok, we have non-zero lanes, map them through.
21243     Mask.push_back(OpMask[OpIdx] * OpRatio +
21244                    RootMaskedIdx % OpRatio);
21245   }
21246
21247   // See if we can recurse into the operand to combine more things.
21248   switch (Op.getOpcode()) {
21249     case X86ISD::PSHUFB:
21250       HasPSHUFB = true;
21251     case X86ISD::PSHUFD:
21252     case X86ISD::PSHUFHW:
21253     case X86ISD::PSHUFLW:
21254       if (Op.getOperand(0).hasOneUse() &&
21255           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21256                                         HasPSHUFB, DAG, DCI, Subtarget))
21257         return true;
21258       break;
21259
21260     case X86ISD::UNPCKL:
21261     case X86ISD::UNPCKH:
21262       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21263       // We can't check for single use, we have to check that this shuffle is the only user.
21264       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21265           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21266                                         HasPSHUFB, DAG, DCI, Subtarget))
21267           return true;
21268       break;
21269   }
21270
21271   // Minor canonicalization of the accumulated shuffle mask to make it easier
21272   // to match below. All this does is detect masks with squential pairs of
21273   // elements, and shrink them to the half-width mask. It does this in a loop
21274   // so it will reduce the size of the mask to the minimal width mask which
21275   // performs an equivalent shuffle.
21276   SmallVector<int, 16> WidenedMask;
21277   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21278     Mask = std::move(WidenedMask);
21279     WidenedMask.clear();
21280   }
21281
21282   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21283                                 Subtarget);
21284 }
21285
21286 /// \brief Get the PSHUF-style mask from PSHUF node.
21287 ///
21288 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21289 /// PSHUF-style masks that can be reused with such instructions.
21290 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21291   MVT VT = N.getSimpleValueType();
21292   SmallVector<int, 4> Mask;
21293   bool IsUnary;
21294   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21295   (void)HaveMask;
21296   assert(HaveMask);
21297
21298   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21299   // matter. Check that the upper masks are repeats and remove them.
21300   if (VT.getSizeInBits() > 128) {
21301     int LaneElts = 128 / VT.getScalarSizeInBits();
21302 #ifndef NDEBUG
21303     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21304       for (int j = 0; j < LaneElts; ++j)
21305         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21306                "Mask doesn't repeat in high 128-bit lanes!");
21307 #endif
21308     Mask.resize(LaneElts);
21309   }
21310
21311   switch (N.getOpcode()) {
21312   case X86ISD::PSHUFD:
21313     return Mask;
21314   case X86ISD::PSHUFLW:
21315     Mask.resize(4);
21316     return Mask;
21317   case X86ISD::PSHUFHW:
21318     Mask.erase(Mask.begin(), Mask.begin() + 4);
21319     for (int &M : Mask)
21320       M -= 4;
21321     return Mask;
21322   default:
21323     llvm_unreachable("No valid shuffle instruction found!");
21324   }
21325 }
21326
21327 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21328 ///
21329 /// We walk up the chain and look for a combinable shuffle, skipping over
21330 /// shuffles that we could hoist this shuffle's transformation past without
21331 /// altering anything.
21332 static SDValue
21333 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21334                              SelectionDAG &DAG,
21335                              TargetLowering::DAGCombinerInfo &DCI) {
21336   assert(N.getOpcode() == X86ISD::PSHUFD &&
21337          "Called with something other than an x86 128-bit half shuffle!");
21338   SDLoc DL(N);
21339
21340   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21341   // of the shuffles in the chain so that we can form a fresh chain to replace
21342   // this one.
21343   SmallVector<SDValue, 8> Chain;
21344   SDValue V = N.getOperand(0);
21345   for (; V.hasOneUse(); V = V.getOperand(0)) {
21346     switch (V.getOpcode()) {
21347     default:
21348       return SDValue(); // Nothing combined!
21349
21350     case ISD::BITCAST:
21351       // Skip bitcasts as we always know the type for the target specific
21352       // instructions.
21353       continue;
21354
21355     case X86ISD::PSHUFD:
21356       // Found another dword shuffle.
21357       break;
21358
21359     case X86ISD::PSHUFLW:
21360       // Check that the low words (being shuffled) are the identity in the
21361       // dword shuffle, and the high words are self-contained.
21362       if (Mask[0] != 0 || Mask[1] != 1 ||
21363           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21364         return SDValue();
21365
21366       Chain.push_back(V);
21367       continue;
21368
21369     case X86ISD::PSHUFHW:
21370       // Check that the high words (being shuffled) are the identity in the
21371       // dword shuffle, and the low words are self-contained.
21372       if (Mask[2] != 2 || Mask[3] != 3 ||
21373           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21374         return SDValue();
21375
21376       Chain.push_back(V);
21377       continue;
21378
21379     case X86ISD::UNPCKL:
21380     case X86ISD::UNPCKH:
21381       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21382       // shuffle into a preceding word shuffle.
21383       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21384           V.getSimpleValueType().getScalarType() != MVT::i16)
21385         return SDValue();
21386
21387       // Search for a half-shuffle which we can combine with.
21388       unsigned CombineOp =
21389           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21390       if (V.getOperand(0) != V.getOperand(1) ||
21391           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21392         return SDValue();
21393       Chain.push_back(V);
21394       V = V.getOperand(0);
21395       do {
21396         switch (V.getOpcode()) {
21397         default:
21398           return SDValue(); // Nothing to combine.
21399
21400         case X86ISD::PSHUFLW:
21401         case X86ISD::PSHUFHW:
21402           if (V.getOpcode() == CombineOp)
21403             break;
21404
21405           Chain.push_back(V);
21406
21407           // Fallthrough!
21408         case ISD::BITCAST:
21409           V = V.getOperand(0);
21410           continue;
21411         }
21412         break;
21413       } while (V.hasOneUse());
21414       break;
21415     }
21416     // Break out of the loop if we break out of the switch.
21417     break;
21418   }
21419
21420   if (!V.hasOneUse())
21421     // We fell out of the loop without finding a viable combining instruction.
21422     return SDValue();
21423
21424   // Merge this node's mask and our incoming mask.
21425   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21426   for (int &M : Mask)
21427     M = VMask[M];
21428   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21429                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21430
21431   // Rebuild the chain around this new shuffle.
21432   while (!Chain.empty()) {
21433     SDValue W = Chain.pop_back_val();
21434
21435     if (V.getValueType() != W.getOperand(0).getValueType())
21436       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21437
21438     switch (W.getOpcode()) {
21439     default:
21440       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21441
21442     case X86ISD::UNPCKL:
21443     case X86ISD::UNPCKH:
21444       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21445       break;
21446
21447     case X86ISD::PSHUFD:
21448     case X86ISD::PSHUFLW:
21449     case X86ISD::PSHUFHW:
21450       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21451       break;
21452     }
21453   }
21454   if (V.getValueType() != N.getValueType())
21455     V = DAG.getBitcast(N.getValueType(), V);
21456
21457   // Return the new chain to replace N.
21458   return V;
21459 }
21460
21461 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21462 ///
21463 /// We walk up the chain, skipping shuffles of the other half and looking
21464 /// through shuffles which switch halves trying to find a shuffle of the same
21465 /// pair of dwords.
21466 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21467                                         SelectionDAG &DAG,
21468                                         TargetLowering::DAGCombinerInfo &DCI) {
21469   assert(
21470       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21471       "Called with something other than an x86 128-bit half shuffle!");
21472   SDLoc DL(N);
21473   unsigned CombineOpcode = N.getOpcode();
21474
21475   // Walk up a single-use chain looking for a combinable shuffle.
21476   SDValue V = N.getOperand(0);
21477   for (; V.hasOneUse(); V = V.getOperand(0)) {
21478     switch (V.getOpcode()) {
21479     default:
21480       return false; // Nothing combined!
21481
21482     case ISD::BITCAST:
21483       // Skip bitcasts as we always know the type for the target specific
21484       // instructions.
21485       continue;
21486
21487     case X86ISD::PSHUFLW:
21488     case X86ISD::PSHUFHW:
21489       if (V.getOpcode() == CombineOpcode)
21490         break;
21491
21492       // Other-half shuffles are no-ops.
21493       continue;
21494     }
21495     // Break out of the loop if we break out of the switch.
21496     break;
21497   }
21498
21499   if (!V.hasOneUse())
21500     // We fell out of the loop without finding a viable combining instruction.
21501     return false;
21502
21503   // Combine away the bottom node as its shuffle will be accumulated into
21504   // a preceding shuffle.
21505   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21506
21507   // Record the old value.
21508   SDValue Old = V;
21509
21510   // Merge this node's mask and our incoming mask (adjusted to account for all
21511   // the pshufd instructions encountered).
21512   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21513   for (int &M : Mask)
21514     M = VMask[M];
21515   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21516                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21517
21518   // Check that the shuffles didn't cancel each other out. If not, we need to
21519   // combine to the new one.
21520   if (Old != V)
21521     // Replace the combinable shuffle with the combined one, updating all users
21522     // so that we re-evaluate the chain here.
21523     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21524
21525   return true;
21526 }
21527
21528 /// \brief Try to combine x86 target specific shuffles.
21529 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21530                                            TargetLowering::DAGCombinerInfo &DCI,
21531                                            const X86Subtarget *Subtarget) {
21532   SDLoc DL(N);
21533   MVT VT = N.getSimpleValueType();
21534   SmallVector<int, 4> Mask;
21535
21536   switch (N.getOpcode()) {
21537   case X86ISD::PSHUFD:
21538   case X86ISD::PSHUFLW:
21539   case X86ISD::PSHUFHW:
21540     Mask = getPSHUFShuffleMask(N);
21541     assert(Mask.size() == 4);
21542     break;
21543   default:
21544     return SDValue();
21545   }
21546
21547   // Nuke no-op shuffles that show up after combining.
21548   if (isNoopShuffleMask(Mask))
21549     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21550
21551   // Look for simplifications involving one or two shuffle instructions.
21552   SDValue V = N.getOperand(0);
21553   switch (N.getOpcode()) {
21554   default:
21555     break;
21556   case X86ISD::PSHUFLW:
21557   case X86ISD::PSHUFHW:
21558     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21559
21560     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21561       return SDValue(); // We combined away this shuffle, so we're done.
21562
21563     // See if this reduces to a PSHUFD which is no more expensive and can
21564     // combine with more operations. Note that it has to at least flip the
21565     // dwords as otherwise it would have been removed as a no-op.
21566     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21567       int DMask[] = {0, 1, 2, 3};
21568       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21569       DMask[DOffset + 0] = DOffset + 1;
21570       DMask[DOffset + 1] = DOffset + 0;
21571       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21572       V = DAG.getBitcast(DVT, V);
21573       DCI.AddToWorklist(V.getNode());
21574       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21575                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21576       DCI.AddToWorklist(V.getNode());
21577       return DAG.getBitcast(VT, V);
21578     }
21579
21580     // Look for shuffle patterns which can be implemented as a single unpack.
21581     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21582     // only works when we have a PSHUFD followed by two half-shuffles.
21583     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21584         (V.getOpcode() == X86ISD::PSHUFLW ||
21585          V.getOpcode() == X86ISD::PSHUFHW) &&
21586         V.getOpcode() != N.getOpcode() &&
21587         V.hasOneUse()) {
21588       SDValue D = V.getOperand(0);
21589       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21590         D = D.getOperand(0);
21591       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21592         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21593         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21594         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21595         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21596         int WordMask[8];
21597         for (int i = 0; i < 4; ++i) {
21598           WordMask[i + NOffset] = Mask[i] + NOffset;
21599           WordMask[i + VOffset] = VMask[i] + VOffset;
21600         }
21601         // Map the word mask through the DWord mask.
21602         int MappedMask[8];
21603         for (int i = 0; i < 8; ++i)
21604           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21605         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21606             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21607           // We can replace all three shuffles with an unpack.
21608           V = DAG.getBitcast(VT, D.getOperand(0));
21609           DCI.AddToWorklist(V.getNode());
21610           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21611                                                 : X86ISD::UNPCKH,
21612                              DL, VT, V, V);
21613         }
21614       }
21615     }
21616
21617     break;
21618
21619   case X86ISD::PSHUFD:
21620     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21621       return NewN;
21622
21623     break;
21624   }
21625
21626   return SDValue();
21627 }
21628
21629 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21630 ///
21631 /// We combine this directly on the abstract vector shuffle nodes so it is
21632 /// easier to generically match. We also insert dummy vector shuffle nodes for
21633 /// the operands which explicitly discard the lanes which are unused by this
21634 /// operation to try to flow through the rest of the combiner the fact that
21635 /// they're unused.
21636 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21637   SDLoc DL(N);
21638   EVT VT = N->getValueType(0);
21639
21640   // We only handle target-independent shuffles.
21641   // FIXME: It would be easy and harmless to use the target shuffle mask
21642   // extraction tool to support more.
21643   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21644     return SDValue();
21645
21646   auto *SVN = cast<ShuffleVectorSDNode>(N);
21647   ArrayRef<int> Mask = SVN->getMask();
21648   SDValue V1 = N->getOperand(0);
21649   SDValue V2 = N->getOperand(1);
21650
21651   // We require the first shuffle operand to be the SUB node, and the second to
21652   // be the ADD node.
21653   // FIXME: We should support the commuted patterns.
21654   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21655     return SDValue();
21656
21657   // If there are other uses of these operations we can't fold them.
21658   if (!V1->hasOneUse() || !V2->hasOneUse())
21659     return SDValue();
21660
21661   // Ensure that both operations have the same operands. Note that we can
21662   // commute the FADD operands.
21663   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21664   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21665       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21666     return SDValue();
21667
21668   // We're looking for blends between FADD and FSUB nodes. We insist on these
21669   // nodes being lined up in a specific expected pattern.
21670   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21671         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21672         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21673     return SDValue();
21674
21675   // Only specific types are legal at this point, assert so we notice if and
21676   // when these change.
21677   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21678           VT == MVT::v4f64) &&
21679          "Unknown vector type encountered!");
21680
21681   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21682 }
21683
21684 /// PerformShuffleCombine - Performs several different shuffle combines.
21685 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21686                                      TargetLowering::DAGCombinerInfo &DCI,
21687                                      const X86Subtarget *Subtarget) {
21688   SDLoc dl(N);
21689   SDValue N0 = N->getOperand(0);
21690   SDValue N1 = N->getOperand(1);
21691   EVT VT = N->getValueType(0);
21692
21693   // Don't create instructions with illegal types after legalize types has run.
21694   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21695   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21696     return SDValue();
21697
21698   // If we have legalized the vector types, look for blends of FADD and FSUB
21699   // nodes that we can fuse into an ADDSUB node.
21700   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21701     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21702       return AddSub;
21703
21704   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21705   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21706       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21707     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21708
21709   // During Type Legalization, when promoting illegal vector types,
21710   // the backend might introduce new shuffle dag nodes and bitcasts.
21711   //
21712   // This code performs the following transformation:
21713   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21714   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21715   //
21716   // We do this only if both the bitcast and the BINOP dag nodes have
21717   // one use. Also, perform this transformation only if the new binary
21718   // operation is legal. This is to avoid introducing dag nodes that
21719   // potentially need to be further expanded (or custom lowered) into a
21720   // less optimal sequence of dag nodes.
21721   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21722       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21723       N0.getOpcode() == ISD::BITCAST) {
21724     SDValue BC0 = N0.getOperand(0);
21725     EVT SVT = BC0.getValueType();
21726     unsigned Opcode = BC0.getOpcode();
21727     unsigned NumElts = VT.getVectorNumElements();
21728
21729     if (BC0.hasOneUse() && SVT.isVector() &&
21730         SVT.getVectorNumElements() * 2 == NumElts &&
21731         TLI.isOperationLegal(Opcode, VT)) {
21732       bool CanFold = false;
21733       switch (Opcode) {
21734       default : break;
21735       case ISD::ADD :
21736       case ISD::FADD :
21737       case ISD::SUB :
21738       case ISD::FSUB :
21739       case ISD::MUL :
21740       case ISD::FMUL :
21741         CanFold = true;
21742       }
21743
21744       unsigned SVTNumElts = SVT.getVectorNumElements();
21745       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21746       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21747         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21748       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21749         CanFold = SVOp->getMaskElt(i) < 0;
21750
21751       if (CanFold) {
21752         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21753         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21754         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21755         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21756       }
21757     }
21758   }
21759
21760   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21761   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21762   // consecutive, non-overlapping, and in the right order.
21763   SmallVector<SDValue, 16> Elts;
21764   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21765     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21766
21767   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21768     return LD;
21769
21770   if (isTargetShuffle(N->getOpcode())) {
21771     SDValue Shuffle =
21772         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21773     if (Shuffle.getNode())
21774       return Shuffle;
21775
21776     // Try recursively combining arbitrary sequences of x86 shuffle
21777     // instructions into higher-order shuffles. We do this after combining
21778     // specific PSHUF instruction sequences into their minimal form so that we
21779     // can evaluate how many specialized shuffle instructions are involved in
21780     // a particular chain.
21781     SmallVector<int, 1> NonceMask; // Just a placeholder.
21782     NonceMask.push_back(0);
21783     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21784                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21785                                       DCI, Subtarget))
21786       return SDValue(); // This routine will use CombineTo to replace N.
21787   }
21788
21789   return SDValue();
21790 }
21791
21792 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21793 /// specific shuffle of a load can be folded into a single element load.
21794 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21795 /// shuffles have been custom lowered so we need to handle those here.
21796 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21797                                          TargetLowering::DAGCombinerInfo &DCI) {
21798   if (DCI.isBeforeLegalizeOps())
21799     return SDValue();
21800
21801   SDValue InVec = N->getOperand(0);
21802   SDValue EltNo = N->getOperand(1);
21803
21804   if (!isa<ConstantSDNode>(EltNo))
21805     return SDValue();
21806
21807   EVT OriginalVT = InVec.getValueType();
21808
21809   if (InVec.getOpcode() == ISD::BITCAST) {
21810     // Don't duplicate a load with other uses.
21811     if (!InVec.hasOneUse())
21812       return SDValue();
21813     EVT BCVT = InVec.getOperand(0).getValueType();
21814     if (!BCVT.isVector() ||
21815         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21816       return SDValue();
21817     InVec = InVec.getOperand(0);
21818   }
21819
21820   EVT CurrentVT = InVec.getValueType();
21821
21822   if (!isTargetShuffle(InVec.getOpcode()))
21823     return SDValue();
21824
21825   // Don't duplicate a load with other uses.
21826   if (!InVec.hasOneUse())
21827     return SDValue();
21828
21829   SmallVector<int, 16> ShuffleMask;
21830   bool UnaryShuffle;
21831   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21832                             ShuffleMask, UnaryShuffle))
21833     return SDValue();
21834
21835   // Select the input vector, guarding against out of range extract vector.
21836   unsigned NumElems = CurrentVT.getVectorNumElements();
21837   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21838   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21839   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21840                                          : InVec.getOperand(1);
21841
21842   // If inputs to shuffle are the same for both ops, then allow 2 uses
21843   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21844                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21845
21846   if (LdNode.getOpcode() == ISD::BITCAST) {
21847     // Don't duplicate a load with other uses.
21848     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21849       return SDValue();
21850
21851     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21852     LdNode = LdNode.getOperand(0);
21853   }
21854
21855   if (!ISD::isNormalLoad(LdNode.getNode()))
21856     return SDValue();
21857
21858   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21859
21860   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21861     return SDValue();
21862
21863   EVT EltVT = N->getValueType(0);
21864   // If there's a bitcast before the shuffle, check if the load type and
21865   // alignment is valid.
21866   unsigned Align = LN0->getAlignment();
21867   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21868   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21869       EltVT.getTypeForEVT(*DAG.getContext()));
21870
21871   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21872     return SDValue();
21873
21874   // All checks match so transform back to vector_shuffle so that DAG combiner
21875   // can finish the job
21876   SDLoc dl(N);
21877
21878   // Create shuffle node taking into account the case that its a unary shuffle
21879   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21880                                    : InVec.getOperand(1);
21881   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21882                                  InVec.getOperand(0), Shuffle,
21883                                  &ShuffleMask[0]);
21884   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21885   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21886                      EltNo);
21887 }
21888
21889 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21890 /// special and don't usually play with other vector types, it's better to
21891 /// handle them early to be sure we emit efficient code by avoiding
21892 /// store-load conversions.
21893 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21894   if (N->getValueType(0) != MVT::x86mmx ||
21895       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21896       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21897     return SDValue();
21898
21899   SDValue V = N->getOperand(0);
21900   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21901   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21902     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21903                        N->getValueType(0), V.getOperand(0));
21904
21905   return SDValue();
21906 }
21907
21908 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21909 /// generation and convert it from being a bunch of shuffles and extracts
21910 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21911 /// storing the value and loading scalars back, while for x64 we should
21912 /// use 64-bit extracts and shifts.
21913 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21914                                          TargetLowering::DAGCombinerInfo &DCI) {
21915   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21916     return NewOp;
21917
21918   SDValue InputVector = N->getOperand(0);
21919   SDLoc dl(InputVector);
21920   // Detect mmx to i32 conversion through a v2i32 elt extract.
21921   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21922       N->getValueType(0) == MVT::i32 &&
21923       InputVector.getValueType() == MVT::v2i32) {
21924
21925     // The bitcast source is a direct mmx result.
21926     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21927     if (MMXSrc.getValueType() == MVT::x86mmx)
21928       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21929                          N->getValueType(0),
21930                          InputVector.getNode()->getOperand(0));
21931
21932     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21933     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21934     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21935         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21936         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21937         MMXSrcOp.getValueType() == MVT::v1i64 &&
21938         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21939       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21940                          N->getValueType(0),
21941                          MMXSrcOp.getOperand(0));
21942   }
21943
21944   EVT VT = N->getValueType(0);
21945
21946   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21947       InputVector.getOpcode() == ISD::BITCAST &&
21948       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21949     uint64_t ExtractedElt =
21950           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21951     uint64_t InputValue =
21952           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21953     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21954     return DAG.getConstant(Res, dl, MVT::i1);
21955   }
21956   // Only operate on vectors of 4 elements, where the alternative shuffling
21957   // gets to be more expensive.
21958   if (InputVector.getValueType() != MVT::v4i32)
21959     return SDValue();
21960
21961   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21962   // single use which is a sign-extend or zero-extend, and all elements are
21963   // used.
21964   SmallVector<SDNode *, 4> Uses;
21965   unsigned ExtractedElements = 0;
21966   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21967        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21968     if (UI.getUse().getResNo() != InputVector.getResNo())
21969       return SDValue();
21970
21971     SDNode *Extract = *UI;
21972     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21973       return SDValue();
21974
21975     if (Extract->getValueType(0) != MVT::i32)
21976       return SDValue();
21977     if (!Extract->hasOneUse())
21978       return SDValue();
21979     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21980         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21981       return SDValue();
21982     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21983       return SDValue();
21984
21985     // Record which element was extracted.
21986     ExtractedElements |=
21987       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21988
21989     Uses.push_back(Extract);
21990   }
21991
21992   // If not all the elements were used, this may not be worthwhile.
21993   if (ExtractedElements != 15)
21994     return SDValue();
21995
21996   // Ok, we've now decided to do the transformation.
21997   // If 64-bit shifts are legal, use the extract-shift sequence,
21998   // otherwise bounce the vector off the cache.
21999   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22000   SDValue Vals[4];
22001
22002   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
22003     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
22004     auto &DL = DAG.getDataLayout();
22005     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
22006     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22007       DAG.getConstant(0, dl, VecIdxTy));
22008     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
22009       DAG.getConstant(1, dl, VecIdxTy));
22010
22011     SDValue ShAmt = DAG.getConstant(
22012         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
22013     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
22014     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22015       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
22016     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
22017     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
22018       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
22019   } else {
22020     // Store the value to a temporary stack slot.
22021     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
22022     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
22023       MachinePointerInfo(), false, false, 0);
22024
22025     EVT ElementType = InputVector.getValueType().getVectorElementType();
22026     unsigned EltSize = ElementType.getSizeInBits() / 8;
22027
22028     // Replace each use (extract) with a load of the appropriate element.
22029     for (unsigned i = 0; i < 4; ++i) {
22030       uint64_t Offset = EltSize * i;
22031       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
22032       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
22033
22034       SDValue ScalarAddr =
22035           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
22036
22037       // Load the scalar.
22038       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22039                             ScalarAddr, MachinePointerInfo(),
22040                             false, false, false, 0);
22041
22042     }
22043   }
22044
22045   // Replace the extracts
22046   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22047     UE = Uses.end(); UI != UE; ++UI) {
22048     SDNode *Extract = *UI;
22049
22050     SDValue Idx = Extract->getOperand(1);
22051     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22052     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22053   }
22054
22055   // The replacement was made in place; don't return anything.
22056   return SDValue();
22057 }
22058
22059 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22060 static std::pair<unsigned, bool>
22061 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22062                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22063   if (!VT.isVector())
22064     return std::make_pair(0, false);
22065
22066   bool NeedSplit = false;
22067   switch (VT.getSimpleVT().SimpleTy) {
22068   default: return std::make_pair(0, false);
22069   case MVT::v4i64:
22070   case MVT::v2i64:
22071     if (!Subtarget->hasVLX())
22072       return std::make_pair(0, false);
22073     break;
22074   case MVT::v64i8:
22075   case MVT::v32i16:
22076     if (!Subtarget->hasBWI())
22077       return std::make_pair(0, false);
22078     break;
22079   case MVT::v16i32:
22080   case MVT::v8i64:
22081     if (!Subtarget->hasAVX512())
22082       return std::make_pair(0, false);
22083     break;
22084   case MVT::v32i8:
22085   case MVT::v16i16:
22086   case MVT::v8i32:
22087     if (!Subtarget->hasAVX2())
22088       NeedSplit = true;
22089     if (!Subtarget->hasAVX())
22090       return std::make_pair(0, false);
22091     break;
22092   case MVT::v16i8:
22093   case MVT::v8i16:
22094   case MVT::v4i32:
22095     if (!Subtarget->hasSSE2())
22096       return std::make_pair(0, false);
22097   }
22098
22099   // SSE2 has only a small subset of the operations.
22100   bool hasUnsigned = Subtarget->hasSSE41() ||
22101                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22102   bool hasSigned = Subtarget->hasSSE41() ||
22103                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22104
22105   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22106
22107   unsigned Opc = 0;
22108   // Check for x CC y ? x : y.
22109   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22110       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22111     switch (CC) {
22112     default: break;
22113     case ISD::SETULT:
22114     case ISD::SETULE:
22115       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22116     case ISD::SETUGT:
22117     case ISD::SETUGE:
22118       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22119     case ISD::SETLT:
22120     case ISD::SETLE:
22121       Opc = hasSigned ? ISD::SMIN : 0; break;
22122     case ISD::SETGT:
22123     case ISD::SETGE:
22124       Opc = hasSigned ? ISD::SMAX : 0; break;
22125     }
22126   // Check for x CC y ? y : x -- a min/max with reversed arms.
22127   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22128              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22129     switch (CC) {
22130     default: break;
22131     case ISD::SETULT:
22132     case ISD::SETULE:
22133       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22134     case ISD::SETUGT:
22135     case ISD::SETUGE:
22136       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22137     case ISD::SETLT:
22138     case ISD::SETLE:
22139       Opc = hasSigned ? ISD::SMAX : 0; break;
22140     case ISD::SETGT:
22141     case ISD::SETGE:
22142       Opc = hasSigned ? ISD::SMIN : 0; break;
22143     }
22144   }
22145
22146   return std::make_pair(Opc, NeedSplit);
22147 }
22148
22149 static SDValue
22150 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22151                                       const X86Subtarget *Subtarget) {
22152   SDLoc dl(N);
22153   SDValue Cond = N->getOperand(0);
22154   SDValue LHS = N->getOperand(1);
22155   SDValue RHS = N->getOperand(2);
22156
22157   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22158     SDValue CondSrc = Cond->getOperand(0);
22159     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22160       Cond = CondSrc->getOperand(0);
22161   }
22162
22163   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22164     return SDValue();
22165
22166   // A vselect where all conditions and data are constants can be optimized into
22167   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22168   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22169       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22170     return SDValue();
22171
22172   unsigned MaskValue = 0;
22173   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22174     return SDValue();
22175
22176   MVT VT = N->getSimpleValueType(0);
22177   unsigned NumElems = VT.getVectorNumElements();
22178   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22179   for (unsigned i = 0; i < NumElems; ++i) {
22180     // Be sure we emit undef where we can.
22181     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22182       ShuffleMask[i] = -1;
22183     else
22184       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22185   }
22186
22187   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22188   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22189     return SDValue();
22190   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22191 }
22192
22193 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22194 /// nodes.
22195 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22196                                     TargetLowering::DAGCombinerInfo &DCI,
22197                                     const X86Subtarget *Subtarget) {
22198   SDLoc DL(N);
22199   SDValue Cond = N->getOperand(0);
22200   // Get the LHS/RHS of the select.
22201   SDValue LHS = N->getOperand(1);
22202   SDValue RHS = N->getOperand(2);
22203   EVT VT = LHS.getValueType();
22204   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22205
22206   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22207   // instructions match the semantics of the common C idiom x<y?x:y but not
22208   // x<=y?x:y, because of how they handle negative zero (which can be
22209   // ignored in unsafe-math mode).
22210   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22211   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22212       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22213       (Subtarget->hasSSE2() ||
22214        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22215     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22216
22217     unsigned Opcode = 0;
22218     // Check for x CC y ? x : y.
22219     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22220         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22221       switch (CC) {
22222       default: break;
22223       case ISD::SETULT:
22224         // Converting this to a min would handle NaNs incorrectly, and swapping
22225         // the operands would cause it to handle comparisons between positive
22226         // and negative zero incorrectly.
22227         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22228           if (!DAG.getTarget().Options.UnsafeFPMath &&
22229               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22230             break;
22231           std::swap(LHS, RHS);
22232         }
22233         Opcode = X86ISD::FMIN;
22234         break;
22235       case ISD::SETOLE:
22236         // Converting this to a min would handle comparisons between positive
22237         // and negative zero incorrectly.
22238         if (!DAG.getTarget().Options.UnsafeFPMath &&
22239             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22240           break;
22241         Opcode = X86ISD::FMIN;
22242         break;
22243       case ISD::SETULE:
22244         // Converting this to a min would handle both negative zeros and NaNs
22245         // incorrectly, but we can swap the operands to fix both.
22246         std::swap(LHS, RHS);
22247       case ISD::SETOLT:
22248       case ISD::SETLT:
22249       case ISD::SETLE:
22250         Opcode = X86ISD::FMIN;
22251         break;
22252
22253       case ISD::SETOGE:
22254         // Converting this to a max would handle comparisons between positive
22255         // and negative zero incorrectly.
22256         if (!DAG.getTarget().Options.UnsafeFPMath &&
22257             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22258           break;
22259         Opcode = X86ISD::FMAX;
22260         break;
22261       case ISD::SETUGT:
22262         // Converting this to a max would handle NaNs incorrectly, and swapping
22263         // the operands would cause it to handle comparisons between positive
22264         // and negative zero incorrectly.
22265         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22266           if (!DAG.getTarget().Options.UnsafeFPMath &&
22267               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22268             break;
22269           std::swap(LHS, RHS);
22270         }
22271         Opcode = X86ISD::FMAX;
22272         break;
22273       case ISD::SETUGE:
22274         // Converting this to a max would handle both negative zeros and NaNs
22275         // incorrectly, but we can swap the operands to fix both.
22276         std::swap(LHS, RHS);
22277       case ISD::SETOGT:
22278       case ISD::SETGT:
22279       case ISD::SETGE:
22280         Opcode = X86ISD::FMAX;
22281         break;
22282       }
22283     // Check for x CC y ? y : x -- a min/max with reversed arms.
22284     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22285                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22286       switch (CC) {
22287       default: break;
22288       case ISD::SETOGE:
22289         // Converting this to a min would handle comparisons between positive
22290         // and negative zero incorrectly, and swapping the operands would
22291         // cause it to handle NaNs incorrectly.
22292         if (!DAG.getTarget().Options.UnsafeFPMath &&
22293             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22294           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22295             break;
22296           std::swap(LHS, RHS);
22297         }
22298         Opcode = X86ISD::FMIN;
22299         break;
22300       case ISD::SETUGT:
22301         // Converting this to a min would handle NaNs incorrectly.
22302         if (!DAG.getTarget().Options.UnsafeFPMath &&
22303             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22304           break;
22305         Opcode = X86ISD::FMIN;
22306         break;
22307       case ISD::SETUGE:
22308         // Converting this to a min would handle both negative zeros and NaNs
22309         // incorrectly, but we can swap the operands to fix both.
22310         std::swap(LHS, RHS);
22311       case ISD::SETOGT:
22312       case ISD::SETGT:
22313       case ISD::SETGE:
22314         Opcode = X86ISD::FMIN;
22315         break;
22316
22317       case ISD::SETULT:
22318         // Converting this to a max would handle NaNs incorrectly.
22319         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22320           break;
22321         Opcode = X86ISD::FMAX;
22322         break;
22323       case ISD::SETOLE:
22324         // Converting this to a max would handle comparisons between positive
22325         // and negative zero incorrectly, and swapping the operands would
22326         // cause it to handle NaNs incorrectly.
22327         if (!DAG.getTarget().Options.UnsafeFPMath &&
22328             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22329           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22330             break;
22331           std::swap(LHS, RHS);
22332         }
22333         Opcode = X86ISD::FMAX;
22334         break;
22335       case ISD::SETULE:
22336         // Converting this to a max would handle both negative zeros and NaNs
22337         // incorrectly, but we can swap the operands to fix both.
22338         std::swap(LHS, RHS);
22339       case ISD::SETOLT:
22340       case ISD::SETLT:
22341       case ISD::SETLE:
22342         Opcode = X86ISD::FMAX;
22343         break;
22344       }
22345     }
22346
22347     if (Opcode)
22348       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22349   }
22350
22351   EVT CondVT = Cond.getValueType();
22352   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22353       CondVT.getVectorElementType() == MVT::i1) {
22354     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22355     // lowering on KNL. In this case we convert it to
22356     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22357     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22358     // Since SKX these selects have a proper lowering.
22359     EVT OpVT = LHS.getValueType();
22360     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22361         (OpVT.getVectorElementType() == MVT::i8 ||
22362          OpVT.getVectorElementType() == MVT::i16) &&
22363         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22364       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22365       DCI.AddToWorklist(Cond.getNode());
22366       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22367     }
22368   }
22369   // If this is a select between two integer constants, try to do some
22370   // optimizations.
22371   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22372     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22373       // Don't do this for crazy integer types.
22374       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22375         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22376         // so that TrueC (the true value) is larger than FalseC.
22377         bool NeedsCondInvert = false;
22378
22379         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22380             // Efficiently invertible.
22381             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22382              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22383               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22384           NeedsCondInvert = true;
22385           std::swap(TrueC, FalseC);
22386         }
22387
22388         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22389         if (FalseC->getAPIntValue() == 0 &&
22390             TrueC->getAPIntValue().isPowerOf2()) {
22391           if (NeedsCondInvert) // Invert the condition if needed.
22392             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22393                                DAG.getConstant(1, DL, Cond.getValueType()));
22394
22395           // Zero extend the condition if needed.
22396           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22397
22398           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22399           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22400                              DAG.getConstant(ShAmt, DL, MVT::i8));
22401         }
22402
22403         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22404         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22405           if (NeedsCondInvert) // Invert the condition if needed.
22406             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22407                                DAG.getConstant(1, DL, Cond.getValueType()));
22408
22409           // Zero extend the condition if needed.
22410           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22411                              FalseC->getValueType(0), Cond);
22412           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22413                              SDValue(FalseC, 0));
22414         }
22415
22416         // Optimize cases that will turn into an LEA instruction.  This requires
22417         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22418         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22419           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22420           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22421
22422           bool isFastMultiplier = false;
22423           if (Diff < 10) {
22424             switch ((unsigned char)Diff) {
22425               default: break;
22426               case 1:  // result = add base, cond
22427               case 2:  // result = lea base(    , cond*2)
22428               case 3:  // result = lea base(cond, cond*2)
22429               case 4:  // result = lea base(    , cond*4)
22430               case 5:  // result = lea base(cond, cond*4)
22431               case 8:  // result = lea base(    , cond*8)
22432               case 9:  // result = lea base(cond, cond*8)
22433                 isFastMultiplier = true;
22434                 break;
22435             }
22436           }
22437
22438           if (isFastMultiplier) {
22439             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22440             if (NeedsCondInvert) // Invert the condition if needed.
22441               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22442                                  DAG.getConstant(1, DL, Cond.getValueType()));
22443
22444             // Zero extend the condition if needed.
22445             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22446                                Cond);
22447             // Scale the condition by the difference.
22448             if (Diff != 1)
22449               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22450                                  DAG.getConstant(Diff, DL,
22451                                                  Cond.getValueType()));
22452
22453             // Add the base if non-zero.
22454             if (FalseC->getAPIntValue() != 0)
22455               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22456                                  SDValue(FalseC, 0));
22457             return Cond;
22458           }
22459         }
22460       }
22461   }
22462
22463   // Canonicalize max and min:
22464   // (x > y) ? x : y -> (x >= y) ? x : y
22465   // (x < y) ? x : y -> (x <= y) ? x : y
22466   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22467   // the need for an extra compare
22468   // against zero. e.g.
22469   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22470   // subl   %esi, %edi
22471   // testl  %edi, %edi
22472   // movl   $0, %eax
22473   // cmovgl %edi, %eax
22474   // =>
22475   // xorl   %eax, %eax
22476   // subl   %esi, $edi
22477   // cmovsl %eax, %edi
22478   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22479       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22480       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22481     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22482     switch (CC) {
22483     default: break;
22484     case ISD::SETLT:
22485     case ISD::SETGT: {
22486       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22487       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22488                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22489       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22490     }
22491     }
22492   }
22493
22494   // Early exit check
22495   if (!TLI.isTypeLegal(VT))
22496     return SDValue();
22497
22498   // Match VSELECTs into subs with unsigned saturation.
22499   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22500       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22501       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22502        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22503     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22504
22505     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22506     // left side invert the predicate to simplify logic below.
22507     SDValue Other;
22508     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22509       Other = RHS;
22510       CC = ISD::getSetCCInverse(CC, true);
22511     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22512       Other = LHS;
22513     }
22514
22515     if (Other.getNode() && Other->getNumOperands() == 2 &&
22516         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22517       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22518       SDValue CondRHS = Cond->getOperand(1);
22519
22520       // Look for a general sub with unsigned saturation first.
22521       // x >= y ? x-y : 0 --> subus x, y
22522       // x >  y ? x-y : 0 --> subus x, y
22523       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22524           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22525         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22526
22527       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22528         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22529           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22530             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22531               // If the RHS is a constant we have to reverse the const
22532               // canonicalization.
22533               // x > C-1 ? x+-C : 0 --> subus x, C
22534               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22535                   CondRHSConst->getAPIntValue() ==
22536                       (-OpRHSConst->getAPIntValue() - 1))
22537                 return DAG.getNode(
22538                     X86ISD::SUBUS, DL, VT, OpLHS,
22539                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22540
22541           // Another special case: If C was a sign bit, the sub has been
22542           // canonicalized into a xor.
22543           // FIXME: Would it be better to use computeKnownBits to determine
22544           //        whether it's safe to decanonicalize the xor?
22545           // x s< 0 ? x^C : 0 --> subus x, C
22546           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22547               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22548               OpRHSConst->getAPIntValue().isSignBit())
22549             // Note that we have to rebuild the RHS constant here to ensure we
22550             // don't rely on particular values of undef lanes.
22551             return DAG.getNode(
22552                 X86ISD::SUBUS, DL, VT, OpLHS,
22553                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22554         }
22555     }
22556   }
22557
22558   // Try to match a min/max vector operation.
22559   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22560     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22561     unsigned Opc = ret.first;
22562     bool NeedSplit = ret.second;
22563
22564     if (Opc && NeedSplit) {
22565       unsigned NumElems = VT.getVectorNumElements();
22566       // Extract the LHS vectors
22567       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22568       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22569
22570       // Extract the RHS vectors
22571       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22572       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22573
22574       // Create min/max for each subvector
22575       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22576       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22577
22578       // Merge the result
22579       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22580     } else if (Opc)
22581       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22582   }
22583
22584   // Simplify vector selection if condition value type matches vselect
22585   // operand type
22586   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22587     assert(Cond.getValueType().isVector() &&
22588            "vector select expects a vector selector!");
22589
22590     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22591     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22592
22593     // Try invert the condition if true value is not all 1s and false value
22594     // is not all 0s.
22595     if (!TValIsAllOnes && !FValIsAllZeros &&
22596         // Check if the selector will be produced by CMPP*/PCMP*
22597         Cond.getOpcode() == ISD::SETCC &&
22598         // Check if SETCC has already been promoted
22599         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22600             CondVT) {
22601       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22602       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22603
22604       if (TValIsAllZeros || FValIsAllOnes) {
22605         SDValue CC = Cond.getOperand(2);
22606         ISD::CondCode NewCC =
22607           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22608                                Cond.getOperand(0).getValueType().isInteger());
22609         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22610         std::swap(LHS, RHS);
22611         TValIsAllOnes = FValIsAllOnes;
22612         FValIsAllZeros = TValIsAllZeros;
22613       }
22614     }
22615
22616     if (TValIsAllOnes || FValIsAllZeros) {
22617       SDValue Ret;
22618
22619       if (TValIsAllOnes && FValIsAllZeros)
22620         Ret = Cond;
22621       else if (TValIsAllOnes)
22622         Ret =
22623             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22624       else if (FValIsAllZeros)
22625         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22626                           DAG.getBitcast(CondVT, LHS));
22627
22628       return DAG.getBitcast(VT, Ret);
22629     }
22630   }
22631
22632   // We should generate an X86ISD::BLENDI from a vselect if its argument
22633   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22634   // constants. This specific pattern gets generated when we split a
22635   // selector for a 512 bit vector in a machine without AVX512 (but with
22636   // 256-bit vectors), during legalization:
22637   //
22638   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22639   //
22640   // Iff we find this pattern and the build_vectors are built from
22641   // constants, we translate the vselect into a shuffle_vector that we
22642   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22643   if ((N->getOpcode() == ISD::VSELECT ||
22644        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22645       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22646     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22647     if (Shuffle.getNode())
22648       return Shuffle;
22649   }
22650
22651   // If this is a *dynamic* select (non-constant condition) and we can match
22652   // this node with one of the variable blend instructions, restructure the
22653   // condition so that the blends can use the high bit of each element and use
22654   // SimplifyDemandedBits to simplify the condition operand.
22655   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22656       !DCI.isBeforeLegalize() &&
22657       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22658     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22659
22660     // Don't optimize vector selects that map to mask-registers.
22661     if (BitWidth == 1)
22662       return SDValue();
22663
22664     // We can only handle the cases where VSELECT is directly legal on the
22665     // subtarget. We custom lower VSELECT nodes with constant conditions and
22666     // this makes it hard to see whether a dynamic VSELECT will correctly
22667     // lower, so we both check the operation's status and explicitly handle the
22668     // cases where a *dynamic* blend will fail even though a constant-condition
22669     // blend could be custom lowered.
22670     // FIXME: We should find a better way to handle this class of problems.
22671     // Potentially, we should combine constant-condition vselect nodes
22672     // pre-legalization into shuffles and not mark as many types as custom
22673     // lowered.
22674     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22675       return SDValue();
22676     // FIXME: We don't support i16-element blends currently. We could and
22677     // should support them by making *all* the bits in the condition be set
22678     // rather than just the high bit and using an i8-element blend.
22679     if (VT.getScalarType() == MVT::i16)
22680       return SDValue();
22681     // Dynamic blending was only available from SSE4.1 onward.
22682     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22683       return SDValue();
22684     // Byte blends are only available in AVX2
22685     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22686         !Subtarget->hasAVX2())
22687       return SDValue();
22688
22689     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22690     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22691
22692     APInt KnownZero, KnownOne;
22693     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22694                                           DCI.isBeforeLegalizeOps());
22695     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22696         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22697                                  TLO)) {
22698       // If we changed the computation somewhere in the DAG, this change
22699       // will affect all users of Cond.
22700       // Make sure it is fine and update all the nodes so that we do not
22701       // use the generic VSELECT anymore. Otherwise, we may perform
22702       // wrong optimizations as we messed up with the actual expectation
22703       // for the vector boolean values.
22704       if (Cond != TLO.Old) {
22705         // Check all uses of that condition operand to check whether it will be
22706         // consumed by non-BLEND instructions, which may depend on all bits are
22707         // set properly.
22708         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22709              I != E; ++I)
22710           if (I->getOpcode() != ISD::VSELECT)
22711             // TODO: Add other opcodes eventually lowered into BLEND.
22712             return SDValue();
22713
22714         // Update all the users of the condition, before committing the change,
22715         // so that the VSELECT optimizations that expect the correct vector
22716         // boolean value will not be triggered.
22717         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22718              I != E; ++I)
22719           DAG.ReplaceAllUsesOfValueWith(
22720               SDValue(*I, 0),
22721               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22722                           Cond, I->getOperand(1), I->getOperand(2)));
22723         DCI.CommitTargetLoweringOpt(TLO);
22724         return SDValue();
22725       }
22726       // At this point, only Cond is changed. Change the condition
22727       // just for N to keep the opportunity to optimize all other
22728       // users their own way.
22729       DAG.ReplaceAllUsesOfValueWith(
22730           SDValue(N, 0),
22731           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22732                       TLO.New, N->getOperand(1), N->getOperand(2)));
22733       return SDValue();
22734     }
22735   }
22736
22737   return SDValue();
22738 }
22739
22740 // Check whether a boolean test is testing a boolean value generated by
22741 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22742 // code.
22743 //
22744 // Simplify the following patterns:
22745 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22746 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22747 // to (Op EFLAGS Cond)
22748 //
22749 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22750 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22751 // to (Op EFLAGS !Cond)
22752 //
22753 // where Op could be BRCOND or CMOV.
22754 //
22755 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22756   // Quit if not CMP and SUB with its value result used.
22757   if (Cmp.getOpcode() != X86ISD::CMP &&
22758       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22759       return SDValue();
22760
22761   // Quit if not used as a boolean value.
22762   if (CC != X86::COND_E && CC != X86::COND_NE)
22763     return SDValue();
22764
22765   // Check CMP operands. One of them should be 0 or 1 and the other should be
22766   // an SetCC or extended from it.
22767   SDValue Op1 = Cmp.getOperand(0);
22768   SDValue Op2 = Cmp.getOperand(1);
22769
22770   SDValue SetCC;
22771   const ConstantSDNode* C = nullptr;
22772   bool needOppositeCond = (CC == X86::COND_E);
22773   bool checkAgainstTrue = false; // Is it a comparison against 1?
22774
22775   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22776     SetCC = Op2;
22777   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22778     SetCC = Op1;
22779   else // Quit if all operands are not constants.
22780     return SDValue();
22781
22782   if (C->getZExtValue() == 1) {
22783     needOppositeCond = !needOppositeCond;
22784     checkAgainstTrue = true;
22785   } else if (C->getZExtValue() != 0)
22786     // Quit if the constant is neither 0 or 1.
22787     return SDValue();
22788
22789   bool truncatedToBoolWithAnd = false;
22790   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22791   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22792          SetCC.getOpcode() == ISD::TRUNCATE ||
22793          SetCC.getOpcode() == ISD::AND) {
22794     if (SetCC.getOpcode() == ISD::AND) {
22795       int OpIdx = -1;
22796       ConstantSDNode *CS;
22797       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22798           CS->getZExtValue() == 1)
22799         OpIdx = 1;
22800       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22801           CS->getZExtValue() == 1)
22802         OpIdx = 0;
22803       if (OpIdx == -1)
22804         break;
22805       SetCC = SetCC.getOperand(OpIdx);
22806       truncatedToBoolWithAnd = true;
22807     } else
22808       SetCC = SetCC.getOperand(0);
22809   }
22810
22811   switch (SetCC.getOpcode()) {
22812   case X86ISD::SETCC_CARRY:
22813     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22814     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22815     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22816     // truncated to i1 using 'and'.
22817     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22818       break;
22819     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22820            "Invalid use of SETCC_CARRY!");
22821     // FALL THROUGH
22822   case X86ISD::SETCC:
22823     // Set the condition code or opposite one if necessary.
22824     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22825     if (needOppositeCond)
22826       CC = X86::GetOppositeBranchCondition(CC);
22827     return SetCC.getOperand(1);
22828   case X86ISD::CMOV: {
22829     // Check whether false/true value has canonical one, i.e. 0 or 1.
22830     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22831     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22832     // Quit if true value is not a constant.
22833     if (!TVal)
22834       return SDValue();
22835     // Quit if false value is not a constant.
22836     if (!FVal) {
22837       SDValue Op = SetCC.getOperand(0);
22838       // Skip 'zext' or 'trunc' node.
22839       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22840           Op.getOpcode() == ISD::TRUNCATE)
22841         Op = Op.getOperand(0);
22842       // A special case for rdrand/rdseed, where 0 is set if false cond is
22843       // found.
22844       if ((Op.getOpcode() != X86ISD::RDRAND &&
22845            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22846         return SDValue();
22847     }
22848     // Quit if false value is not the constant 0 or 1.
22849     bool FValIsFalse = true;
22850     if (FVal && FVal->getZExtValue() != 0) {
22851       if (FVal->getZExtValue() != 1)
22852         return SDValue();
22853       // If FVal is 1, opposite cond is needed.
22854       needOppositeCond = !needOppositeCond;
22855       FValIsFalse = false;
22856     }
22857     // Quit if TVal is not the constant opposite of FVal.
22858     if (FValIsFalse && TVal->getZExtValue() != 1)
22859       return SDValue();
22860     if (!FValIsFalse && TVal->getZExtValue() != 0)
22861       return SDValue();
22862     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22863     if (needOppositeCond)
22864       CC = X86::GetOppositeBranchCondition(CC);
22865     return SetCC.getOperand(3);
22866   }
22867   }
22868
22869   return SDValue();
22870 }
22871
22872 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22873 /// Match:
22874 ///   (X86or (X86setcc) (X86setcc))
22875 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22876 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22877                                            X86::CondCode &CC1, SDValue &Flags,
22878                                            bool &isAnd) {
22879   if (Cond->getOpcode() == X86ISD::CMP) {
22880     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22881     if (!CondOp1C || !CondOp1C->isNullValue())
22882       return false;
22883
22884     Cond = Cond->getOperand(0);
22885   }
22886
22887   isAnd = false;
22888
22889   SDValue SetCC0, SetCC1;
22890   switch (Cond->getOpcode()) {
22891   default: return false;
22892   case ISD::AND:
22893   case X86ISD::AND:
22894     isAnd = true;
22895     // fallthru
22896   case ISD::OR:
22897   case X86ISD::OR:
22898     SetCC0 = Cond->getOperand(0);
22899     SetCC1 = Cond->getOperand(1);
22900     break;
22901   };
22902
22903   // Make sure we have SETCC nodes, using the same flags value.
22904   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22905       SetCC1.getOpcode() != X86ISD::SETCC ||
22906       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22907     return false;
22908
22909   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22910   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22911   Flags = SetCC0->getOperand(1);
22912   return true;
22913 }
22914
22915 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22916 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22917                                   TargetLowering::DAGCombinerInfo &DCI,
22918                                   const X86Subtarget *Subtarget) {
22919   SDLoc DL(N);
22920
22921   // If the flag operand isn't dead, don't touch this CMOV.
22922   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22923     return SDValue();
22924
22925   SDValue FalseOp = N->getOperand(0);
22926   SDValue TrueOp = N->getOperand(1);
22927   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22928   SDValue Cond = N->getOperand(3);
22929
22930   if (CC == X86::COND_E || CC == X86::COND_NE) {
22931     switch (Cond.getOpcode()) {
22932     default: break;
22933     case X86ISD::BSR:
22934     case X86ISD::BSF:
22935       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22936       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22937         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22938     }
22939   }
22940
22941   SDValue Flags;
22942
22943   Flags = checkBoolTestSetCCCombine(Cond, CC);
22944   if (Flags.getNode() &&
22945       // Extra check as FCMOV only supports a subset of X86 cond.
22946       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22947     SDValue Ops[] = { FalseOp, TrueOp,
22948                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22949     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22950   }
22951
22952   // If this is a select between two integer constants, try to do some
22953   // optimizations.  Note that the operands are ordered the opposite of SELECT
22954   // operands.
22955   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22956     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22957       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22958       // larger than FalseC (the false value).
22959       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22960         CC = X86::GetOppositeBranchCondition(CC);
22961         std::swap(TrueC, FalseC);
22962         std::swap(TrueOp, FalseOp);
22963       }
22964
22965       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22966       // This is efficient for any integer data type (including i8/i16) and
22967       // shift amount.
22968       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22969         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22970                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22971
22972         // Zero extend the condition if needed.
22973         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22974
22975         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22976         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22977                            DAG.getConstant(ShAmt, DL, MVT::i8));
22978         if (N->getNumValues() == 2)  // Dead flag value?
22979           return DCI.CombineTo(N, Cond, SDValue());
22980         return Cond;
22981       }
22982
22983       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22984       // for any integer data type, including i8/i16.
22985       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22986         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22987                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22988
22989         // Zero extend the condition if needed.
22990         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22991                            FalseC->getValueType(0), Cond);
22992         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22993                            SDValue(FalseC, 0));
22994
22995         if (N->getNumValues() == 2)  // Dead flag value?
22996           return DCI.CombineTo(N, Cond, SDValue());
22997         return Cond;
22998       }
22999
23000       // Optimize cases that will turn into an LEA instruction.  This requires
23001       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
23002       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
23003         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
23004         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
23005
23006         bool isFastMultiplier = false;
23007         if (Diff < 10) {
23008           switch ((unsigned char)Diff) {
23009           default: break;
23010           case 1:  // result = add base, cond
23011           case 2:  // result = lea base(    , cond*2)
23012           case 3:  // result = lea base(cond, cond*2)
23013           case 4:  // result = lea base(    , cond*4)
23014           case 5:  // result = lea base(cond, cond*4)
23015           case 8:  // result = lea base(    , cond*8)
23016           case 9:  // result = lea base(cond, cond*8)
23017             isFastMultiplier = true;
23018             break;
23019           }
23020         }
23021
23022         if (isFastMultiplier) {
23023           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
23024           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
23025                              DAG.getConstant(CC, DL, MVT::i8), Cond);
23026           // Zero extend the condition if needed.
23027           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
23028                              Cond);
23029           // Scale the condition by the difference.
23030           if (Diff != 1)
23031             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
23032                                DAG.getConstant(Diff, DL, Cond.getValueType()));
23033
23034           // Add the base if non-zero.
23035           if (FalseC->getAPIntValue() != 0)
23036             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
23037                                SDValue(FalseC, 0));
23038           if (N->getNumValues() == 2)  // Dead flag value?
23039             return DCI.CombineTo(N, Cond, SDValue());
23040           return Cond;
23041         }
23042       }
23043     }
23044   }
23045
23046   // Handle these cases:
23047   //   (select (x != c), e, c) -> select (x != c), e, x),
23048   //   (select (x == c), c, e) -> select (x == c), x, e)
23049   // where the c is an integer constant, and the "select" is the combination
23050   // of CMOV and CMP.
23051   //
23052   // The rationale for this change is that the conditional-move from a constant
23053   // needs two instructions, however, conditional-move from a register needs
23054   // only one instruction.
23055   //
23056   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23057   //  some instruction-combining opportunities. This opt needs to be
23058   //  postponed as late as possible.
23059   //
23060   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23061     // the DCI.xxxx conditions are provided to postpone the optimization as
23062     // late as possible.
23063
23064     ConstantSDNode *CmpAgainst = nullptr;
23065     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23066         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23067         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23068
23069       if (CC == X86::COND_NE &&
23070           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23071         CC = X86::GetOppositeBranchCondition(CC);
23072         std::swap(TrueOp, FalseOp);
23073       }
23074
23075       if (CC == X86::COND_E &&
23076           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23077         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23078                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23079         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23080       }
23081     }
23082   }
23083
23084   // Fold and/or of setcc's to double CMOV:
23085   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23086   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23087   //
23088   // This combine lets us generate:
23089   //   cmovcc1 (jcc1 if we don't have CMOV)
23090   //   cmovcc2 (same)
23091   // instead of:
23092   //   setcc1
23093   //   setcc2
23094   //   and/or
23095   //   cmovne (jne if we don't have CMOV)
23096   // When we can't use the CMOV instruction, it might increase branch
23097   // mispredicts.
23098   // When we can use CMOV, or when there is no mispredict, this improves
23099   // throughput and reduces register pressure.
23100   //
23101   if (CC == X86::COND_NE) {
23102     SDValue Flags;
23103     X86::CondCode CC0, CC1;
23104     bool isAndSetCC;
23105     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23106       if (isAndSetCC) {
23107         std::swap(FalseOp, TrueOp);
23108         CC0 = X86::GetOppositeBranchCondition(CC0);
23109         CC1 = X86::GetOppositeBranchCondition(CC1);
23110       }
23111
23112       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23113         Flags};
23114       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23115       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23116       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23117       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23118       return CMOV;
23119     }
23120   }
23121
23122   return SDValue();
23123 }
23124
23125 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23126                                                 const X86Subtarget *Subtarget) {
23127   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23128   switch (IntNo) {
23129   default: return SDValue();
23130   // SSE/AVX/AVX2 blend intrinsics.
23131   case Intrinsic::x86_avx2_pblendvb:
23132     // Don't try to simplify this intrinsic if we don't have AVX2.
23133     if (!Subtarget->hasAVX2())
23134       return SDValue();
23135     // FALL-THROUGH
23136   case Intrinsic::x86_avx_blendv_pd_256:
23137   case Intrinsic::x86_avx_blendv_ps_256:
23138     // Don't try to simplify this intrinsic if we don't have AVX.
23139     if (!Subtarget->hasAVX())
23140       return SDValue();
23141     // FALL-THROUGH
23142   case Intrinsic::x86_sse41_blendvps:
23143   case Intrinsic::x86_sse41_blendvpd:
23144   case Intrinsic::x86_sse41_pblendvb: {
23145     SDValue Op0 = N->getOperand(1);
23146     SDValue Op1 = N->getOperand(2);
23147     SDValue Mask = N->getOperand(3);
23148
23149     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23150     if (!Subtarget->hasSSE41())
23151       return SDValue();
23152
23153     // fold (blend A, A, Mask) -> A
23154     if (Op0 == Op1)
23155       return Op0;
23156     // fold (blend A, B, allZeros) -> A
23157     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23158       return Op0;
23159     // fold (blend A, B, allOnes) -> B
23160     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23161       return Op1;
23162
23163     // Simplify the case where the mask is a constant i32 value.
23164     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23165       if (C->isNullValue())
23166         return Op0;
23167       if (C->isAllOnesValue())
23168         return Op1;
23169     }
23170
23171     return SDValue();
23172   }
23173
23174   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23175   case Intrinsic::x86_sse2_psrai_w:
23176   case Intrinsic::x86_sse2_psrai_d:
23177   case Intrinsic::x86_avx2_psrai_w:
23178   case Intrinsic::x86_avx2_psrai_d:
23179   case Intrinsic::x86_sse2_psra_w:
23180   case Intrinsic::x86_sse2_psra_d:
23181   case Intrinsic::x86_avx2_psra_w:
23182   case Intrinsic::x86_avx2_psra_d: {
23183     SDValue Op0 = N->getOperand(1);
23184     SDValue Op1 = N->getOperand(2);
23185     EVT VT = Op0.getValueType();
23186     assert(VT.isVector() && "Expected a vector type!");
23187
23188     if (isa<BuildVectorSDNode>(Op1))
23189       Op1 = Op1.getOperand(0);
23190
23191     if (!isa<ConstantSDNode>(Op1))
23192       return SDValue();
23193
23194     EVT SVT = VT.getVectorElementType();
23195     unsigned SVTBits = SVT.getSizeInBits();
23196
23197     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23198     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23199     uint64_t ShAmt = C.getZExtValue();
23200
23201     // Don't try to convert this shift into a ISD::SRA if the shift
23202     // count is bigger than or equal to the element size.
23203     if (ShAmt >= SVTBits)
23204       return SDValue();
23205
23206     // Trivial case: if the shift count is zero, then fold this
23207     // into the first operand.
23208     if (ShAmt == 0)
23209       return Op0;
23210
23211     // Replace this packed shift intrinsic with a target independent
23212     // shift dag node.
23213     SDLoc DL(N);
23214     SDValue Splat = DAG.getConstant(C, DL, VT);
23215     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23216   }
23217   }
23218 }
23219
23220 /// PerformMulCombine - Optimize a single multiply with constant into two
23221 /// in order to implement it with two cheaper instructions, e.g.
23222 /// LEA + SHL, LEA + LEA.
23223 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23224                                  TargetLowering::DAGCombinerInfo &DCI) {
23225   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23226     return SDValue();
23227
23228   EVT VT = N->getValueType(0);
23229   if (VT != MVT::i64 && VT != MVT::i32)
23230     return SDValue();
23231
23232   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23233   if (!C)
23234     return SDValue();
23235   uint64_t MulAmt = C->getZExtValue();
23236   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23237     return SDValue();
23238
23239   uint64_t MulAmt1 = 0;
23240   uint64_t MulAmt2 = 0;
23241   if ((MulAmt % 9) == 0) {
23242     MulAmt1 = 9;
23243     MulAmt2 = MulAmt / 9;
23244   } else if ((MulAmt % 5) == 0) {
23245     MulAmt1 = 5;
23246     MulAmt2 = MulAmt / 5;
23247   } else if ((MulAmt % 3) == 0) {
23248     MulAmt1 = 3;
23249     MulAmt2 = MulAmt / 3;
23250   }
23251   if (MulAmt2 &&
23252       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23253     SDLoc DL(N);
23254
23255     if (isPowerOf2_64(MulAmt2) &&
23256         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23257       // If second multiplifer is pow2, issue it first. We want the multiply by
23258       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23259       // is an add.
23260       std::swap(MulAmt1, MulAmt2);
23261
23262     SDValue NewMul;
23263     if (isPowerOf2_64(MulAmt1))
23264       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23265                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23266     else
23267       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23268                            DAG.getConstant(MulAmt1, DL, VT));
23269
23270     if (isPowerOf2_64(MulAmt2))
23271       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23272                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23273     else
23274       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23275                            DAG.getConstant(MulAmt2, DL, VT));
23276
23277     // Do not add new nodes to DAG combiner worklist.
23278     DCI.CombineTo(N, NewMul, false);
23279   }
23280   return SDValue();
23281 }
23282
23283 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23284   SDValue N0 = N->getOperand(0);
23285   SDValue N1 = N->getOperand(1);
23286   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23287   EVT VT = N0.getValueType();
23288
23289   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23290   // since the result of setcc_c is all zero's or all ones.
23291   if (VT.isInteger() && !VT.isVector() &&
23292       N1C && N0.getOpcode() == ISD::AND &&
23293       N0.getOperand(1).getOpcode() == ISD::Constant) {
23294     SDValue N00 = N0.getOperand(0);
23295     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23296         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23297           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23298          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23299       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23300       APInt ShAmt = N1C->getAPIntValue();
23301       Mask = Mask.shl(ShAmt);
23302       if (Mask != 0) {
23303         SDLoc DL(N);
23304         return DAG.getNode(ISD::AND, DL, VT,
23305                            N00, DAG.getConstant(Mask, DL, VT));
23306       }
23307     }
23308   }
23309
23310   // Hardware support for vector shifts is sparse which makes us scalarize the
23311   // vector operations in many cases. Also, on sandybridge ADD is faster than
23312   // shl.
23313   // (shl V, 1) -> add V,V
23314   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23315     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23316       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23317       // We shift all of the values by one. In many cases we do not have
23318       // hardware support for this operation. This is better expressed as an ADD
23319       // of two values.
23320       if (N1SplatC->getAPIntValue() == 1)
23321         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23322     }
23323
23324   return SDValue();
23325 }
23326
23327 /// \brief Returns a vector of 0s if the node in input is a vector logical
23328 /// shift by a constant amount which is known to be bigger than or equal
23329 /// to the vector element size in bits.
23330 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23331                                       const X86Subtarget *Subtarget) {
23332   EVT VT = N->getValueType(0);
23333
23334   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23335       (!Subtarget->hasInt256() ||
23336        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23337     return SDValue();
23338
23339   SDValue Amt = N->getOperand(1);
23340   SDLoc DL(N);
23341   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23342     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23343       APInt ShiftAmt = AmtSplat->getAPIntValue();
23344       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23345
23346       // SSE2/AVX2 logical shifts always return a vector of 0s
23347       // if the shift amount is bigger than or equal to
23348       // the element size. The constant shift amount will be
23349       // encoded as a 8-bit immediate.
23350       if (ShiftAmt.trunc(8).uge(MaxAmount))
23351         return getZeroVector(VT, Subtarget, DAG, DL);
23352     }
23353
23354   return SDValue();
23355 }
23356
23357 /// PerformShiftCombine - Combine shifts.
23358 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23359                                    TargetLowering::DAGCombinerInfo &DCI,
23360                                    const X86Subtarget *Subtarget) {
23361   if (N->getOpcode() == ISD::SHL)
23362     if (SDValue V = PerformSHLCombine(N, DAG))
23363       return V;
23364
23365   // Try to fold this logical shift into a zero vector.
23366   if (N->getOpcode() != ISD::SRA)
23367     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23368       return V;
23369
23370   return SDValue();
23371 }
23372
23373 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23374 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23375 // and friends.  Likewise for OR -> CMPNEQSS.
23376 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23377                             TargetLowering::DAGCombinerInfo &DCI,
23378                             const X86Subtarget *Subtarget) {
23379   unsigned opcode;
23380
23381   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23382   // we're requiring SSE2 for both.
23383   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23384     SDValue N0 = N->getOperand(0);
23385     SDValue N1 = N->getOperand(1);
23386     SDValue CMP0 = N0->getOperand(1);
23387     SDValue CMP1 = N1->getOperand(1);
23388     SDLoc DL(N);
23389
23390     // The SETCCs should both refer to the same CMP.
23391     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23392       return SDValue();
23393
23394     SDValue CMP00 = CMP0->getOperand(0);
23395     SDValue CMP01 = CMP0->getOperand(1);
23396     EVT     VT    = CMP00.getValueType();
23397
23398     if (VT == MVT::f32 || VT == MVT::f64) {
23399       bool ExpectingFlags = false;
23400       // Check for any users that want flags:
23401       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23402            !ExpectingFlags && UI != UE; ++UI)
23403         switch (UI->getOpcode()) {
23404         default:
23405         case ISD::BR_CC:
23406         case ISD::BRCOND:
23407         case ISD::SELECT:
23408           ExpectingFlags = true;
23409           break;
23410         case ISD::CopyToReg:
23411         case ISD::SIGN_EXTEND:
23412         case ISD::ZERO_EXTEND:
23413         case ISD::ANY_EXTEND:
23414           break;
23415         }
23416
23417       if (!ExpectingFlags) {
23418         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23419         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23420
23421         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23422           X86::CondCode tmp = cc0;
23423           cc0 = cc1;
23424           cc1 = tmp;
23425         }
23426
23427         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23428             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23429           // FIXME: need symbolic constants for these magic numbers.
23430           // See X86ATTInstPrinter.cpp:printSSECC().
23431           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23432           if (Subtarget->hasAVX512()) {
23433             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23434                                          CMP01,
23435                                          DAG.getConstant(x86cc, DL, MVT::i8));
23436             if (N->getValueType(0) != MVT::i1)
23437               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23438                                  FSetCC);
23439             return FSetCC;
23440           }
23441           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23442                                               CMP00.getValueType(), CMP00, CMP01,
23443                                               DAG.getConstant(x86cc, DL,
23444                                                               MVT::i8));
23445
23446           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23447           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23448
23449           if (is64BitFP && !Subtarget->is64Bit()) {
23450             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23451             // 64-bit integer, since that's not a legal type. Since
23452             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23453             // bits, but can do this little dance to extract the lowest 32 bits
23454             // and work with those going forward.
23455             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23456                                            OnesOrZeroesF);
23457             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23458             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23459                                         Vector32, DAG.getIntPtrConstant(0, DL));
23460             IntVT = MVT::i32;
23461           }
23462
23463           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23464           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23465                                       DAG.getConstant(1, DL, IntVT));
23466           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23467                                               ANDed);
23468           return OneBitOfTruth;
23469         }
23470       }
23471     }
23472   }
23473   return SDValue();
23474 }
23475
23476 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23477 /// so it can be folded inside ANDNP.
23478 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23479   EVT VT = N->getValueType(0);
23480
23481   // Match direct AllOnes for 128 and 256-bit vectors
23482   if (ISD::isBuildVectorAllOnes(N))
23483     return true;
23484
23485   // Look through a bit convert.
23486   if (N->getOpcode() == ISD::BITCAST)
23487     N = N->getOperand(0).getNode();
23488
23489   // Sometimes the operand may come from a insert_subvector building a 256-bit
23490   // allones vector
23491   if (VT.is256BitVector() &&
23492       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23493     SDValue V1 = N->getOperand(0);
23494     SDValue V2 = N->getOperand(1);
23495
23496     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23497         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23498         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23499         ISD::isBuildVectorAllOnes(V2.getNode()))
23500       return true;
23501   }
23502
23503   return false;
23504 }
23505
23506 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23507 // register. In most cases we actually compare or select YMM-sized registers
23508 // and mixing the two types creates horrible code. This method optimizes
23509 // some of the transition sequences.
23510 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23511                                  TargetLowering::DAGCombinerInfo &DCI,
23512                                  const X86Subtarget *Subtarget) {
23513   EVT VT = N->getValueType(0);
23514   if (!VT.is256BitVector())
23515     return SDValue();
23516
23517   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23518           N->getOpcode() == ISD::ZERO_EXTEND ||
23519           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23520
23521   SDValue Narrow = N->getOperand(0);
23522   EVT NarrowVT = Narrow->getValueType(0);
23523   if (!NarrowVT.is128BitVector())
23524     return SDValue();
23525
23526   if (Narrow->getOpcode() != ISD::XOR &&
23527       Narrow->getOpcode() != ISD::AND &&
23528       Narrow->getOpcode() != ISD::OR)
23529     return SDValue();
23530
23531   SDValue N0  = Narrow->getOperand(0);
23532   SDValue N1  = Narrow->getOperand(1);
23533   SDLoc DL(Narrow);
23534
23535   // The Left side has to be a trunc.
23536   if (N0.getOpcode() != ISD::TRUNCATE)
23537     return SDValue();
23538
23539   // The type of the truncated inputs.
23540   EVT WideVT = N0->getOperand(0)->getValueType(0);
23541   if (WideVT != VT)
23542     return SDValue();
23543
23544   // The right side has to be a 'trunc' or a constant vector.
23545   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23546   ConstantSDNode *RHSConstSplat = nullptr;
23547   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23548     RHSConstSplat = RHSBV->getConstantSplatNode();
23549   if (!RHSTrunc && !RHSConstSplat)
23550     return SDValue();
23551
23552   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23553
23554   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23555     return SDValue();
23556
23557   // Set N0 and N1 to hold the inputs to the new wide operation.
23558   N0 = N0->getOperand(0);
23559   if (RHSConstSplat) {
23560     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23561                      SDValue(RHSConstSplat, 0));
23562     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23563     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23564   } else if (RHSTrunc) {
23565     N1 = N1->getOperand(0);
23566   }
23567
23568   // Generate the wide operation.
23569   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23570   unsigned Opcode = N->getOpcode();
23571   switch (Opcode) {
23572   case ISD::ANY_EXTEND:
23573     return Op;
23574   case ISD::ZERO_EXTEND: {
23575     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23576     APInt Mask = APInt::getAllOnesValue(InBits);
23577     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23578     return DAG.getNode(ISD::AND, DL, VT,
23579                        Op, DAG.getConstant(Mask, DL, VT));
23580   }
23581   case ISD::SIGN_EXTEND:
23582     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23583                        Op, DAG.getValueType(NarrowVT));
23584   default:
23585     llvm_unreachable("Unexpected opcode");
23586   }
23587 }
23588
23589 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23590                                  TargetLowering::DAGCombinerInfo &DCI,
23591                                  const X86Subtarget *Subtarget) {
23592   SDValue N0 = N->getOperand(0);
23593   SDValue N1 = N->getOperand(1);
23594   SDLoc DL(N);
23595
23596   // A vector zext_in_reg may be represented as a shuffle,
23597   // feeding into a bitcast (this represents anyext) feeding into
23598   // an and with a mask.
23599   // We'd like to try to combine that into a shuffle with zero
23600   // plus a bitcast, removing the and.
23601   if (N0.getOpcode() != ISD::BITCAST ||
23602       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23603     return SDValue();
23604
23605   // The other side of the AND should be a splat of 2^C, where C
23606   // is the number of bits in the source type.
23607   if (N1.getOpcode() == ISD::BITCAST)
23608     N1 = N1.getOperand(0);
23609   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23610     return SDValue();
23611   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23612
23613   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23614   EVT SrcType = Shuffle->getValueType(0);
23615
23616   // We expect a single-source shuffle
23617   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23618     return SDValue();
23619
23620   unsigned SrcSize = SrcType.getScalarSizeInBits();
23621
23622   APInt SplatValue, SplatUndef;
23623   unsigned SplatBitSize;
23624   bool HasAnyUndefs;
23625   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23626                                 SplatBitSize, HasAnyUndefs))
23627     return SDValue();
23628
23629   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23630   // Make sure the splat matches the mask we expect
23631   if (SplatBitSize > ResSize ||
23632       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23633     return SDValue();
23634
23635   // Make sure the input and output size make sense
23636   if (SrcSize >= ResSize || ResSize % SrcSize)
23637     return SDValue();
23638
23639   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23640   // The number of u's between each two values depends on the ratio between
23641   // the source and dest type.
23642   unsigned ZextRatio = ResSize / SrcSize;
23643   bool IsZext = true;
23644   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23645     if (i % ZextRatio) {
23646       if (Shuffle->getMaskElt(i) > 0) {
23647         // Expected undef
23648         IsZext = false;
23649         break;
23650       }
23651     } else {
23652       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23653         // Expected element number
23654         IsZext = false;
23655         break;
23656       }
23657     }
23658   }
23659
23660   if (!IsZext)
23661     return SDValue();
23662
23663   // Ok, perform the transformation - replace the shuffle with
23664   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23665   // (instead of undef) where the k elements come from the zero vector.
23666   SmallVector<int, 8> Mask;
23667   unsigned NumElems = SrcType.getVectorNumElements();
23668   for (unsigned i = 0; i < NumElems; ++i)
23669     if (i % ZextRatio)
23670       Mask.push_back(NumElems);
23671     else
23672       Mask.push_back(i / ZextRatio);
23673
23674   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23675     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23676   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23677 }
23678
23679 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23680                                  TargetLowering::DAGCombinerInfo &DCI,
23681                                  const X86Subtarget *Subtarget) {
23682   if (DCI.isBeforeLegalizeOps())
23683     return SDValue();
23684
23685   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23686     return Zext;
23687
23688   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23689     return R;
23690
23691   EVT VT = N->getValueType(0);
23692   SDValue N0 = N->getOperand(0);
23693   SDValue N1 = N->getOperand(1);
23694   SDLoc DL(N);
23695
23696   // Create BEXTR instructions
23697   // BEXTR is ((X >> imm) & (2**size-1))
23698   if (VT == MVT::i32 || VT == MVT::i64) {
23699     // Check for BEXTR.
23700     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23701         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23702       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23703       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23704       if (MaskNode && ShiftNode) {
23705         uint64_t Mask = MaskNode->getZExtValue();
23706         uint64_t Shift = ShiftNode->getZExtValue();
23707         if (isMask_64(Mask)) {
23708           uint64_t MaskSize = countPopulation(Mask);
23709           if (Shift + MaskSize <= VT.getSizeInBits())
23710             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23711                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23712                                                VT));
23713         }
23714       }
23715     } // BEXTR
23716
23717     return SDValue();
23718   }
23719
23720   // Want to form ANDNP nodes:
23721   // 1) In the hopes of then easily combining them with OR and AND nodes
23722   //    to form PBLEND/PSIGN.
23723   // 2) To match ANDN packed intrinsics
23724   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23725     return SDValue();
23726
23727   // Check LHS for vnot
23728   if (N0.getOpcode() == ISD::XOR &&
23729       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23730       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23731     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23732
23733   // Check RHS for vnot
23734   if (N1.getOpcode() == ISD::XOR &&
23735       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23736       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23737     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23738
23739   return SDValue();
23740 }
23741
23742 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23743                                 TargetLowering::DAGCombinerInfo &DCI,
23744                                 const X86Subtarget *Subtarget) {
23745   if (DCI.isBeforeLegalizeOps())
23746     return SDValue();
23747
23748   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23749     return R;
23750
23751   SDValue N0 = N->getOperand(0);
23752   SDValue N1 = N->getOperand(1);
23753   EVT VT = N->getValueType(0);
23754
23755   // look for psign/blend
23756   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23757     if (!Subtarget->hasSSSE3() ||
23758         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23759       return SDValue();
23760
23761     // Canonicalize pandn to RHS
23762     if (N0.getOpcode() == X86ISD::ANDNP)
23763       std::swap(N0, N1);
23764     // or (and (m, y), (pandn m, x))
23765     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23766       SDValue Mask = N1.getOperand(0);
23767       SDValue X    = N1.getOperand(1);
23768       SDValue Y;
23769       if (N0.getOperand(0) == Mask)
23770         Y = N0.getOperand(1);
23771       if (N0.getOperand(1) == Mask)
23772         Y = N0.getOperand(0);
23773
23774       // Check to see if the mask appeared in both the AND and ANDNP and
23775       if (!Y.getNode())
23776         return SDValue();
23777
23778       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23779       // Look through mask bitcast.
23780       if (Mask.getOpcode() == ISD::BITCAST)
23781         Mask = Mask.getOperand(0);
23782       if (X.getOpcode() == ISD::BITCAST)
23783         X = X.getOperand(0);
23784       if (Y.getOpcode() == ISD::BITCAST)
23785         Y = Y.getOperand(0);
23786
23787       EVT MaskVT = Mask.getValueType();
23788
23789       // Validate that the Mask operand is a vector sra node.
23790       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23791       // there is no psrai.b
23792       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23793       unsigned SraAmt = ~0;
23794       if (Mask.getOpcode() == ISD::SRA) {
23795         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23796           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23797             SraAmt = AmtConst->getZExtValue();
23798       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23799         SDValue SraC = Mask.getOperand(1);
23800         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23801       }
23802       if ((SraAmt + 1) != EltBits)
23803         return SDValue();
23804
23805       SDLoc DL(N);
23806
23807       // Now we know we at least have a plendvb with the mask val.  See if
23808       // we can form a psignb/w/d.
23809       // psign = x.type == y.type == mask.type && y = sub(0, x);
23810       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23811           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23812           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23813         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23814                "Unsupported VT for PSIGN");
23815         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23816         return DAG.getBitcast(VT, Mask);
23817       }
23818       // PBLENDVB only available on SSE 4.1
23819       if (!Subtarget->hasSSE41())
23820         return SDValue();
23821
23822       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23823
23824       X = DAG.getBitcast(BlendVT, X);
23825       Y = DAG.getBitcast(BlendVT, Y);
23826       Mask = DAG.getBitcast(BlendVT, Mask);
23827       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23828       return DAG.getBitcast(VT, Mask);
23829     }
23830   }
23831
23832   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23833     return SDValue();
23834
23835   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23836   MachineFunction &MF = DAG.getMachineFunction();
23837   bool OptForSize =
23838       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23839
23840   // SHLD/SHRD instructions have lower register pressure, but on some
23841   // platforms they have higher latency than the equivalent
23842   // series of shifts/or that would otherwise be generated.
23843   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23844   // have higher latencies and we are not optimizing for size.
23845   if (!OptForSize && Subtarget->isSHLDSlow())
23846     return SDValue();
23847
23848   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23849     std::swap(N0, N1);
23850   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23851     return SDValue();
23852   if (!N0.hasOneUse() || !N1.hasOneUse())
23853     return SDValue();
23854
23855   SDValue ShAmt0 = N0.getOperand(1);
23856   if (ShAmt0.getValueType() != MVT::i8)
23857     return SDValue();
23858   SDValue ShAmt1 = N1.getOperand(1);
23859   if (ShAmt1.getValueType() != MVT::i8)
23860     return SDValue();
23861   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23862     ShAmt0 = ShAmt0.getOperand(0);
23863   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23864     ShAmt1 = ShAmt1.getOperand(0);
23865
23866   SDLoc DL(N);
23867   unsigned Opc = X86ISD::SHLD;
23868   SDValue Op0 = N0.getOperand(0);
23869   SDValue Op1 = N1.getOperand(0);
23870   if (ShAmt0.getOpcode() == ISD::SUB) {
23871     Opc = X86ISD::SHRD;
23872     std::swap(Op0, Op1);
23873     std::swap(ShAmt0, ShAmt1);
23874   }
23875
23876   unsigned Bits = VT.getSizeInBits();
23877   if (ShAmt1.getOpcode() == ISD::SUB) {
23878     SDValue Sum = ShAmt1.getOperand(0);
23879     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23880       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23881       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23882         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23883       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23884         return DAG.getNode(Opc, DL, VT,
23885                            Op0, Op1,
23886                            DAG.getNode(ISD::TRUNCATE, DL,
23887                                        MVT::i8, ShAmt0));
23888     }
23889   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23890     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23891     if (ShAmt0C &&
23892         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23893       return DAG.getNode(Opc, DL, VT,
23894                          N0.getOperand(0), N1.getOperand(0),
23895                          DAG.getNode(ISD::TRUNCATE, DL,
23896                                        MVT::i8, ShAmt0));
23897   }
23898
23899   return SDValue();
23900 }
23901
23902 // Generate NEG and CMOV for integer abs.
23903 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23904   EVT VT = N->getValueType(0);
23905
23906   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23907   // 8-bit integer abs to NEG and CMOV.
23908   if (VT.isInteger() && VT.getSizeInBits() == 8)
23909     return SDValue();
23910
23911   SDValue N0 = N->getOperand(0);
23912   SDValue N1 = N->getOperand(1);
23913   SDLoc DL(N);
23914
23915   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23916   // and change it to SUB and CMOV.
23917   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23918       N0.getOpcode() == ISD::ADD &&
23919       N0.getOperand(1) == N1 &&
23920       N1.getOpcode() == ISD::SRA &&
23921       N1.getOperand(0) == N0.getOperand(0))
23922     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23923       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23924         // Generate SUB & CMOV.
23925         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23926                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23927
23928         SDValue Ops[] = { N0.getOperand(0), Neg,
23929                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23930                           SDValue(Neg.getNode(), 1) };
23931         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23932       }
23933   return SDValue();
23934 }
23935
23936 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23937 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23938                                  TargetLowering::DAGCombinerInfo &DCI,
23939                                  const X86Subtarget *Subtarget) {
23940   if (DCI.isBeforeLegalizeOps())
23941     return SDValue();
23942
23943   if (Subtarget->hasCMov())
23944     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23945       return RV;
23946
23947   return SDValue();
23948 }
23949
23950 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23951 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23952                                   TargetLowering::DAGCombinerInfo &DCI,
23953                                   const X86Subtarget *Subtarget) {
23954   LoadSDNode *Ld = cast<LoadSDNode>(N);
23955   EVT RegVT = Ld->getValueType(0);
23956   EVT MemVT = Ld->getMemoryVT();
23957   SDLoc dl(Ld);
23958   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23959
23960   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23961   // into two 16-byte operations.
23962   ISD::LoadExtType Ext = Ld->getExtensionType();
23963   unsigned Alignment = Ld->getAlignment();
23964   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23965   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23966       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23967     unsigned NumElems = RegVT.getVectorNumElements();
23968     if (NumElems < 2)
23969       return SDValue();
23970
23971     SDValue Ptr = Ld->getBasePtr();
23972     SDValue Increment =
23973         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23974
23975     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23976                                   NumElems/2);
23977     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23978                                 Ld->getPointerInfo(), Ld->isVolatile(),
23979                                 Ld->isNonTemporal(), Ld->isInvariant(),
23980                                 Alignment);
23981     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23982     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23983                                 Ld->getPointerInfo(), Ld->isVolatile(),
23984                                 Ld->isNonTemporal(), Ld->isInvariant(),
23985                                 std::min(16U, Alignment));
23986     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23987                              Load1.getValue(1),
23988                              Load2.getValue(1));
23989
23990     SDValue NewVec = DAG.getUNDEF(RegVT);
23991     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23992     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23993     return DCI.CombineTo(N, NewVec, TF, true);
23994   }
23995
23996   return SDValue();
23997 }
23998
23999 /// PerformMLOADCombine - Resolve extending loads
24000 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
24001                                    TargetLowering::DAGCombinerInfo &DCI,
24002                                    const X86Subtarget *Subtarget) {
24003   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
24004   if (Mld->getExtensionType() != ISD::SEXTLOAD)
24005     return SDValue();
24006
24007   EVT VT = Mld->getValueType(0);
24008   unsigned NumElems = VT.getVectorNumElements();
24009   EVT LdVT = Mld->getMemoryVT();
24010   SDLoc dl(Mld);
24011
24012   assert(LdVT != VT && "Cannot extend to the same type");
24013   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
24014   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
24015   // From, To sizes and ElemCount must be pow of two
24016   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24017     "Unexpected size for extending masked load");
24018
24019   unsigned SizeRatio  = ToSz / FromSz;
24020   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
24021
24022   // Create a type on which we perform the shuffle
24023   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24024           LdVT.getScalarType(), NumElems*SizeRatio);
24025   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24026
24027   // Convert Src0 value
24028   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
24029   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
24030     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24031     for (unsigned i = 0; i != NumElems; ++i)
24032       ShuffleVec[i] = i * SizeRatio;
24033
24034     // Can't shuffle using an illegal type.
24035     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24036             && "WideVecVT should be legal");
24037     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24038                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24039   }
24040   // Prepare the new mask
24041   SDValue NewMask;
24042   SDValue Mask = Mld->getMask();
24043   if (Mask.getValueType() == VT) {
24044     // Mask and original value have the same type
24045     NewMask = DAG.getBitcast(WideVecVT, Mask);
24046     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24047     for (unsigned i = 0; i != NumElems; ++i)
24048       ShuffleVec[i] = i * SizeRatio;
24049     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24050       ShuffleVec[i] = NumElems*SizeRatio;
24051     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24052                                    DAG.getConstant(0, dl, WideVecVT),
24053                                    &ShuffleVec[0]);
24054   }
24055   else {
24056     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24057     unsigned WidenNumElts = NumElems*SizeRatio;
24058     unsigned MaskNumElts = VT.getVectorNumElements();
24059     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24060                                      WidenNumElts);
24061
24062     unsigned NumConcat = WidenNumElts / MaskNumElts;
24063     SmallVector<SDValue, 16> Ops(NumConcat);
24064     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24065     Ops[0] = Mask;
24066     for (unsigned i = 1; i != NumConcat; ++i)
24067       Ops[i] = ZeroVal;
24068
24069     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24070   }
24071
24072   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24073                                      Mld->getBasePtr(), NewMask, WideSrc0,
24074                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24075                                      ISD::NON_EXTLOAD);
24076   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24077   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24078
24079 }
24080 /// PerformMSTORECombine - Resolve truncating stores
24081 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24082                                     const X86Subtarget *Subtarget) {
24083   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24084   if (!Mst->isTruncatingStore())
24085     return SDValue();
24086
24087   EVT VT = Mst->getValue().getValueType();
24088   unsigned NumElems = VT.getVectorNumElements();
24089   EVT StVT = Mst->getMemoryVT();
24090   SDLoc dl(Mst);
24091
24092   assert(StVT != VT && "Cannot truncate to the same type");
24093   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24094   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24095
24096   // From, To sizes and ElemCount must be pow of two
24097   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24098     "Unexpected size for truncating masked store");
24099   // We are going to use the original vector elt for storing.
24100   // Accumulated smaller vector elements must be a multiple of the store size.
24101   assert (((NumElems * FromSz) % ToSz) == 0 &&
24102           "Unexpected ratio for truncating masked store");
24103
24104   unsigned SizeRatio  = FromSz / ToSz;
24105   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24106
24107   // Create a type on which we perform the shuffle
24108   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24109           StVT.getScalarType(), NumElems*SizeRatio);
24110
24111   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24112
24113   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24114   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24115   for (unsigned i = 0; i != NumElems; ++i)
24116     ShuffleVec[i] = i * SizeRatio;
24117
24118   // Can't shuffle using an illegal type.
24119   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24120           && "WideVecVT should be legal");
24121
24122   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24123                                         DAG.getUNDEF(WideVecVT),
24124                                         &ShuffleVec[0]);
24125
24126   SDValue NewMask;
24127   SDValue Mask = Mst->getMask();
24128   if (Mask.getValueType() == VT) {
24129     // Mask and original value have the same type
24130     NewMask = DAG.getBitcast(WideVecVT, Mask);
24131     for (unsigned i = 0; i != NumElems; ++i)
24132       ShuffleVec[i] = i * SizeRatio;
24133     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24134       ShuffleVec[i] = NumElems*SizeRatio;
24135     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24136                                    DAG.getConstant(0, dl, WideVecVT),
24137                                    &ShuffleVec[0]);
24138   }
24139   else {
24140     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24141     unsigned WidenNumElts = NumElems*SizeRatio;
24142     unsigned MaskNumElts = VT.getVectorNumElements();
24143     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24144                                      WidenNumElts);
24145
24146     unsigned NumConcat = WidenNumElts / MaskNumElts;
24147     SmallVector<SDValue, 16> Ops(NumConcat);
24148     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24149     Ops[0] = Mask;
24150     for (unsigned i = 1; i != NumConcat; ++i)
24151       Ops[i] = ZeroVal;
24152
24153     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24154   }
24155
24156   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24157                             NewMask, StVT, Mst->getMemOperand(), false);
24158 }
24159 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24160 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24161                                    const X86Subtarget *Subtarget) {
24162   StoreSDNode *St = cast<StoreSDNode>(N);
24163   EVT VT = St->getValue().getValueType();
24164   EVT StVT = St->getMemoryVT();
24165   SDLoc dl(St);
24166   SDValue StoredVal = St->getOperand(1);
24167   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24168
24169   // If we are saving a concatenation of two XMM registers and 32-byte stores
24170   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24171   unsigned Alignment = St->getAlignment();
24172   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24173   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24174       StVT == VT && !IsAligned) {
24175     unsigned NumElems = VT.getVectorNumElements();
24176     if (NumElems < 2)
24177       return SDValue();
24178
24179     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24180     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24181
24182     SDValue Stride =
24183         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24184     SDValue Ptr0 = St->getBasePtr();
24185     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24186
24187     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24188                                 St->getPointerInfo(), St->isVolatile(),
24189                                 St->isNonTemporal(), Alignment);
24190     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24191                                 St->getPointerInfo(), St->isVolatile(),
24192                                 St->isNonTemporal(),
24193                                 std::min(16U, Alignment));
24194     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24195   }
24196
24197   // Optimize trunc store (of multiple scalars) to shuffle and store.
24198   // First, pack all of the elements in one place. Next, store to memory
24199   // in fewer chunks.
24200   if (St->isTruncatingStore() && VT.isVector()) {
24201     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24202     unsigned NumElems = VT.getVectorNumElements();
24203     assert(StVT != VT && "Cannot truncate to the same type");
24204     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24205     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24206
24207     // From, To sizes and ElemCount must be pow of two
24208     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24209     // We are going to use the original vector elt for storing.
24210     // Accumulated smaller vector elements must be a multiple of the store size.
24211     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24212
24213     unsigned SizeRatio  = FromSz / ToSz;
24214
24215     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24216
24217     // Create a type on which we perform the shuffle
24218     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24219             StVT.getScalarType(), NumElems*SizeRatio);
24220
24221     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24222
24223     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24224     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24225     for (unsigned i = 0; i != NumElems; ++i)
24226       ShuffleVec[i] = i * SizeRatio;
24227
24228     // Can't shuffle using an illegal type.
24229     if (!TLI.isTypeLegal(WideVecVT))
24230       return SDValue();
24231
24232     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24233                                          DAG.getUNDEF(WideVecVT),
24234                                          &ShuffleVec[0]);
24235     // At this point all of the data is stored at the bottom of the
24236     // register. We now need to save it to mem.
24237
24238     // Find the largest store unit
24239     MVT StoreType = MVT::i8;
24240     for (MVT Tp : MVT::integer_valuetypes()) {
24241       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24242         StoreType = Tp;
24243     }
24244
24245     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24246     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24247         (64 <= NumElems * ToSz))
24248       StoreType = MVT::f64;
24249
24250     // Bitcast the original vector into a vector of store-size units
24251     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24252             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24253     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24254     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24255     SmallVector<SDValue, 8> Chains;
24256     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24257                                         TLI.getPointerTy(DAG.getDataLayout()));
24258     SDValue Ptr = St->getBasePtr();
24259
24260     // Perform one or more big stores into memory.
24261     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24262       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24263                                    StoreType, ShuffWide,
24264                                    DAG.getIntPtrConstant(i, dl));
24265       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24266                                 St->getPointerInfo(), St->isVolatile(),
24267                                 St->isNonTemporal(), St->getAlignment());
24268       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24269       Chains.push_back(Ch);
24270     }
24271
24272     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24273   }
24274
24275   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24276   // the FP state in cases where an emms may be missing.
24277   // A preferable solution to the general problem is to figure out the right
24278   // places to insert EMMS.  This qualifies as a quick hack.
24279
24280   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24281   if (VT.getSizeInBits() != 64)
24282     return SDValue();
24283
24284   const Function *F = DAG.getMachineFunction().getFunction();
24285   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24286   bool F64IsLegal =
24287       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24288   if ((VT.isVector() ||
24289        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24290       isa<LoadSDNode>(St->getValue()) &&
24291       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24292       St->getChain().hasOneUse() && !St->isVolatile()) {
24293     SDNode* LdVal = St->getValue().getNode();
24294     LoadSDNode *Ld = nullptr;
24295     int TokenFactorIndex = -1;
24296     SmallVector<SDValue, 8> Ops;
24297     SDNode* ChainVal = St->getChain().getNode();
24298     // Must be a store of a load.  We currently handle two cases:  the load
24299     // is a direct child, and it's under an intervening TokenFactor.  It is
24300     // possible to dig deeper under nested TokenFactors.
24301     if (ChainVal == LdVal)
24302       Ld = cast<LoadSDNode>(St->getChain());
24303     else if (St->getValue().hasOneUse() &&
24304              ChainVal->getOpcode() == ISD::TokenFactor) {
24305       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24306         if (ChainVal->getOperand(i).getNode() == LdVal) {
24307           TokenFactorIndex = i;
24308           Ld = cast<LoadSDNode>(St->getValue());
24309         } else
24310           Ops.push_back(ChainVal->getOperand(i));
24311       }
24312     }
24313
24314     if (!Ld || !ISD::isNormalLoad(Ld))
24315       return SDValue();
24316
24317     // If this is not the MMX case, i.e. we are just turning i64 load/store
24318     // into f64 load/store, avoid the transformation if there are multiple
24319     // uses of the loaded value.
24320     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24321       return SDValue();
24322
24323     SDLoc LdDL(Ld);
24324     SDLoc StDL(N);
24325     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24326     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24327     // pair instead.
24328     if (Subtarget->is64Bit() || F64IsLegal) {
24329       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24330       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24331                                   Ld->getPointerInfo(), Ld->isVolatile(),
24332                                   Ld->isNonTemporal(), Ld->isInvariant(),
24333                                   Ld->getAlignment());
24334       SDValue NewChain = NewLd.getValue(1);
24335       if (TokenFactorIndex != -1) {
24336         Ops.push_back(NewChain);
24337         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24338       }
24339       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24340                           St->getPointerInfo(),
24341                           St->isVolatile(), St->isNonTemporal(),
24342                           St->getAlignment());
24343     }
24344
24345     // Otherwise, lower to two pairs of 32-bit loads / stores.
24346     SDValue LoAddr = Ld->getBasePtr();
24347     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24348                                  DAG.getConstant(4, LdDL, MVT::i32));
24349
24350     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24351                                Ld->getPointerInfo(),
24352                                Ld->isVolatile(), Ld->isNonTemporal(),
24353                                Ld->isInvariant(), Ld->getAlignment());
24354     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24355                                Ld->getPointerInfo().getWithOffset(4),
24356                                Ld->isVolatile(), Ld->isNonTemporal(),
24357                                Ld->isInvariant(),
24358                                MinAlign(Ld->getAlignment(), 4));
24359
24360     SDValue NewChain = LoLd.getValue(1);
24361     if (TokenFactorIndex != -1) {
24362       Ops.push_back(LoLd);
24363       Ops.push_back(HiLd);
24364       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24365     }
24366
24367     LoAddr = St->getBasePtr();
24368     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24369                          DAG.getConstant(4, StDL, MVT::i32));
24370
24371     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24372                                 St->getPointerInfo(),
24373                                 St->isVolatile(), St->isNonTemporal(),
24374                                 St->getAlignment());
24375     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24376                                 St->getPointerInfo().getWithOffset(4),
24377                                 St->isVolatile(),
24378                                 St->isNonTemporal(),
24379                                 MinAlign(St->getAlignment(), 4));
24380     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24381   }
24382
24383   // This is similar to the above case, but here we handle a scalar 64-bit
24384   // integer store that is extracted from a vector on a 32-bit target.
24385   // If we have SSE2, then we can treat it like a floating-point double
24386   // to get past legalization. The execution dependencies fixup pass will
24387   // choose the optimal machine instruction for the store if this really is
24388   // an integer or v2f32 rather than an f64.
24389   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24390       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24391     SDValue OldExtract = St->getOperand(1);
24392     SDValue ExtOp0 = OldExtract.getOperand(0);
24393     unsigned VecSize = ExtOp0.getValueSizeInBits();
24394     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24395     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24396     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24397                                      BitCast, OldExtract.getOperand(1));
24398     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24399                         St->getPointerInfo(), St->isVolatile(),
24400                         St->isNonTemporal(), St->getAlignment());
24401   }
24402
24403   return SDValue();
24404 }
24405
24406 /// Return 'true' if this vector operation is "horizontal"
24407 /// and return the operands for the horizontal operation in LHS and RHS.  A
24408 /// horizontal operation performs the binary operation on successive elements
24409 /// of its first operand, then on successive elements of its second operand,
24410 /// returning the resulting values in a vector.  For example, if
24411 ///   A = < float a0, float a1, float a2, float a3 >
24412 /// and
24413 ///   B = < float b0, float b1, float b2, float b3 >
24414 /// then the result of doing a horizontal operation on A and B is
24415 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24416 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24417 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24418 /// set to A, RHS to B, and the routine returns 'true'.
24419 /// Note that the binary operation should have the property that if one of the
24420 /// operands is UNDEF then the result is UNDEF.
24421 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24422   // Look for the following pattern: if
24423   //   A = < float a0, float a1, float a2, float a3 >
24424   //   B = < float b0, float b1, float b2, float b3 >
24425   // and
24426   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24427   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24428   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24429   // which is A horizontal-op B.
24430
24431   // At least one of the operands should be a vector shuffle.
24432   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24433       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24434     return false;
24435
24436   MVT VT = LHS.getSimpleValueType();
24437
24438   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24439          "Unsupported vector type for horizontal add/sub");
24440
24441   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24442   // operate independently on 128-bit lanes.
24443   unsigned NumElts = VT.getVectorNumElements();
24444   unsigned NumLanes = VT.getSizeInBits()/128;
24445   unsigned NumLaneElts = NumElts / NumLanes;
24446   assert((NumLaneElts % 2 == 0) &&
24447          "Vector type should have an even number of elements in each lane");
24448   unsigned HalfLaneElts = NumLaneElts/2;
24449
24450   // View LHS in the form
24451   //   LHS = VECTOR_SHUFFLE A, B, LMask
24452   // If LHS is not a shuffle then pretend it is the shuffle
24453   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24454   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24455   // type VT.
24456   SDValue A, B;
24457   SmallVector<int, 16> LMask(NumElts);
24458   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24459     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24460       A = LHS.getOperand(0);
24461     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24462       B = LHS.getOperand(1);
24463     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24464     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24465   } else {
24466     if (LHS.getOpcode() != ISD::UNDEF)
24467       A = LHS;
24468     for (unsigned i = 0; i != NumElts; ++i)
24469       LMask[i] = i;
24470   }
24471
24472   // Likewise, view RHS in the form
24473   //   RHS = VECTOR_SHUFFLE C, D, RMask
24474   SDValue C, D;
24475   SmallVector<int, 16> RMask(NumElts);
24476   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24477     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24478       C = RHS.getOperand(0);
24479     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24480       D = RHS.getOperand(1);
24481     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24482     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24483   } else {
24484     if (RHS.getOpcode() != ISD::UNDEF)
24485       C = RHS;
24486     for (unsigned i = 0; i != NumElts; ++i)
24487       RMask[i] = i;
24488   }
24489
24490   // Check that the shuffles are both shuffling the same vectors.
24491   if (!(A == C && B == D) && !(A == D && B == C))
24492     return false;
24493
24494   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24495   if (!A.getNode() && !B.getNode())
24496     return false;
24497
24498   // If A and B occur in reverse order in RHS, then "swap" them (which means
24499   // rewriting the mask).
24500   if (A != C)
24501     ShuffleVectorSDNode::commuteMask(RMask);
24502
24503   // At this point LHS and RHS are equivalent to
24504   //   LHS = VECTOR_SHUFFLE A, B, LMask
24505   //   RHS = VECTOR_SHUFFLE A, B, RMask
24506   // Check that the masks correspond to performing a horizontal operation.
24507   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24508     for (unsigned i = 0; i != NumLaneElts; ++i) {
24509       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24510
24511       // Ignore any UNDEF components.
24512       if (LIdx < 0 || RIdx < 0 ||
24513           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24514           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24515         continue;
24516
24517       // Check that successive elements are being operated on.  If not, this is
24518       // not a horizontal operation.
24519       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24520       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24521       if (!(LIdx == Index && RIdx == Index + 1) &&
24522           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24523         return false;
24524     }
24525   }
24526
24527   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24528   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24529   return true;
24530 }
24531
24532 /// Do target-specific dag combines on floating point adds.
24533 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24534                                   const X86Subtarget *Subtarget) {
24535   EVT VT = N->getValueType(0);
24536   SDValue LHS = N->getOperand(0);
24537   SDValue RHS = N->getOperand(1);
24538
24539   // Try to synthesize horizontal adds from adds of shuffles.
24540   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24541        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24542       isHorizontalBinOp(LHS, RHS, true))
24543     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24544   return SDValue();
24545 }
24546
24547 /// Do target-specific dag combines on floating point subs.
24548 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24549                                   const X86Subtarget *Subtarget) {
24550   EVT VT = N->getValueType(0);
24551   SDValue LHS = N->getOperand(0);
24552   SDValue RHS = N->getOperand(1);
24553
24554   // Try to synthesize horizontal subs from subs of shuffles.
24555   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24556        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24557       isHorizontalBinOp(LHS, RHS, false))
24558     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24559   return SDValue();
24560 }
24561
24562 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24563 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24564   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24565
24566   // F[X]OR(0.0, x) -> x
24567   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24568     if (C->getValueAPF().isPosZero())
24569       return N->getOperand(1);
24570
24571   // F[X]OR(x, 0.0) -> x
24572   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24573     if (C->getValueAPF().isPosZero())
24574       return N->getOperand(0);
24575   return SDValue();
24576 }
24577
24578 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24579 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24580   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24581
24582   // Only perform optimizations if UnsafeMath is used.
24583   if (!DAG.getTarget().Options.UnsafeFPMath)
24584     return SDValue();
24585
24586   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24587   // into FMINC and FMAXC, which are Commutative operations.
24588   unsigned NewOp = 0;
24589   switch (N->getOpcode()) {
24590     default: llvm_unreachable("unknown opcode");
24591     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24592     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24593   }
24594
24595   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24596                      N->getOperand(0), N->getOperand(1));
24597 }
24598
24599 /// Do target-specific dag combines on X86ISD::FAND nodes.
24600 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24601   // FAND(0.0, x) -> 0.0
24602   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24603     if (C->getValueAPF().isPosZero())
24604       return N->getOperand(0);
24605
24606   // FAND(x, 0.0) -> 0.0
24607   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24608     if (C->getValueAPF().isPosZero())
24609       return N->getOperand(1);
24610
24611   return SDValue();
24612 }
24613
24614 /// Do target-specific dag combines on X86ISD::FANDN nodes
24615 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24616   // FANDN(0.0, x) -> x
24617   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24618     if (C->getValueAPF().isPosZero())
24619       return N->getOperand(1);
24620
24621   // FANDN(x, 0.0) -> 0.0
24622   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24623     if (C->getValueAPF().isPosZero())
24624       return N->getOperand(1);
24625
24626   return SDValue();
24627 }
24628
24629 static SDValue PerformBTCombine(SDNode *N,
24630                                 SelectionDAG &DAG,
24631                                 TargetLowering::DAGCombinerInfo &DCI) {
24632   // BT ignores high bits in the bit index operand.
24633   SDValue Op1 = N->getOperand(1);
24634   if (Op1.hasOneUse()) {
24635     unsigned BitWidth = Op1.getValueSizeInBits();
24636     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24637     APInt KnownZero, KnownOne;
24638     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24639                                           !DCI.isBeforeLegalizeOps());
24640     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24641     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24642         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24643       DCI.CommitTargetLoweringOpt(TLO);
24644   }
24645   return SDValue();
24646 }
24647
24648 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24649   SDValue Op = N->getOperand(0);
24650   if (Op.getOpcode() == ISD::BITCAST)
24651     Op = Op.getOperand(0);
24652   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24653   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24654       VT.getVectorElementType().getSizeInBits() ==
24655       OpVT.getVectorElementType().getSizeInBits()) {
24656     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24657   }
24658   return SDValue();
24659 }
24660
24661 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24662                                                const X86Subtarget *Subtarget) {
24663   EVT VT = N->getValueType(0);
24664   if (!VT.isVector())
24665     return SDValue();
24666
24667   SDValue N0 = N->getOperand(0);
24668   SDValue N1 = N->getOperand(1);
24669   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24670   SDLoc dl(N);
24671
24672   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24673   // both SSE and AVX2 since there is no sign-extended shift right
24674   // operation on a vector with 64-bit elements.
24675   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24676   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24677   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24678       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24679     SDValue N00 = N0.getOperand(0);
24680
24681     // EXTLOAD has a better solution on AVX2,
24682     // it may be replaced with X86ISD::VSEXT node.
24683     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24684       if (!ISD::isNormalLoad(N00.getNode()))
24685         return SDValue();
24686
24687     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24688         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24689                                   N00, N1);
24690       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24691     }
24692   }
24693   return SDValue();
24694 }
24695
24696 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24697                                   TargetLowering::DAGCombinerInfo &DCI,
24698                                   const X86Subtarget *Subtarget) {
24699   SDValue N0 = N->getOperand(0);
24700   EVT VT = N->getValueType(0);
24701   EVT SVT = VT.getScalarType();
24702   EVT InVT = N0.getValueType();
24703   EVT InSVT = InVT.getScalarType();
24704   SDLoc DL(N);
24705
24706   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24707   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24708   // This exposes the sext to the sdivrem lowering, so that it directly extends
24709   // from AH (which we otherwise need to do contortions to access).
24710   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24711       InVT == MVT::i8 && VT == MVT::i32) {
24712     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24713     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24714                             N0.getOperand(0), N0.getOperand(1));
24715     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24716     return R.getValue(1);
24717   }
24718
24719   if (!DCI.isBeforeLegalizeOps()) {
24720     if (InVT == MVT::i1) {
24721       SDValue Zero = DAG.getConstant(0, DL, VT);
24722       SDValue AllOnes =
24723         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24724       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24725     }
24726     return SDValue();
24727   }
24728
24729   if (VT.isVector() && Subtarget->hasSSE2()) {
24730     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24731       EVT InVT = N.getValueType();
24732       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24733                                    Size / InVT.getScalarSizeInBits());
24734       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24735                                     DAG.getUNDEF(InVT));
24736       Opnds[0] = N;
24737       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24738     };
24739
24740     // If target-size is less than 128-bits, extend to a type that would extend
24741     // to 128 bits, extend that and extract the original target vector.
24742     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24743         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24744         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24745       unsigned Scale = 128 / VT.getSizeInBits();
24746       EVT ExVT =
24747           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24748       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24749       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24750       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24751                          DAG.getIntPtrConstant(0, DL));
24752     }
24753
24754     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24755     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24756     if (VT.getSizeInBits() == 128 &&
24757         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24758         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24759       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24760       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24761     }
24762
24763     // On pre-AVX2 targets, split into 128-bit nodes of
24764     // ISD::SIGN_EXTEND_VECTOR_INREG.
24765     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24766         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24767         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24768       unsigned NumVecs = VT.getSizeInBits() / 128;
24769       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24770       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24771       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24772
24773       SmallVector<SDValue, 8> Opnds;
24774       for (unsigned i = 0, Offset = 0; i != NumVecs;
24775            ++i, Offset += NumSubElts) {
24776         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24777                                      DAG.getIntPtrConstant(Offset, DL));
24778         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24779         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24780         Opnds.push_back(SrcVec);
24781       }
24782       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24783     }
24784   }
24785
24786   if (!Subtarget->hasFp256())
24787     return SDValue();
24788
24789   if (VT.isVector() && VT.getSizeInBits() == 256)
24790     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24791       return R;
24792
24793   return SDValue();
24794 }
24795
24796 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24797                                  const X86Subtarget* Subtarget) {
24798   SDLoc dl(N);
24799   EVT VT = N->getValueType(0);
24800
24801   // Let legalize expand this if it isn't a legal type yet.
24802   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24803     return SDValue();
24804
24805   EVT ScalarVT = VT.getScalarType();
24806   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24807       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24808        !Subtarget->hasAVX512()))
24809     return SDValue();
24810
24811   SDValue A = N->getOperand(0);
24812   SDValue B = N->getOperand(1);
24813   SDValue C = N->getOperand(2);
24814
24815   bool NegA = (A.getOpcode() == ISD::FNEG);
24816   bool NegB = (B.getOpcode() == ISD::FNEG);
24817   bool NegC = (C.getOpcode() == ISD::FNEG);
24818
24819   // Negative multiplication when NegA xor NegB
24820   bool NegMul = (NegA != NegB);
24821   if (NegA)
24822     A = A.getOperand(0);
24823   if (NegB)
24824     B = B.getOperand(0);
24825   if (NegC)
24826     C = C.getOperand(0);
24827
24828   unsigned Opcode;
24829   if (!NegMul)
24830     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24831   else
24832     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24833
24834   return DAG.getNode(Opcode, dl, VT, A, B, C);
24835 }
24836
24837 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24838                                   TargetLowering::DAGCombinerInfo &DCI,
24839                                   const X86Subtarget *Subtarget) {
24840   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24841   //           (and (i32 x86isd::setcc_carry), 1)
24842   // This eliminates the zext. This transformation is necessary because
24843   // ISD::SETCC is always legalized to i8.
24844   SDLoc dl(N);
24845   SDValue N0 = N->getOperand(0);
24846   EVT VT = N->getValueType(0);
24847
24848   if (N0.getOpcode() == ISD::AND &&
24849       N0.hasOneUse() &&
24850       N0.getOperand(0).hasOneUse()) {
24851     SDValue N00 = N0.getOperand(0);
24852     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24853       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24854       if (!C || C->getZExtValue() != 1)
24855         return SDValue();
24856       return DAG.getNode(ISD::AND, dl, VT,
24857                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24858                                      N00.getOperand(0), N00.getOperand(1)),
24859                          DAG.getConstant(1, dl, VT));
24860     }
24861   }
24862
24863   if (N0.getOpcode() == ISD::TRUNCATE &&
24864       N0.hasOneUse() &&
24865       N0.getOperand(0).hasOneUse()) {
24866     SDValue N00 = N0.getOperand(0);
24867     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24868       return DAG.getNode(ISD::AND, dl, VT,
24869                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24870                                      N00.getOperand(0), N00.getOperand(1)),
24871                          DAG.getConstant(1, dl, VT));
24872     }
24873   }
24874
24875   if (VT.is256BitVector())
24876     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24877       return R;
24878
24879   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24880   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24881   // This exposes the zext to the udivrem lowering, so that it directly extends
24882   // from AH (which we otherwise need to do contortions to access).
24883   if (N0.getOpcode() == ISD::UDIVREM &&
24884       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24885       (VT == MVT::i32 || VT == MVT::i64)) {
24886     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24887     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24888                             N0.getOperand(0), N0.getOperand(1));
24889     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24890     return R.getValue(1);
24891   }
24892
24893   return SDValue();
24894 }
24895
24896 // Optimize x == -y --> x+y == 0
24897 //          x != -y --> x+y != 0
24898 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24899                                       const X86Subtarget* Subtarget) {
24900   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24901   SDValue LHS = N->getOperand(0);
24902   SDValue RHS = N->getOperand(1);
24903   EVT VT = N->getValueType(0);
24904   SDLoc DL(N);
24905
24906   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24907     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24908       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24909         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24910                                    LHS.getOperand(1));
24911         return DAG.getSetCC(DL, N->getValueType(0), addV,
24912                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24913       }
24914   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24915     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24916       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24917         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24918                                    RHS.getOperand(1));
24919         return DAG.getSetCC(DL, N->getValueType(0), addV,
24920                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24921       }
24922
24923   if (VT.getScalarType() == MVT::i1 &&
24924       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24925     bool IsSEXT0 =
24926         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24927         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24928     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24929
24930     if (!IsSEXT0 || !IsVZero1) {
24931       // Swap the operands and update the condition code.
24932       std::swap(LHS, RHS);
24933       CC = ISD::getSetCCSwappedOperands(CC);
24934
24935       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24936                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24937       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24938     }
24939
24940     if (IsSEXT0 && IsVZero1) {
24941       assert(VT == LHS.getOperand(0).getValueType() &&
24942              "Uexpected operand type");
24943       if (CC == ISD::SETGT)
24944         return DAG.getConstant(0, DL, VT);
24945       if (CC == ISD::SETLE)
24946         return DAG.getConstant(1, DL, VT);
24947       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24948         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24949
24950       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24951              "Unexpected condition code!");
24952       return LHS.getOperand(0);
24953     }
24954   }
24955
24956   return SDValue();
24957 }
24958
24959 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24960                                          SelectionDAG &DAG) {
24961   SDLoc dl(Load);
24962   MVT VT = Load->getSimpleValueType(0);
24963   MVT EVT = VT.getVectorElementType();
24964   SDValue Addr = Load->getOperand(1);
24965   SDValue NewAddr = DAG.getNode(
24966       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24967       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24968                       Addr.getSimpleValueType()));
24969
24970   SDValue NewLoad =
24971       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24972                   DAG.getMachineFunction().getMachineMemOperand(
24973                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24974   return NewLoad;
24975 }
24976
24977 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24978                                       const X86Subtarget *Subtarget) {
24979   SDLoc dl(N);
24980   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24981   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24982          "X86insertps is only defined for v4x32");
24983
24984   SDValue Ld = N->getOperand(1);
24985   if (MayFoldLoad(Ld)) {
24986     // Extract the countS bits from the immediate so we can get the proper
24987     // address when narrowing the vector load to a specific element.
24988     // When the second source op is a memory address, insertps doesn't use
24989     // countS and just gets an f32 from that address.
24990     unsigned DestIndex =
24991         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24992
24993     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24994
24995     // Create this as a scalar to vector to match the instruction pattern.
24996     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24997     // countS bits are ignored when loading from memory on insertps, which
24998     // means we don't need to explicitly set them to 0.
24999     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
25000                        LoadScalarToVector, N->getOperand(2));
25001   }
25002   return SDValue();
25003 }
25004
25005 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
25006   SDValue V0 = N->getOperand(0);
25007   SDValue V1 = N->getOperand(1);
25008   SDLoc DL(N);
25009   EVT VT = N->getValueType(0);
25010
25011   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
25012   // operands and changing the mask to 1. This saves us a bunch of
25013   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
25014   // x86InstrInfo knows how to commute this back after instruction selection
25015   // if it would help register allocation.
25016
25017   // TODO: If optimizing for size or a processor that doesn't suffer from
25018   // partial register update stalls, this should be transformed into a MOVSD
25019   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
25020
25021   if (VT == MVT::v2f64)
25022     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
25023       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
25024         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
25025         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
25026       }
25027
25028   return SDValue();
25029 }
25030
25031 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
25032 // as "sbb reg,reg", since it can be extended without zext and produces
25033 // an all-ones bit which is more useful than 0/1 in some cases.
25034 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
25035                                MVT VT) {
25036   if (VT == MVT::i8)
25037     return DAG.getNode(ISD::AND, DL, VT,
25038                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25039                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25040                                    EFLAGS),
25041                        DAG.getConstant(1, DL, VT));
25042   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25043   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25044                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25045                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25046                                  EFLAGS));
25047 }
25048
25049 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25050 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25051                                    TargetLowering::DAGCombinerInfo &DCI,
25052                                    const X86Subtarget *Subtarget) {
25053   SDLoc DL(N);
25054   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25055   SDValue EFLAGS = N->getOperand(1);
25056
25057   if (CC == X86::COND_A) {
25058     // Try to convert COND_A into COND_B in an attempt to facilitate
25059     // materializing "setb reg".
25060     //
25061     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25062     // cannot take an immediate as its first operand.
25063     //
25064     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25065         EFLAGS.getValueType().isInteger() &&
25066         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25067       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25068                                    EFLAGS.getNode()->getVTList(),
25069                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25070       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25071       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25072     }
25073   }
25074
25075   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25076   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25077   // cases.
25078   if (CC == X86::COND_B)
25079     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25080
25081   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25082     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25083     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25084   }
25085
25086   return SDValue();
25087 }
25088
25089 // Optimize branch condition evaluation.
25090 //
25091 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25092                                     TargetLowering::DAGCombinerInfo &DCI,
25093                                     const X86Subtarget *Subtarget) {
25094   SDLoc DL(N);
25095   SDValue Chain = N->getOperand(0);
25096   SDValue Dest = N->getOperand(1);
25097   SDValue EFLAGS = N->getOperand(3);
25098   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25099
25100   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25101     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25102     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25103                        Flags);
25104   }
25105
25106   return SDValue();
25107 }
25108
25109 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25110                                                          SelectionDAG &DAG) {
25111   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25112   // optimize away operation when it's from a constant.
25113   //
25114   // The general transformation is:
25115   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25116   //       AND(VECTOR_CMP(x,y), constant2)
25117   //    constant2 = UNARYOP(constant)
25118
25119   // Early exit if this isn't a vector operation, the operand of the
25120   // unary operation isn't a bitwise AND, or if the sizes of the operations
25121   // aren't the same.
25122   EVT VT = N->getValueType(0);
25123   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25124       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25125       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25126     return SDValue();
25127
25128   // Now check that the other operand of the AND is a constant. We could
25129   // make the transformation for non-constant splats as well, but it's unclear
25130   // that would be a benefit as it would not eliminate any operations, just
25131   // perform one more step in scalar code before moving to the vector unit.
25132   if (BuildVectorSDNode *BV =
25133           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25134     // Bail out if the vector isn't a constant.
25135     if (!BV->isConstant())
25136       return SDValue();
25137
25138     // Everything checks out. Build up the new and improved node.
25139     SDLoc DL(N);
25140     EVT IntVT = BV->getValueType(0);
25141     // Create a new constant of the appropriate type for the transformed
25142     // DAG.
25143     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25144     // The AND node needs bitcasts to/from an integer vector type around it.
25145     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25146     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25147                                  N->getOperand(0)->getOperand(0), MaskConst);
25148     SDValue Res = DAG.getBitcast(VT, NewAnd);
25149     return Res;
25150   }
25151
25152   return SDValue();
25153 }
25154
25155 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25156                                         const X86Subtarget *Subtarget) {
25157   SDValue Op0 = N->getOperand(0);
25158   EVT VT = N->getValueType(0);
25159   EVT InVT = Op0.getValueType();
25160   EVT InSVT = InVT.getScalarType();
25161   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25162
25163   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25164   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25165   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25166     SDLoc dl(N);
25167     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25168                                  InVT.getVectorNumElements());
25169     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25170
25171     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25172       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25173
25174     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25175   }
25176
25177   return SDValue();
25178 }
25179
25180 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25181                                         const X86Subtarget *Subtarget) {
25182   // First try to optimize away the conversion entirely when it's
25183   // conditionally from a constant. Vectors only.
25184   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25185     return Res;
25186
25187   // Now move on to more general possibilities.
25188   SDValue Op0 = N->getOperand(0);
25189   EVT VT = N->getValueType(0);
25190   EVT InVT = Op0.getValueType();
25191   EVT InSVT = InVT.getScalarType();
25192
25193   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25194   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25195   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25196     SDLoc dl(N);
25197     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25198                                  InVT.getVectorNumElements());
25199     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25200     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25201   }
25202
25203   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25204   // a 32-bit target where SSE doesn't support i64->FP operations.
25205   if (Op0.getOpcode() == ISD::LOAD) {
25206     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25207     EVT LdVT = Ld->getValueType(0);
25208
25209     // This transformation is not supported if the result type is f16
25210     if (VT == MVT::f16)
25211       return SDValue();
25212
25213     if (!Ld->isVolatile() && !VT.isVector() &&
25214         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25215         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25216       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25217           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25218       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25219       return FILDChain;
25220     }
25221   }
25222   return SDValue();
25223 }
25224
25225 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25226 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25227                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25228   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25229   // the result is either zero or one (depending on the input carry bit).
25230   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25231   if (X86::isZeroNode(N->getOperand(0)) &&
25232       X86::isZeroNode(N->getOperand(1)) &&
25233       // We don't have a good way to replace an EFLAGS use, so only do this when
25234       // dead right now.
25235       SDValue(N, 1).use_empty()) {
25236     SDLoc DL(N);
25237     EVT VT = N->getValueType(0);
25238     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25239     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25240                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25241                                            DAG.getConstant(X86::COND_B, DL,
25242                                                            MVT::i8),
25243                                            N->getOperand(2)),
25244                                DAG.getConstant(1, DL, VT));
25245     return DCI.CombineTo(N, Res1, CarryOut);
25246   }
25247
25248   return SDValue();
25249 }
25250
25251 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25252 //      (add Y, (setne X, 0)) -> sbb -1, Y
25253 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25254 //      (sub (setne X, 0), Y) -> adc -1, Y
25255 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25256   SDLoc DL(N);
25257
25258   // Look through ZExts.
25259   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25260   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25261     return SDValue();
25262
25263   SDValue SetCC = Ext.getOperand(0);
25264   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25265     return SDValue();
25266
25267   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25268   if (CC != X86::COND_E && CC != X86::COND_NE)
25269     return SDValue();
25270
25271   SDValue Cmp = SetCC.getOperand(1);
25272   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25273       !X86::isZeroNode(Cmp.getOperand(1)) ||
25274       !Cmp.getOperand(0).getValueType().isInteger())
25275     return SDValue();
25276
25277   SDValue CmpOp0 = Cmp.getOperand(0);
25278   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25279                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25280
25281   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25282   if (CC == X86::COND_NE)
25283     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25284                        DL, OtherVal.getValueType(), OtherVal,
25285                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25286                        NewCmp);
25287   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25288                      DL, OtherVal.getValueType(), OtherVal,
25289                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25290 }
25291
25292 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25293 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25294                                  const X86Subtarget *Subtarget) {
25295   EVT VT = N->getValueType(0);
25296   SDValue Op0 = N->getOperand(0);
25297   SDValue Op1 = N->getOperand(1);
25298
25299   // Try to synthesize horizontal adds from adds of shuffles.
25300   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25301        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25302       isHorizontalBinOp(Op0, Op1, true))
25303     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25304
25305   return OptimizeConditionalInDecrement(N, DAG);
25306 }
25307
25308 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25309                                  const X86Subtarget *Subtarget) {
25310   SDValue Op0 = N->getOperand(0);
25311   SDValue Op1 = N->getOperand(1);
25312
25313   // X86 can't encode an immediate LHS of a sub. See if we can push the
25314   // negation into a preceding instruction.
25315   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25316     // If the RHS of the sub is a XOR with one use and a constant, invert the
25317     // immediate. Then add one to the LHS of the sub so we can turn
25318     // X-Y -> X+~Y+1, saving one register.
25319     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25320         isa<ConstantSDNode>(Op1.getOperand(1))) {
25321       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25322       EVT VT = Op0.getValueType();
25323       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25324                                    Op1.getOperand(0),
25325                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25326       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25327                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25328     }
25329   }
25330
25331   // Try to synthesize horizontal adds from adds of shuffles.
25332   EVT VT = N->getValueType(0);
25333   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25334        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25335       isHorizontalBinOp(Op0, Op1, true))
25336     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25337
25338   return OptimizeConditionalInDecrement(N, DAG);
25339 }
25340
25341 /// performVZEXTCombine - Performs build vector combines
25342 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25343                                    TargetLowering::DAGCombinerInfo &DCI,
25344                                    const X86Subtarget *Subtarget) {
25345   SDLoc DL(N);
25346   MVT VT = N->getSimpleValueType(0);
25347   SDValue Op = N->getOperand(0);
25348   MVT OpVT = Op.getSimpleValueType();
25349   MVT OpEltVT = OpVT.getVectorElementType();
25350   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25351
25352   // (vzext (bitcast (vzext (x)) -> (vzext x)
25353   SDValue V = Op;
25354   while (V.getOpcode() == ISD::BITCAST)
25355     V = V.getOperand(0);
25356
25357   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25358     MVT InnerVT = V.getSimpleValueType();
25359     MVT InnerEltVT = InnerVT.getVectorElementType();
25360
25361     // If the element sizes match exactly, we can just do one larger vzext. This
25362     // is always an exact type match as vzext operates on integer types.
25363     if (OpEltVT == InnerEltVT) {
25364       assert(OpVT == InnerVT && "Types must match for vzext!");
25365       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25366     }
25367
25368     // The only other way we can combine them is if only a single element of the
25369     // inner vzext is used in the input to the outer vzext.
25370     if (InnerEltVT.getSizeInBits() < InputBits)
25371       return SDValue();
25372
25373     // In this case, the inner vzext is completely dead because we're going to
25374     // only look at bits inside of the low element. Just do the outer vzext on
25375     // a bitcast of the input to the inner.
25376     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25377   }
25378
25379   // Check if we can bypass extracting and re-inserting an element of an input
25380   // vector. Essentialy:
25381   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25382   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25383       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25384       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25385     SDValue ExtractedV = V.getOperand(0);
25386     SDValue OrigV = ExtractedV.getOperand(0);
25387     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25388       if (ExtractIdx->getZExtValue() == 0) {
25389         MVT OrigVT = OrigV.getSimpleValueType();
25390         // Extract a subvector if necessary...
25391         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25392           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25393           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25394                                     OrigVT.getVectorNumElements() / Ratio);
25395           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25396                               DAG.getIntPtrConstant(0, DL));
25397         }
25398         Op = DAG.getBitcast(OpVT, OrigV);
25399         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25400       }
25401   }
25402
25403   return SDValue();
25404 }
25405
25406 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25407                                              DAGCombinerInfo &DCI) const {
25408   SelectionDAG &DAG = DCI.DAG;
25409   switch (N->getOpcode()) {
25410   default: break;
25411   case ISD::EXTRACT_VECTOR_ELT:
25412     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25413   case ISD::VSELECT:
25414   case ISD::SELECT:
25415   case X86ISD::SHRUNKBLEND:
25416     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25417   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25418   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25419   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25420   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25421   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25422   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25423   case ISD::SHL:
25424   case ISD::SRA:
25425   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25426   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25427   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25428   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25429   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25430   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25431   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25432   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25433   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25434   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25435   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25436   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25437   case X86ISD::FXOR:
25438   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25439   case X86ISD::FMIN:
25440   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25441   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25442   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25443   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25444   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25445   case ISD::ANY_EXTEND:
25446   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25447   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25448   case ISD::SIGN_EXTEND_INREG:
25449     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25450   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25451   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25452   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25453   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25454   case X86ISD::SHUFP:       // Handle all target specific shuffles
25455   case X86ISD::PALIGNR:
25456   case X86ISD::UNPCKH:
25457   case X86ISD::UNPCKL:
25458   case X86ISD::MOVHLPS:
25459   case X86ISD::MOVLHPS:
25460   case X86ISD::PSHUFB:
25461   case X86ISD::PSHUFD:
25462   case X86ISD::PSHUFHW:
25463   case X86ISD::PSHUFLW:
25464   case X86ISD::MOVSS:
25465   case X86ISD::MOVSD:
25466   case X86ISD::VPERMILPI:
25467   case X86ISD::VPERM2X128:
25468   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25469   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25470   case ISD::INTRINSIC_WO_CHAIN:
25471     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25472   case X86ISD::INSERTPS: {
25473     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25474       return PerformINSERTPSCombine(N, DAG, Subtarget);
25475     break;
25476   }
25477   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25478   }
25479
25480   return SDValue();
25481 }
25482
25483 /// isTypeDesirableForOp - Return true if the target has native support for
25484 /// the specified value type and it is 'desirable' to use the type for the
25485 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25486 /// instruction encodings are longer and some i16 instructions are slow.
25487 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25488   if (!isTypeLegal(VT))
25489     return false;
25490   if (VT != MVT::i16)
25491     return true;
25492
25493   switch (Opc) {
25494   default:
25495     return true;
25496   case ISD::LOAD:
25497   case ISD::SIGN_EXTEND:
25498   case ISD::ZERO_EXTEND:
25499   case ISD::ANY_EXTEND:
25500   case ISD::SHL:
25501   case ISD::SRL:
25502   case ISD::SUB:
25503   case ISD::ADD:
25504   case ISD::MUL:
25505   case ISD::AND:
25506   case ISD::OR:
25507   case ISD::XOR:
25508     return false;
25509   }
25510 }
25511
25512 /// IsDesirableToPromoteOp - This method query the target whether it is
25513 /// beneficial for dag combiner to promote the specified node. If true, it
25514 /// should return the desired promotion type by reference.
25515 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25516   EVT VT = Op.getValueType();
25517   if (VT != MVT::i16)
25518     return false;
25519
25520   bool Promote = false;
25521   bool Commute = false;
25522   switch (Op.getOpcode()) {
25523   default: break;
25524   case ISD::LOAD: {
25525     LoadSDNode *LD = cast<LoadSDNode>(Op);
25526     // If the non-extending load has a single use and it's not live out, then it
25527     // might be folded.
25528     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25529                                                      Op.hasOneUse()*/) {
25530       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25531              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25532         // The only case where we'd want to promote LOAD (rather then it being
25533         // promoted as an operand is when it's only use is liveout.
25534         if (UI->getOpcode() != ISD::CopyToReg)
25535           return false;
25536       }
25537     }
25538     Promote = true;
25539     break;
25540   }
25541   case ISD::SIGN_EXTEND:
25542   case ISD::ZERO_EXTEND:
25543   case ISD::ANY_EXTEND:
25544     Promote = true;
25545     break;
25546   case ISD::SHL:
25547   case ISD::SRL: {
25548     SDValue N0 = Op.getOperand(0);
25549     // Look out for (store (shl (load), x)).
25550     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25551       return false;
25552     Promote = true;
25553     break;
25554   }
25555   case ISD::ADD:
25556   case ISD::MUL:
25557   case ISD::AND:
25558   case ISD::OR:
25559   case ISD::XOR:
25560     Commute = true;
25561     // fallthrough
25562   case ISD::SUB: {
25563     SDValue N0 = Op.getOperand(0);
25564     SDValue N1 = Op.getOperand(1);
25565     if (!Commute && MayFoldLoad(N1))
25566       return false;
25567     // Avoid disabling potential load folding opportunities.
25568     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25569       return false;
25570     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25571       return false;
25572     Promote = true;
25573   }
25574   }
25575
25576   PVT = MVT::i32;
25577   return Promote;
25578 }
25579
25580 //===----------------------------------------------------------------------===//
25581 //                           X86 Inline Assembly Support
25582 //===----------------------------------------------------------------------===//
25583
25584 // Helper to match a string separated by whitespace.
25585 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25586   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25587
25588   for (StringRef Piece : Pieces) {
25589     if (!S.startswith(Piece)) // Check if the piece matches.
25590       return false;
25591
25592     S = S.substr(Piece.size());
25593     StringRef::size_type Pos = S.find_first_not_of(" \t");
25594     if (Pos == 0) // We matched a prefix.
25595       return false;
25596
25597     S = S.substr(Pos);
25598   }
25599
25600   return S.empty();
25601 }
25602
25603 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25604
25605   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25606     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25607         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25608         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25609
25610       if (AsmPieces.size() == 3)
25611         return true;
25612       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25613         return true;
25614     }
25615   }
25616   return false;
25617 }
25618
25619 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25620   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25621
25622   std::string AsmStr = IA->getAsmString();
25623
25624   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25625   if (!Ty || Ty->getBitWidth() % 16 != 0)
25626     return false;
25627
25628   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25629   SmallVector<StringRef, 4> AsmPieces;
25630   SplitString(AsmStr, AsmPieces, ";\n");
25631
25632   switch (AsmPieces.size()) {
25633   default: return false;
25634   case 1:
25635     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25636     // we will turn this bswap into something that will be lowered to logical
25637     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25638     // lower so don't worry about this.
25639     // bswap $0
25640     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25641         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25642         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25643         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25644         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25645         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25646       // No need to check constraints, nothing other than the equivalent of
25647       // "=r,0" would be valid here.
25648       return IntrinsicLowering::LowerToByteSwap(CI);
25649     }
25650
25651     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25652     if (CI->getType()->isIntegerTy(16) &&
25653         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25654         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25655          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25656       AsmPieces.clear();
25657       StringRef ConstraintsStr = IA->getConstraintString();
25658       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25659       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25660       if (clobbersFlagRegisters(AsmPieces))
25661         return IntrinsicLowering::LowerToByteSwap(CI);
25662     }
25663     break;
25664   case 3:
25665     if (CI->getType()->isIntegerTy(32) &&
25666         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25667         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25668         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25669         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25670       AsmPieces.clear();
25671       StringRef ConstraintsStr = IA->getConstraintString();
25672       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25673       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25674       if (clobbersFlagRegisters(AsmPieces))
25675         return IntrinsicLowering::LowerToByteSwap(CI);
25676     }
25677
25678     if (CI->getType()->isIntegerTy(64)) {
25679       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25680       if (Constraints.size() >= 2 &&
25681           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25682           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25683         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25684         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25685             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25686             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25687           return IntrinsicLowering::LowerToByteSwap(CI);
25688       }
25689     }
25690     break;
25691   }
25692   return false;
25693 }
25694
25695 /// getConstraintType - Given a constraint letter, return the type of
25696 /// constraint it is for this target.
25697 X86TargetLowering::ConstraintType
25698 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25699   if (Constraint.size() == 1) {
25700     switch (Constraint[0]) {
25701     case 'R':
25702     case 'q':
25703     case 'Q':
25704     case 'f':
25705     case 't':
25706     case 'u':
25707     case 'y':
25708     case 'x':
25709     case 'Y':
25710     case 'l':
25711       return C_RegisterClass;
25712     case 'a':
25713     case 'b':
25714     case 'c':
25715     case 'd':
25716     case 'S':
25717     case 'D':
25718     case 'A':
25719       return C_Register;
25720     case 'I':
25721     case 'J':
25722     case 'K':
25723     case 'L':
25724     case 'M':
25725     case 'N':
25726     case 'G':
25727     case 'C':
25728     case 'e':
25729     case 'Z':
25730       return C_Other;
25731     default:
25732       break;
25733     }
25734   }
25735   return TargetLowering::getConstraintType(Constraint);
25736 }
25737
25738 /// Examine constraint type and operand type and determine a weight value.
25739 /// This object must already have been set up with the operand type
25740 /// and the current alternative constraint selected.
25741 TargetLowering::ConstraintWeight
25742   X86TargetLowering::getSingleConstraintMatchWeight(
25743     AsmOperandInfo &info, const char *constraint) const {
25744   ConstraintWeight weight = CW_Invalid;
25745   Value *CallOperandVal = info.CallOperandVal;
25746     // If we don't have a value, we can't do a match,
25747     // but allow it at the lowest weight.
25748   if (!CallOperandVal)
25749     return CW_Default;
25750   Type *type = CallOperandVal->getType();
25751   // Look at the constraint type.
25752   switch (*constraint) {
25753   default:
25754     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25755   case 'R':
25756   case 'q':
25757   case 'Q':
25758   case 'a':
25759   case 'b':
25760   case 'c':
25761   case 'd':
25762   case 'S':
25763   case 'D':
25764   case 'A':
25765     if (CallOperandVal->getType()->isIntegerTy())
25766       weight = CW_SpecificReg;
25767     break;
25768   case 'f':
25769   case 't':
25770   case 'u':
25771     if (type->isFloatingPointTy())
25772       weight = CW_SpecificReg;
25773     break;
25774   case 'y':
25775     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25776       weight = CW_SpecificReg;
25777     break;
25778   case 'x':
25779   case 'Y':
25780     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25781         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25782       weight = CW_Register;
25783     break;
25784   case 'I':
25785     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25786       if (C->getZExtValue() <= 31)
25787         weight = CW_Constant;
25788     }
25789     break;
25790   case 'J':
25791     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25792       if (C->getZExtValue() <= 63)
25793         weight = CW_Constant;
25794     }
25795     break;
25796   case 'K':
25797     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25798       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25799         weight = CW_Constant;
25800     }
25801     break;
25802   case 'L':
25803     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25804       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25805         weight = CW_Constant;
25806     }
25807     break;
25808   case 'M':
25809     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25810       if (C->getZExtValue() <= 3)
25811         weight = CW_Constant;
25812     }
25813     break;
25814   case 'N':
25815     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25816       if (C->getZExtValue() <= 0xff)
25817         weight = CW_Constant;
25818     }
25819     break;
25820   case 'G':
25821   case 'C':
25822     if (isa<ConstantFP>(CallOperandVal)) {
25823       weight = CW_Constant;
25824     }
25825     break;
25826   case 'e':
25827     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25828       if ((C->getSExtValue() >= -0x80000000LL) &&
25829           (C->getSExtValue() <= 0x7fffffffLL))
25830         weight = CW_Constant;
25831     }
25832     break;
25833   case 'Z':
25834     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25835       if (C->getZExtValue() <= 0xffffffff)
25836         weight = CW_Constant;
25837     }
25838     break;
25839   }
25840   return weight;
25841 }
25842
25843 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25844 /// with another that has more specific requirements based on the type of the
25845 /// corresponding operand.
25846 const char *X86TargetLowering::
25847 LowerXConstraint(EVT ConstraintVT) const {
25848   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25849   // 'f' like normal targets.
25850   if (ConstraintVT.isFloatingPoint()) {
25851     if (Subtarget->hasSSE2())
25852       return "Y";
25853     if (Subtarget->hasSSE1())
25854       return "x";
25855   }
25856
25857   return TargetLowering::LowerXConstraint(ConstraintVT);
25858 }
25859
25860 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25861 /// vector.  If it is invalid, don't add anything to Ops.
25862 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25863                                                      std::string &Constraint,
25864                                                      std::vector<SDValue>&Ops,
25865                                                      SelectionDAG &DAG) const {
25866   SDValue Result;
25867
25868   // Only support length 1 constraints for now.
25869   if (Constraint.length() > 1) return;
25870
25871   char ConstraintLetter = Constraint[0];
25872   switch (ConstraintLetter) {
25873   default: break;
25874   case 'I':
25875     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25876       if (C->getZExtValue() <= 31) {
25877         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25878                                        Op.getValueType());
25879         break;
25880       }
25881     }
25882     return;
25883   case 'J':
25884     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25885       if (C->getZExtValue() <= 63) {
25886         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25887                                        Op.getValueType());
25888         break;
25889       }
25890     }
25891     return;
25892   case 'K':
25893     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25894       if (isInt<8>(C->getSExtValue())) {
25895         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25896                                        Op.getValueType());
25897         break;
25898       }
25899     }
25900     return;
25901   case 'L':
25902     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25903       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25904           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25905         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25906                                        Op.getValueType());
25907         break;
25908       }
25909     }
25910     return;
25911   case 'M':
25912     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25913       if (C->getZExtValue() <= 3) {
25914         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25915                                        Op.getValueType());
25916         break;
25917       }
25918     }
25919     return;
25920   case 'N':
25921     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25922       if (C->getZExtValue() <= 255) {
25923         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25924                                        Op.getValueType());
25925         break;
25926       }
25927     }
25928     return;
25929   case 'O':
25930     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25931       if (C->getZExtValue() <= 127) {
25932         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25933                                        Op.getValueType());
25934         break;
25935       }
25936     }
25937     return;
25938   case 'e': {
25939     // 32-bit signed value
25940     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25941       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25942                                            C->getSExtValue())) {
25943         // Widen to 64 bits here to get it sign extended.
25944         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25945         break;
25946       }
25947     // FIXME gcc accepts some relocatable values here too, but only in certain
25948     // memory models; it's complicated.
25949     }
25950     return;
25951   }
25952   case 'Z': {
25953     // 32-bit unsigned value
25954     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25955       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25956                                            C->getZExtValue())) {
25957         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25958                                        Op.getValueType());
25959         break;
25960       }
25961     }
25962     // FIXME gcc accepts some relocatable values here too, but only in certain
25963     // memory models; it's complicated.
25964     return;
25965   }
25966   case 'i': {
25967     // Literal immediates are always ok.
25968     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25969       // Widen to 64 bits here to get it sign extended.
25970       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25971       break;
25972     }
25973
25974     // In any sort of PIC mode addresses need to be computed at runtime by
25975     // adding in a register or some sort of table lookup.  These can't
25976     // be used as immediates.
25977     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25978       return;
25979
25980     // If we are in non-pic codegen mode, we allow the address of a global (with
25981     // an optional displacement) to be used with 'i'.
25982     GlobalAddressSDNode *GA = nullptr;
25983     int64_t Offset = 0;
25984
25985     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25986     while (1) {
25987       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25988         Offset += GA->getOffset();
25989         break;
25990       } else if (Op.getOpcode() == ISD::ADD) {
25991         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25992           Offset += C->getZExtValue();
25993           Op = Op.getOperand(0);
25994           continue;
25995         }
25996       } else if (Op.getOpcode() == ISD::SUB) {
25997         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25998           Offset += -C->getZExtValue();
25999           Op = Op.getOperand(0);
26000           continue;
26001         }
26002       }
26003
26004       // Otherwise, this isn't something we can handle, reject it.
26005       return;
26006     }
26007
26008     const GlobalValue *GV = GA->getGlobal();
26009     // If we require an extra load to get this address, as in PIC mode, we
26010     // can't accept it.
26011     if (isGlobalStubReference(
26012             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
26013       return;
26014
26015     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
26016                                         GA->getValueType(0), Offset);
26017     break;
26018   }
26019   }
26020
26021   if (Result.getNode()) {
26022     Ops.push_back(Result);
26023     return;
26024   }
26025   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
26026 }
26027
26028 std::pair<unsigned, const TargetRegisterClass *>
26029 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
26030                                                 StringRef Constraint,
26031                                                 MVT VT) const {
26032   // First, see if this is a constraint that directly corresponds to an LLVM
26033   // register class.
26034   if (Constraint.size() == 1) {
26035     // GCC Constraint Letters
26036     switch (Constraint[0]) {
26037     default: break;
26038       // TODO: Slight differences here in allocation order and leaving
26039       // RIP in the class. Do they matter any more here than they do
26040       // in the normal allocation?
26041     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26042       if (Subtarget->is64Bit()) {
26043         if (VT == MVT::i32 || VT == MVT::f32)
26044           return std::make_pair(0U, &X86::GR32RegClass);
26045         if (VT == MVT::i16)
26046           return std::make_pair(0U, &X86::GR16RegClass);
26047         if (VT == MVT::i8 || VT == MVT::i1)
26048           return std::make_pair(0U, &X86::GR8RegClass);
26049         if (VT == MVT::i64 || VT == MVT::f64)
26050           return std::make_pair(0U, &X86::GR64RegClass);
26051         break;
26052       }
26053       // 32-bit fallthrough
26054     case 'Q':   // Q_REGS
26055       if (VT == MVT::i32 || VT == MVT::f32)
26056         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26057       if (VT == MVT::i16)
26058         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26059       if (VT == MVT::i8 || VT == MVT::i1)
26060         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26061       if (VT == MVT::i64)
26062         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26063       break;
26064     case 'r':   // GENERAL_REGS
26065     case 'l':   // INDEX_REGS
26066       if (VT == MVT::i8 || VT == MVT::i1)
26067         return std::make_pair(0U, &X86::GR8RegClass);
26068       if (VT == MVT::i16)
26069         return std::make_pair(0U, &X86::GR16RegClass);
26070       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26071         return std::make_pair(0U, &X86::GR32RegClass);
26072       return std::make_pair(0U, &X86::GR64RegClass);
26073     case 'R':   // LEGACY_REGS
26074       if (VT == MVT::i8 || VT == MVT::i1)
26075         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26076       if (VT == MVT::i16)
26077         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26078       if (VT == MVT::i32 || !Subtarget->is64Bit())
26079         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26080       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26081     case 'f':  // FP Stack registers.
26082       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26083       // value to the correct fpstack register class.
26084       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26085         return std::make_pair(0U, &X86::RFP32RegClass);
26086       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26087         return std::make_pair(0U, &X86::RFP64RegClass);
26088       return std::make_pair(0U, &X86::RFP80RegClass);
26089     case 'y':   // MMX_REGS if MMX allowed.
26090       if (!Subtarget->hasMMX()) break;
26091       return std::make_pair(0U, &X86::VR64RegClass);
26092     case 'Y':   // SSE_REGS if SSE2 allowed
26093       if (!Subtarget->hasSSE2()) break;
26094       // FALL THROUGH.
26095     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26096       if (!Subtarget->hasSSE1()) break;
26097
26098       switch (VT.SimpleTy) {
26099       default: break;
26100       // Scalar SSE types.
26101       case MVT::f32:
26102       case MVT::i32:
26103         return std::make_pair(0U, &X86::FR32RegClass);
26104       case MVT::f64:
26105       case MVT::i64:
26106         return std::make_pair(0U, &X86::FR64RegClass);
26107       // Vector types.
26108       case MVT::v16i8:
26109       case MVT::v8i16:
26110       case MVT::v4i32:
26111       case MVT::v2i64:
26112       case MVT::v4f32:
26113       case MVT::v2f64:
26114         return std::make_pair(0U, &X86::VR128RegClass);
26115       // AVX types.
26116       case MVT::v32i8:
26117       case MVT::v16i16:
26118       case MVT::v8i32:
26119       case MVT::v4i64:
26120       case MVT::v8f32:
26121       case MVT::v4f64:
26122         return std::make_pair(0U, &X86::VR256RegClass);
26123       case MVT::v8f64:
26124       case MVT::v16f32:
26125       case MVT::v16i32:
26126       case MVT::v8i64:
26127         return std::make_pair(0U, &X86::VR512RegClass);
26128       }
26129       break;
26130     }
26131   }
26132
26133   // Use the default implementation in TargetLowering to convert the register
26134   // constraint into a member of a register class.
26135   std::pair<unsigned, const TargetRegisterClass*> Res;
26136   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26137
26138   // Not found as a standard register?
26139   if (!Res.second) {
26140     // Map st(0) -> st(7) -> ST0
26141     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26142         tolower(Constraint[1]) == 's' &&
26143         tolower(Constraint[2]) == 't' &&
26144         Constraint[3] == '(' &&
26145         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26146         Constraint[5] == ')' &&
26147         Constraint[6] == '}') {
26148
26149       Res.first = X86::FP0+Constraint[4]-'0';
26150       Res.second = &X86::RFP80RegClass;
26151       return Res;
26152     }
26153
26154     // GCC allows "st(0)" to be called just plain "st".
26155     if (StringRef("{st}").equals_lower(Constraint)) {
26156       Res.first = X86::FP0;
26157       Res.second = &X86::RFP80RegClass;
26158       return Res;
26159     }
26160
26161     // flags -> EFLAGS
26162     if (StringRef("{flags}").equals_lower(Constraint)) {
26163       Res.first = X86::EFLAGS;
26164       Res.second = &X86::CCRRegClass;
26165       return Res;
26166     }
26167
26168     // 'A' means EAX + EDX.
26169     if (Constraint == "A") {
26170       Res.first = X86::EAX;
26171       Res.second = &X86::GR32_ADRegClass;
26172       return Res;
26173     }
26174     return Res;
26175   }
26176
26177   // Otherwise, check to see if this is a register class of the wrong value
26178   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26179   // turn into {ax},{dx}.
26180   // MVT::Other is used to specify clobber names.
26181   if (Res.second->hasType(VT) || VT == MVT::Other)
26182     return Res;   // Correct type already, nothing to do.
26183
26184   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26185   // return "eax". This should even work for things like getting 64bit integer
26186   // registers when given an f64 type.
26187   const TargetRegisterClass *Class = Res.second;
26188   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26189       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26190     unsigned Size = VT.getSizeInBits();
26191     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26192                                   : Size == 16 ? MVT::i16
26193                                   : Size == 32 ? MVT::i32
26194                                   : Size == 64 ? MVT::i64
26195                                   : MVT::Other;
26196     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26197     if (DestReg > 0) {
26198       Res.first = DestReg;
26199       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26200                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26201                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26202                  : &X86::GR64RegClass;
26203       assert(Res.second->contains(Res.first) && "Register in register class");
26204     } else {
26205       // No register found/type mismatch.
26206       Res.first = 0;
26207       Res.second = nullptr;
26208     }
26209   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26210              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26211              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26212              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26213              Class == &X86::VR512RegClass) {
26214     // Handle references to XMM physical registers that got mapped into the
26215     // wrong class.  This can happen with constraints like {xmm0} where the
26216     // target independent register mapper will just pick the first match it can
26217     // find, ignoring the required type.
26218
26219     if (VT == MVT::f32 || VT == MVT::i32)
26220       Res.second = &X86::FR32RegClass;
26221     else if (VT == MVT::f64 || VT == MVT::i64)
26222       Res.second = &X86::FR64RegClass;
26223     else if (X86::VR128RegClass.hasType(VT))
26224       Res.second = &X86::VR128RegClass;
26225     else if (X86::VR256RegClass.hasType(VT))
26226       Res.second = &X86::VR256RegClass;
26227     else if (X86::VR512RegClass.hasType(VT))
26228       Res.second = &X86::VR512RegClass;
26229     else {
26230       // Type mismatch and not a clobber: Return an error;
26231       Res.first = 0;
26232       Res.second = nullptr;
26233     }
26234   }
26235
26236   return Res;
26237 }
26238
26239 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26240                                             const AddrMode &AM, Type *Ty,
26241                                             unsigned AS) const {
26242   // Scaling factors are not free at all.
26243   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26244   // will take 2 allocations in the out of order engine instead of 1
26245   // for plain addressing mode, i.e. inst (reg1).
26246   // E.g.,
26247   // vaddps (%rsi,%drx), %ymm0, %ymm1
26248   // Requires two allocations (one for the load, one for the computation)
26249   // whereas:
26250   // vaddps (%rsi), %ymm0, %ymm1
26251   // Requires just 1 allocation, i.e., freeing allocations for other operations
26252   // and having less micro operations to execute.
26253   //
26254   // For some X86 architectures, this is even worse because for instance for
26255   // stores, the complex addressing mode forces the instruction to use the
26256   // "load" ports instead of the dedicated "store" port.
26257   // E.g., on Haswell:
26258   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26259   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26260   if (isLegalAddressingMode(DL, AM, Ty, AS))
26261     // Scale represents reg2 * scale, thus account for 1
26262     // as soon as we use a second register.
26263     return AM.Scale != 0;
26264   return -1;
26265 }
26266
26267 bool X86TargetLowering::isTargetFTOL() const {
26268   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26269 }