[X86][SSE] Vectorized i64 uniform constant SRA shifts
[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 = 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(), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1357     }
1358     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1359     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1360     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1361     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1362     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1363     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1364     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1370     if (Subtarget->hasDQI()) {
1371       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1372       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1373     }
1374     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1375     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1376     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1377     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1379     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1380     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1381     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1382     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1383     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1384
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1407
1408     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1409     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1410     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1411     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1412     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1413     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1414     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1415     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1416
1417     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1424
1425     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1426     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1427
1428     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1429     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1430
1431     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1436     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1437     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1438     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1439     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1440
1441     if (Subtarget->hasCDI()) {
1442       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1443       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1444     }
1445     if (Subtarget->hasDQI()) {
1446       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1447       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1448       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1449     }
1450     // Custom lower several nodes.
1451     for (MVT VT : MVT::vector_valuetypes()) {
1452       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453       if (EltSize == 1) {
1454         setOperationAction(ISD::AND, VT, Legal);
1455         setOperationAction(ISD::OR,  VT, Legal);
1456         setOperationAction(ISD::XOR,  VT, Legal);
1457       }
1458       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459         setOperationAction(ISD::MGATHER,  VT, Custom);
1460         setOperationAction(ISD::MSCATTER, VT, Custom);
1461       }
1462       // Extract subvector is special because the value type
1463       // (result) is 256/128-bit but the source is 512-bit wide.
1464       if (VT.is128BitVector() || VT.is256BitVector()) {
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1466       }
1467       if (VT.getVectorElementType() == MVT::i1)
1468         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1469
1470       // Do not attempt to custom lower other non-512-bit vectors
1471       if (!VT.is512BitVector())
1472         continue;
1473
1474       if (EltSize >= 32) {
1475         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1476         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1477         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1478         setOperationAction(ISD::VSELECT,             VT, Legal);
1479         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1480         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1481         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1482         setOperationAction(ISD::MLOAD,               VT, Legal);
1483         setOperationAction(ISD::MSTORE,              VT, Legal);
1484       }
1485     }
1486     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487       MVT VT = (MVT::SimpleValueType)i;
1488
1489       // Do not attempt to promote non-512-bit vectors.
1490       if (!VT.is512BitVector())
1491         continue;
1492
1493       setOperationAction(ISD::SELECT, VT, Promote);
1494       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1495     }
1496   }// has  AVX-512
1497
1498   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1501
1502     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1503     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1504
1505     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1506     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1507     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1508     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1509     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1510     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1511     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1512     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1513     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1514     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1515     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1516     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1517     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1518     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1519     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1520     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1521     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1522     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1525     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1526     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1527     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1528     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1529     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1530     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1531     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1532     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1533     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1534
1535     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1536     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1539     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1540     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1541     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1542     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1543
1544     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545       const MVT VT = (MVT::SimpleValueType)i;
1546
1547       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1548
1549       // Do not attempt to promote non-512-bit vectors.
1550       if (!VT.is512BitVector())
1551         continue;
1552
1553       if (EltSize < 32) {
1554         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1555         setOperationAction(ISD::VSELECT,             VT, Legal);
1556       }
1557     }
1558   }
1559
1560   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1562     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1563
1564     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1565     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1566     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1567     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1568     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1569     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1570     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1571     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1572     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1573     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1574
1575     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1576     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1577     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1578     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1579     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1580     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1581     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1582     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1583
1584     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1585     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1586     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1587     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1588     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1589     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1590     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1591     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1592   }
1593
1594   // We want to custom lower some of our intrinsics.
1595   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598   if (!Subtarget->is64Bit())
1599     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1600
1601   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602   // handle type legalization for these operations here.
1603   //
1604   // FIXME: We really should do custom legalization for addition and
1605   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1606   // than generic legalization for 64-bit multiplication-with-overflow, though.
1607   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608     // Add/Sub/Mul with overflow operations are custom lowered.
1609     MVT VT = IntVTs[i];
1610     setOperationAction(ISD::SADDO, VT, Custom);
1611     setOperationAction(ISD::UADDO, VT, Custom);
1612     setOperationAction(ISD::SSUBO, VT, Custom);
1613     setOperationAction(ISD::USUBO, VT, Custom);
1614     setOperationAction(ISD::SMULO, VT, Custom);
1615     setOperationAction(ISD::UMULO, VT, Custom);
1616   }
1617
1618
1619   if (!Subtarget->is64Bit()) {
1620     // These libcalls are not available in 32-bit.
1621     setLibcallName(RTLIB::SHL_I128, nullptr);
1622     setLibcallName(RTLIB::SRL_I128, nullptr);
1623     setLibcallName(RTLIB::SRA_I128, nullptr);
1624   }
1625
1626   // Combine sin / cos into one node or libcall if possible.
1627   if (Subtarget->hasSinCos()) {
1628     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630     if (Subtarget->isTargetDarwin()) {
1631       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1635     }
1636   }
1637
1638   if (Subtarget->isTargetWin64()) {
1639     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::SREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UREM, MVT::i128, Custom);
1643     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1645   }
1646
1647   // We have target-specific dag combine patterns for the following nodes:
1648   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650   setTargetDAGCombine(ISD::BITCAST);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::MLOAD);
1665   setTargetDAGCombine(ISD::STORE);
1666   setTargetDAGCombine(ISD::MSTORE);
1667   setTargetDAGCombine(ISD::ZERO_EXTEND);
1668   setTargetDAGCombine(ISD::ANY_EXTEND);
1669   setTargetDAGCombine(ISD::SIGN_EXTEND);
1670   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671   setTargetDAGCombine(ISD::SINT_TO_FP);
1672   setTargetDAGCombine(ISD::UINT_TO_FP);
1673   setTargetDAGCombine(ISD::SETCC);
1674   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675   setTargetDAGCombine(ISD::BUILD_VECTOR);
1676   setTargetDAGCombine(ISD::MUL);
1677   setTargetDAGCombine(ISD::XOR);
1678
1679   computeRegisterProperties(Subtarget->getRegisterInfo());
1680
1681   // On Darwin, -Os means optimize for size without hurting performance,
1682   // do not reduce the limit.
1683   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689   setPrefLoopAlignment(4); // 2^4 bytes.
1690
1691   // Predictable cmov don't hurt on atom because it's in-order.
1692   PredictableSelectIsExpensive = !Subtarget->isAtom();
1693   EnableExtLdPromotion = true;
1694   setPrefFunctionAlignment(4); // 2^4 bytes.
1695
1696   verifyIntrinsicTables();
1697 }
1698
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1702 }
1703
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706   if (ExperimentalVectorWideningLegalization &&
1707       VT.getVectorNumElements() != 1 &&
1708       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709     return TypeWidenVector;
1710
1711   return TargetLoweringBase::getPreferredVectorAction(VT);
1712 }
1713
1714 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1715   if (!VT.isVector())
1716     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1717
1718   const unsigned NumElts = VT.getVectorNumElements();
1719   const EVT EltVT = VT.getVectorElementType();
1720   if (VT.is512BitVector()) {
1721     if (Subtarget->hasAVX512())
1722       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1723           EltVT == MVT::f32 || EltVT == MVT::f64)
1724         switch(NumElts) {
1725         case  8: return MVT::v8i1;
1726         case 16: return MVT::v16i1;
1727       }
1728     if (Subtarget->hasBWI())
1729       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1730         switch(NumElts) {
1731         case 32: return MVT::v32i1;
1732         case 64: return MVT::v64i1;
1733       }
1734   }
1735
1736   if (VT.is256BitVector() || VT.is128BitVector()) {
1737     if (Subtarget->hasVLX())
1738       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1739           EltVT == MVT::f32 || EltVT == MVT::f64)
1740         switch(NumElts) {
1741         case 2: return MVT::v2i1;
1742         case 4: return MVT::v4i1;
1743         case 8: return MVT::v8i1;
1744       }
1745     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1746       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1747         switch(NumElts) {
1748         case  8: return MVT::v8i1;
1749         case 16: return MVT::v16i1;
1750         case 32: return MVT::v32i1;
1751       }
1752   }
1753
1754   return VT.changeVectorElementTypeToInteger();
1755 }
1756
1757 /// Helper for getByValTypeAlignment to determine
1758 /// the desired ByVal argument alignment.
1759 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1760   if (MaxAlign == 16)
1761     return;
1762   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1763     if (VTy->getBitWidth() == 128)
1764       MaxAlign = 16;
1765   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1766     unsigned EltAlign = 0;
1767     getMaxByValAlign(ATy->getElementType(), EltAlign);
1768     if (EltAlign > MaxAlign)
1769       MaxAlign = EltAlign;
1770   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1771     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1772       unsigned EltAlign = 0;
1773       getMaxByValAlign(STy->getElementType(i), EltAlign);
1774       if (EltAlign > MaxAlign)
1775         MaxAlign = EltAlign;
1776       if (MaxAlign == 16)
1777         break;
1778     }
1779   }
1780 }
1781
1782 /// Return the desired alignment for ByVal aggregate
1783 /// function arguments in the caller parameter area. For X86, aggregates
1784 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1785 /// are at 4-byte boundaries.
1786 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1787   if (Subtarget->is64Bit()) {
1788     // Max of 8 and alignment of type.
1789     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1790     if (TyAlign > 8)
1791       return TyAlign;
1792     return 8;
1793   }
1794
1795   unsigned Align = 4;
1796   if (Subtarget->hasSSE1())
1797     getMaxByValAlign(Ty, Align);
1798   return Align;
1799 }
1800
1801 /// Returns the target specific optimal type for load
1802 /// and store operations as a result of memset, memcpy, and memmove
1803 /// lowering. If DstAlign is zero that means it's safe to destination
1804 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1805 /// means there isn't a need to check it against alignment requirement,
1806 /// probably because the source does not need to be loaded. If 'IsMemset' is
1807 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1808 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1809 /// source is constant so it does not need to be loaded.
1810 /// It returns EVT::Other if the type should be determined using generic
1811 /// target-independent logic.
1812 EVT
1813 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1814                                        unsigned DstAlign, unsigned SrcAlign,
1815                                        bool IsMemset, bool ZeroMemset,
1816                                        bool MemcpyStrSrc,
1817                                        MachineFunction &MF) const {
1818   const Function *F = MF.getFunction();
1819   if ((!IsMemset || ZeroMemset) &&
1820       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1821     if (Size >= 16 &&
1822         (Subtarget->isUnalignedMemAccessFast() ||
1823          ((DstAlign == 0 || DstAlign >= 16) &&
1824           (SrcAlign == 0 || SrcAlign >= 16)))) {
1825       if (Size >= 32) {
1826         if (Subtarget->hasInt256())
1827           return MVT::v8i32;
1828         if (Subtarget->hasFp256())
1829           return MVT::v8f32;
1830       }
1831       if (Subtarget->hasSSE2())
1832         return MVT::v4i32;
1833       if (Subtarget->hasSSE1())
1834         return MVT::v4f32;
1835     } else if (!MemcpyStrSrc && Size >= 8 &&
1836                !Subtarget->is64Bit() &&
1837                Subtarget->hasSSE2()) {
1838       // Do not use f64 to lower memcpy if source is string constant. It's
1839       // better to use i32 to avoid the loads.
1840       return MVT::f64;
1841     }
1842   }
1843   if (Subtarget->is64Bit() && Size >= 8)
1844     return MVT::i64;
1845   return MVT::i32;
1846 }
1847
1848 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1849   if (VT == MVT::f32)
1850     return X86ScalarSSEf32;
1851   else if (VT == MVT::f64)
1852     return X86ScalarSSEf64;
1853   return true;
1854 }
1855
1856 bool
1857 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1858                                                   unsigned,
1859                                                   unsigned,
1860                                                   bool *Fast) const {
1861   if (Fast)
1862     *Fast = Subtarget->isUnalignedMemAccessFast();
1863   return true;
1864 }
1865
1866 /// Return the entry encoding for a jump table in the
1867 /// current function.  The returned value is a member of the
1868 /// MachineJumpTableInfo::JTEntryKind enum.
1869 unsigned X86TargetLowering::getJumpTableEncoding() const {
1870   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1871   // symbol.
1872   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1873       Subtarget->isPICStyleGOT())
1874     return MachineJumpTableInfo::EK_Custom32;
1875
1876   // Otherwise, use the normal jump table encoding heuristics.
1877   return TargetLowering::getJumpTableEncoding();
1878 }
1879
1880 bool X86TargetLowering::useSoftFloat() const {
1881   return Subtarget->useSoftFloat();
1882 }
1883
1884 const MCExpr *
1885 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1886                                              const MachineBasicBlock *MBB,
1887                                              unsigned uid,MCContext &Ctx) const{
1888   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1889          Subtarget->isPICStyleGOT());
1890   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1891   // entries.
1892   return MCSymbolRefExpr::create(MBB->getSymbol(),
1893                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1894 }
1895
1896 /// Returns relocation base for the given PIC jumptable.
1897 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1898                                                     SelectionDAG &DAG) const {
1899   if (!Subtarget->is64Bit())
1900     // This doesn't have SDLoc associated with it, but is not really the
1901     // same as a Register.
1902     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1903   return Table;
1904 }
1905
1906 /// This returns the relocation base for the given PIC jumptable,
1907 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1908 const MCExpr *X86TargetLowering::
1909 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1910                              MCContext &Ctx) const {
1911   // X86-64 uses RIP relative addressing based on the jump table label.
1912   if (Subtarget->isPICStyleRIPRel())
1913     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1914
1915   // Otherwise, the reference is relative to the PIC base.
1916   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1917 }
1918
1919 std::pair<const TargetRegisterClass *, uint8_t>
1920 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1921                                            MVT VT) const {
1922   const TargetRegisterClass *RRC = nullptr;
1923   uint8_t Cost = 1;
1924   switch (VT.SimpleTy) {
1925   default:
1926     return TargetLowering::findRepresentativeClass(TRI, VT);
1927   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1928     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1929     break;
1930   case MVT::x86mmx:
1931     RRC = &X86::VR64RegClass;
1932     break;
1933   case MVT::f32: case MVT::f64:
1934   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1935   case MVT::v4f32: case MVT::v2f64:
1936   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1937   case MVT::v4f64:
1938     RRC = &X86::VR128RegClass;
1939     break;
1940   }
1941   return std::make_pair(RRC, Cost);
1942 }
1943
1944 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1945                                                unsigned &Offset) const {
1946   if (!Subtarget->isTargetLinux())
1947     return false;
1948
1949   if (Subtarget->is64Bit()) {
1950     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1951     Offset = 0x28;
1952     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1953       AddressSpace = 256;
1954     else
1955       AddressSpace = 257;
1956   } else {
1957     // %gs:0x14 on i386
1958     Offset = 0x14;
1959     AddressSpace = 256;
1960   }
1961   return true;
1962 }
1963
1964 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1965                                             unsigned DestAS) const {
1966   assert(SrcAS != DestAS && "Expected different address spaces!");
1967
1968   return SrcAS < 256 && DestAS < 256;
1969 }
1970
1971 //===----------------------------------------------------------------------===//
1972 //               Return Value Calling Convention Implementation
1973 //===----------------------------------------------------------------------===//
1974
1975 #include "X86GenCallingConv.inc"
1976
1977 bool
1978 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1979                                   MachineFunction &MF, bool isVarArg,
1980                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1981                         LLVMContext &Context) const {
1982   SmallVector<CCValAssign, 16> RVLocs;
1983   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1984   return CCInfo.CheckReturn(Outs, RetCC_X86);
1985 }
1986
1987 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1988   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1989   return ScratchRegs;
1990 }
1991
1992 SDValue
1993 X86TargetLowering::LowerReturn(SDValue Chain,
1994                                CallingConv::ID CallConv, bool isVarArg,
1995                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1996                                const SmallVectorImpl<SDValue> &OutVals,
1997                                SDLoc dl, SelectionDAG &DAG) const {
1998   MachineFunction &MF = DAG.getMachineFunction();
1999   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2000
2001   SmallVector<CCValAssign, 16> RVLocs;
2002   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2003   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2004
2005   SDValue Flag;
2006   SmallVector<SDValue, 6> RetOps;
2007   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2008   // Operand #1 = Bytes To Pop
2009   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2010                    MVT::i16));
2011
2012   // Copy the result values into the output registers.
2013   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2014     CCValAssign &VA = RVLocs[i];
2015     assert(VA.isRegLoc() && "Can only return in registers!");
2016     SDValue ValToCopy = OutVals[i];
2017     EVT ValVT = ValToCopy.getValueType();
2018
2019     // Promote values to the appropriate types.
2020     if (VA.getLocInfo() == CCValAssign::SExt)
2021       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022     else if (VA.getLocInfo() == CCValAssign::ZExt)
2023       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2024     else if (VA.getLocInfo() == CCValAssign::AExt) {
2025       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2026         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027       else
2028         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2029     }
2030     else if (VA.getLocInfo() == CCValAssign::BCvt)
2031       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2032
2033     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2034            "Unexpected FP-extend for return value.");
2035
2036     // If this is x86-64, and we disabled SSE, we can't return FP values,
2037     // or SSE or MMX vectors.
2038     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2039          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2040           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2041       report_fatal_error("SSE register return with SSE disabled");
2042     }
2043     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2044     // llvm-gcc has never done it right and no one has noticed, so this
2045     // should be OK for now.
2046     if (ValVT == MVT::f64 &&
2047         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2048       report_fatal_error("SSE2 register return with SSE2 disabled");
2049
2050     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2051     // the RET instruction and handled by the FP Stackifier.
2052     if (VA.getLocReg() == X86::FP0 ||
2053         VA.getLocReg() == X86::FP1) {
2054       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2055       // change the value to the FP stack register class.
2056       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2057         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2058       RetOps.push_back(ValToCopy);
2059       // Don't emit a copytoreg.
2060       continue;
2061     }
2062
2063     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2064     // which is returned in RAX / RDX.
2065     if (Subtarget->is64Bit()) {
2066       if (ValVT == MVT::x86mmx) {
2067         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2068           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2069           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2070                                   ValToCopy);
2071           // If we don't have SSE2 available, convert to v4f32 so the generated
2072           // register is legal.
2073           if (!Subtarget->hasSSE2())
2074             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2075         }
2076       }
2077     }
2078
2079     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2080     Flag = Chain.getValue(1);
2081     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2082   }
2083
2084   // All x86 ABIs require that for returning structs by value we copy
2085   // the sret argument into %rax/%eax (depending on ABI) for the return.
2086   // We saved the argument into a virtual register in the entry block,
2087   // so now we copy the value out and into %rax/%eax.
2088   //
2089   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2090   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2091   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2092   // either case FuncInfo->setSRetReturnReg() will have been called.
2093   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2094     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2095
2096     unsigned RetValReg
2097         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2098           X86::RAX : X86::EAX;
2099     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2100     Flag = Chain.getValue(1);
2101
2102     // RAX/EAX now acts like a return value.
2103     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2104   }
2105
2106   RetOps[0] = Chain;  // Update chain.
2107
2108   // Add the flag if we have it.
2109   if (Flag.getNode())
2110     RetOps.push_back(Flag);
2111
2112   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2113 }
2114
2115 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2116   if (N->getNumValues() != 1)
2117     return false;
2118   if (!N->hasNUsesOfValue(1, 0))
2119     return false;
2120
2121   SDValue TCChain = Chain;
2122   SDNode *Copy = *N->use_begin();
2123   if (Copy->getOpcode() == ISD::CopyToReg) {
2124     // If the copy has a glue operand, we conservatively assume it isn't safe to
2125     // perform a tail call.
2126     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2127       return false;
2128     TCChain = Copy->getOperand(0);
2129   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2130     return false;
2131
2132   bool HasRet = false;
2133   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2134        UI != UE; ++UI) {
2135     if (UI->getOpcode() != X86ISD::RET_FLAG)
2136       return false;
2137     // If we are returning more than one value, we can definitely
2138     // not make a tail call see PR19530
2139     if (UI->getNumOperands() > 4)
2140       return false;
2141     if (UI->getNumOperands() == 4 &&
2142         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2143       return false;
2144     HasRet = true;
2145   }
2146
2147   if (!HasRet)
2148     return false;
2149
2150   Chain = TCChain;
2151   return true;
2152 }
2153
2154 EVT
2155 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2156                                             ISD::NodeType ExtendKind) const {
2157   MVT ReturnMVT;
2158   // TODO: Is this also valid on 32-bit?
2159   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2160     ReturnMVT = MVT::i8;
2161   else
2162     ReturnMVT = MVT::i32;
2163
2164   EVT MinVT = getRegisterType(Context, ReturnMVT);
2165   return VT.bitsLT(MinVT) ? MinVT : VT;
2166 }
2167
2168 /// Lower the result values of a call into the
2169 /// appropriate copies out of appropriate physical registers.
2170 ///
2171 SDValue
2172 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2173                                    CallingConv::ID CallConv, bool isVarArg,
2174                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2175                                    SDLoc dl, SelectionDAG &DAG,
2176                                    SmallVectorImpl<SDValue> &InVals) const {
2177
2178   // Assign locations to each value returned by this call.
2179   SmallVector<CCValAssign, 16> RVLocs;
2180   bool Is64Bit = Subtarget->is64Bit();
2181   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2182                  *DAG.getContext());
2183   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2184
2185   // Copy all of the result registers out of their specified physreg.
2186   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2187     CCValAssign &VA = RVLocs[i];
2188     EVT CopyVT = VA.getLocVT();
2189
2190     // If this is x86-64, and we disabled SSE, we can't return FP values
2191     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2192         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2193       report_fatal_error("SSE register return with SSE disabled");
2194     }
2195
2196     // If we prefer to use the value in xmm registers, copy it out as f80 and
2197     // use a truncate to move it from fp stack reg to xmm reg.
2198     bool RoundAfterCopy = false;
2199     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2200         isScalarFPTypeInSSEReg(VA.getValVT())) {
2201       CopyVT = MVT::f80;
2202       RoundAfterCopy = (CopyVT != VA.getLocVT());
2203     }
2204
2205     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2206                                CopyVT, InFlag).getValue(1);
2207     SDValue Val = Chain.getValue(0);
2208
2209     if (RoundAfterCopy)
2210       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2211                         // This truncation won't change the value.
2212                         DAG.getIntPtrConstant(1, dl));
2213
2214     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2215       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2216
2217     InFlag = Chain.getValue(2);
2218     InVals.push_back(Val);
2219   }
2220
2221   return Chain;
2222 }
2223
2224 //===----------------------------------------------------------------------===//
2225 //                C & StdCall & Fast Calling Convention implementation
2226 //===----------------------------------------------------------------------===//
2227 //  StdCall calling convention seems to be standard for many Windows' API
2228 //  routines and around. It differs from C calling convention just a little:
2229 //  callee should clean up the stack, not caller. Symbols should be also
2230 //  decorated in some fancy way :) It doesn't support any vector arguments.
2231 //  For info on fast calling convention see Fast Calling Convention (tail call)
2232 //  implementation LowerX86_32FastCCCallTo.
2233
2234 /// CallIsStructReturn - Determines whether a call uses struct return
2235 /// semantics.
2236 enum StructReturnType {
2237   NotStructReturn,
2238   RegStructReturn,
2239   StackStructReturn
2240 };
2241 static StructReturnType
2242 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2243   if (Outs.empty())
2244     return NotStructReturn;
2245
2246   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2247   if (!Flags.isSRet())
2248     return NotStructReturn;
2249   if (Flags.isInReg())
2250     return RegStructReturn;
2251   return StackStructReturn;
2252 }
2253
2254 /// Determines whether a function uses struct return semantics.
2255 static StructReturnType
2256 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2257   if (Ins.empty())
2258     return NotStructReturn;
2259
2260   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2261   if (!Flags.isSRet())
2262     return NotStructReturn;
2263   if (Flags.isInReg())
2264     return RegStructReturn;
2265   return StackStructReturn;
2266 }
2267
2268 /// Make a copy of an aggregate at address specified by "Src" to address
2269 /// "Dst" with size and alignment information specified by the specific
2270 /// parameter attribute. The copy will be passed as a byval function parameter.
2271 static SDValue
2272 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2273                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2274                           SDLoc dl) {
2275   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2276
2277   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2278                        /*isVolatile*/false, /*AlwaysInline=*/true,
2279                        /*isTailCall*/false,
2280                        MachinePointerInfo(), MachinePointerInfo());
2281 }
2282
2283 /// Return true if the calling convention is one that
2284 /// supports tail call optimization.
2285 static bool IsTailCallConvention(CallingConv::ID CC) {
2286   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2287           CC == CallingConv::HiPE);
2288 }
2289
2290 /// \brief Return true if the calling convention is a C calling convention.
2291 static bool IsCCallConvention(CallingConv::ID CC) {
2292   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2293           CC == CallingConv::X86_64_SysV);
2294 }
2295
2296 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2297   auto Attr =
2298       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2299   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2300     return false;
2301
2302   CallSite CS(CI);
2303   CallingConv::ID CalleeCC = CS.getCallingConv();
2304   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2305     return false;
2306
2307   return true;
2308 }
2309
2310 /// Return true if the function is being made into
2311 /// a tailcall target by changing its ABI.
2312 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2313                                    bool GuaranteedTailCallOpt) {
2314   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2315 }
2316
2317 SDValue
2318 X86TargetLowering::LowerMemArgument(SDValue Chain,
2319                                     CallingConv::ID CallConv,
2320                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2321                                     SDLoc dl, SelectionDAG &DAG,
2322                                     const CCValAssign &VA,
2323                                     MachineFrameInfo *MFI,
2324                                     unsigned i) const {
2325   // Create the nodes corresponding to a load from this parameter slot.
2326   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2327   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2328       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2329   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2330   EVT ValVT;
2331
2332   // If value is passed by pointer we have address passed instead of the value
2333   // itself.
2334   bool ExtendedInMem = VA.isExtInLoc() &&
2335     VA.getValVT().getScalarType() == MVT::i1;
2336
2337   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2338     ValVT = VA.getLocVT();
2339   else
2340     ValVT = VA.getValVT();
2341
2342   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2343   // changed with more analysis.
2344   // In case of tail call optimization mark all arguments mutable. Since they
2345   // could be overwritten by lowering of arguments in case of a tail call.
2346   if (Flags.isByVal()) {
2347     unsigned Bytes = Flags.getByValSize();
2348     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2349     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2350     return DAG.getFrameIndex(FI, getPointerTy());
2351   } else {
2352     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2353                                     VA.getLocMemOffset(), isImmutable);
2354     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2355     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2356                                MachinePointerInfo::getFixedStack(FI),
2357                                false, false, false, 0);
2358     return ExtendedInMem ?
2359       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2360   }
2361 }
2362
2363 // FIXME: Get this from tablegen.
2364 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2365                                                 const X86Subtarget *Subtarget) {
2366   assert(Subtarget->is64Bit());
2367
2368   if (Subtarget->isCallingConvWin64(CallConv)) {
2369     static const MCPhysReg GPR64ArgRegsWin64[] = {
2370       X86::RCX, X86::RDX, X86::R8,  X86::R9
2371     };
2372     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2373   }
2374
2375   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2376     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2377   };
2378   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2379 }
2380
2381 // FIXME: Get this from tablegen.
2382 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2383                                                 CallingConv::ID CallConv,
2384                                                 const X86Subtarget *Subtarget) {
2385   assert(Subtarget->is64Bit());
2386   if (Subtarget->isCallingConvWin64(CallConv)) {
2387     // The XMM registers which might contain var arg parameters are shadowed
2388     // in their paired GPR.  So we only need to save the GPR to their home
2389     // slots.
2390     // TODO: __vectorcall will change this.
2391     return None;
2392   }
2393
2394   const Function *Fn = MF.getFunction();
2395   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2396   bool isSoftFloat = Subtarget->useSoftFloat();
2397   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2398          "SSE register cannot be used when SSE is disabled!");
2399   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2400     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2401     // registers.
2402     return None;
2403
2404   static const MCPhysReg XMMArgRegs64Bit[] = {
2405     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2406     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2407   };
2408   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2409 }
2410
2411 SDValue
2412 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2413                                         CallingConv::ID CallConv,
2414                                         bool isVarArg,
2415                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2416                                         SDLoc dl,
2417                                         SelectionDAG &DAG,
2418                                         SmallVectorImpl<SDValue> &InVals)
2419                                           const {
2420   MachineFunction &MF = DAG.getMachineFunction();
2421   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2422   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2423
2424   const Function* Fn = MF.getFunction();
2425   if (Fn->hasExternalLinkage() &&
2426       Subtarget->isTargetCygMing() &&
2427       Fn->getName() == "main")
2428     FuncInfo->setForceFramePointer(true);
2429
2430   MachineFrameInfo *MFI = MF.getFrameInfo();
2431   bool Is64Bit = Subtarget->is64Bit();
2432   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2433
2434   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2435          "Var args not supported with calling convention fastcc, ghc or hipe");
2436
2437   // Assign locations to all of the incoming arguments.
2438   SmallVector<CCValAssign, 16> ArgLocs;
2439   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2440
2441   // Allocate shadow area for Win64
2442   if (IsWin64)
2443     CCInfo.AllocateStack(32, 8);
2444
2445   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2446
2447   unsigned LastVal = ~0U;
2448   SDValue ArgValue;
2449   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2450     CCValAssign &VA = ArgLocs[i];
2451     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2452     // places.
2453     assert(VA.getValNo() != LastVal &&
2454            "Don't support value assigned to multiple locs yet");
2455     (void)LastVal;
2456     LastVal = VA.getValNo();
2457
2458     if (VA.isRegLoc()) {
2459       EVT RegVT = VA.getLocVT();
2460       const TargetRegisterClass *RC;
2461       if (RegVT == MVT::i32)
2462         RC = &X86::GR32RegClass;
2463       else if (Is64Bit && RegVT == MVT::i64)
2464         RC = &X86::GR64RegClass;
2465       else if (RegVT == MVT::f32)
2466         RC = &X86::FR32RegClass;
2467       else if (RegVT == MVT::f64)
2468         RC = &X86::FR64RegClass;
2469       else if (RegVT.is512BitVector())
2470         RC = &X86::VR512RegClass;
2471       else if (RegVT.is256BitVector())
2472         RC = &X86::VR256RegClass;
2473       else if (RegVT.is128BitVector())
2474         RC = &X86::VR128RegClass;
2475       else if (RegVT == MVT::x86mmx)
2476         RC = &X86::VR64RegClass;
2477       else if (RegVT == MVT::i1)
2478         RC = &X86::VK1RegClass;
2479       else if (RegVT == MVT::v8i1)
2480         RC = &X86::VK8RegClass;
2481       else if (RegVT == MVT::v16i1)
2482         RC = &X86::VK16RegClass;
2483       else if (RegVT == MVT::v32i1)
2484         RC = &X86::VK32RegClass;
2485       else if (RegVT == MVT::v64i1)
2486         RC = &X86::VK64RegClass;
2487       else
2488         llvm_unreachable("Unknown argument type!");
2489
2490       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2491       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2492
2493       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2494       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2495       // right size.
2496       if (VA.getLocInfo() == CCValAssign::SExt)
2497         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2498                                DAG.getValueType(VA.getValVT()));
2499       else if (VA.getLocInfo() == CCValAssign::ZExt)
2500         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2501                                DAG.getValueType(VA.getValVT()));
2502       else if (VA.getLocInfo() == CCValAssign::BCvt)
2503         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2504
2505       if (VA.isExtInLoc()) {
2506         // Handle MMX values passed in XMM regs.
2507         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2508           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2509         else
2510           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2511       }
2512     } else {
2513       assert(VA.isMemLoc());
2514       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2515     }
2516
2517     // If value is passed via pointer - do a load.
2518     if (VA.getLocInfo() == CCValAssign::Indirect)
2519       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2520                              MachinePointerInfo(), false, false, false, 0);
2521
2522     InVals.push_back(ArgValue);
2523   }
2524
2525   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2526     // All x86 ABIs require that for returning structs by value we copy the
2527     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2528     // the argument into a virtual register so that we can access it from the
2529     // return points.
2530     if (Ins[i].Flags.isSRet()) {
2531       unsigned Reg = FuncInfo->getSRetReturnReg();
2532       if (!Reg) {
2533         MVT PtrTy = getPointerTy();
2534         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2535         FuncInfo->setSRetReturnReg(Reg);
2536       }
2537       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2538       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2539       break;
2540     }
2541   }
2542
2543   unsigned StackSize = CCInfo.getNextStackOffset();
2544   // Align stack specially for tail calls.
2545   if (FuncIsMadeTailCallSafe(CallConv,
2546                              MF.getTarget().Options.GuaranteedTailCallOpt))
2547     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2548
2549   // If the function takes variable number of arguments, make a frame index for
2550   // the start of the first vararg value... for expansion of llvm.va_start. We
2551   // can skip this if there are no va_start calls.
2552   if (MFI->hasVAStart() &&
2553       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2554                    CallConv != CallingConv::X86_ThisCall))) {
2555     FuncInfo->setVarArgsFrameIndex(
2556         MFI->CreateFixedObject(1, StackSize, true));
2557   }
2558
2559   MachineModuleInfo &MMI = MF.getMMI();
2560   const Function *WinEHParent = nullptr;
2561   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2562     WinEHParent = MMI.getWinEHParent(Fn);
2563   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2564   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2565
2566   // Figure out if XMM registers are in use.
2567   assert(!(Subtarget->useSoftFloat() &&
2568            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2569          "SSE register cannot be used when SSE is disabled!");
2570
2571   // 64-bit calling conventions support varargs and register parameters, so we
2572   // have to do extra work to spill them in the prologue.
2573   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2574     // Find the first unallocated argument registers.
2575     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2576     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2577     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2578     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2579     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2580            "SSE register cannot be used when SSE is disabled!");
2581
2582     // Gather all the live in physical registers.
2583     SmallVector<SDValue, 6> LiveGPRs;
2584     SmallVector<SDValue, 8> LiveXMMRegs;
2585     SDValue ALVal;
2586     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2587       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2588       LiveGPRs.push_back(
2589           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2590     }
2591     if (!ArgXMMs.empty()) {
2592       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2593       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2594       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2595         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2596         LiveXMMRegs.push_back(
2597             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2598       }
2599     }
2600
2601     if (IsWin64) {
2602       // Get to the caller-allocated home save location.  Add 8 to account
2603       // for the return address.
2604       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2605       FuncInfo->setRegSaveFrameIndex(
2606           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2607       // Fixup to set vararg frame on shadow area (4 x i64).
2608       if (NumIntRegs < 4)
2609         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2610     } else {
2611       // For X86-64, if there are vararg parameters that are passed via
2612       // registers, then we must store them to their spots on the stack so
2613       // they may be loaded by deferencing the result of va_next.
2614       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2615       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2616       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2617           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2618     }
2619
2620     // Store the integer parameter registers.
2621     SmallVector<SDValue, 8> MemOps;
2622     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2623                                       getPointerTy());
2624     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2625     for (SDValue Val : LiveGPRs) {
2626       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2627                                 DAG.getIntPtrConstant(Offset, dl));
2628       SDValue Store =
2629         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2630                      MachinePointerInfo::getFixedStack(
2631                        FuncInfo->getRegSaveFrameIndex(), Offset),
2632                      false, false, 0);
2633       MemOps.push_back(Store);
2634       Offset += 8;
2635     }
2636
2637     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2638       // Now store the XMM (fp + vector) parameter registers.
2639       SmallVector<SDValue, 12> SaveXMMOps;
2640       SaveXMMOps.push_back(Chain);
2641       SaveXMMOps.push_back(ALVal);
2642       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2643                              FuncInfo->getRegSaveFrameIndex(), dl));
2644       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2645                              FuncInfo->getVarArgsFPOffset(), dl));
2646       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2647                         LiveXMMRegs.end());
2648       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2649                                    MVT::Other, SaveXMMOps));
2650     }
2651
2652     if (!MemOps.empty())
2653       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2654   } else if (IsWinEHOutlined) {
2655     // Get to the caller-allocated home save location.  Add 8 to account
2656     // for the return address.
2657     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2658     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2659         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2660
2661     MMI.getWinEHFuncInfo(Fn)
2662         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2663         FuncInfo->getRegSaveFrameIndex();
2664
2665     // Store the second integer parameter (rdx) into rsp+16 relative to the
2666     // stack pointer at the entry of the function.
2667     SDValue RSFIN =
2668         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2669     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2670     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2671     Chain = DAG.getStore(
2672         Val.getValue(1), dl, Val, RSFIN,
2673         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2674         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2675   }
2676
2677   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2678     // Find the largest legal vector type.
2679     MVT VecVT = MVT::Other;
2680     // FIXME: Only some x86_32 calling conventions support AVX512.
2681     if (Subtarget->hasAVX512() &&
2682         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2683                      CallConv == CallingConv::Intel_OCL_BI)))
2684       VecVT = MVT::v16f32;
2685     else if (Subtarget->hasAVX())
2686       VecVT = MVT::v8f32;
2687     else if (Subtarget->hasSSE2())
2688       VecVT = MVT::v4f32;
2689
2690     // We forward some GPRs and some vector types.
2691     SmallVector<MVT, 2> RegParmTypes;
2692     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2693     RegParmTypes.push_back(IntVT);
2694     if (VecVT != MVT::Other)
2695       RegParmTypes.push_back(VecVT);
2696
2697     // Compute the set of forwarded registers. The rest are scratch.
2698     SmallVectorImpl<ForwardedRegister> &Forwards =
2699         FuncInfo->getForwardedMustTailRegParms();
2700     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2701
2702     // Conservatively forward AL on x86_64, since it might be used for varargs.
2703     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2704       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2705       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2706     }
2707
2708     // Copy all forwards from physical to virtual registers.
2709     for (ForwardedRegister &F : Forwards) {
2710       // FIXME: Can we use a less constrained schedule?
2711       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2712       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2713       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2714     }
2715   }
2716
2717   // Some CCs need callee pop.
2718   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2719                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2720     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2721   } else {
2722     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2723     // If this is an sret function, the return should pop the hidden pointer.
2724     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2725         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2726         argsAreStructReturn(Ins) == StackStructReturn)
2727       FuncInfo->setBytesToPopOnReturn(4);
2728   }
2729
2730   if (!Is64Bit) {
2731     // RegSaveFrameIndex is X86-64 only.
2732     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2733     if (CallConv == CallingConv::X86_FastCall ||
2734         CallConv == CallingConv::X86_ThisCall)
2735       // fastcc functions can't have varargs.
2736       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2737   }
2738
2739   FuncInfo->setArgumentStackSize(StackSize);
2740
2741   if (IsWinEHParent) {
2742     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2743     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2744     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2745     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2746     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2747                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2748                          /*isVolatile=*/true,
2749                          /*isNonTemporal=*/false, /*Alignment=*/0);
2750   }
2751
2752   return Chain;
2753 }
2754
2755 SDValue
2756 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2757                                     SDValue StackPtr, SDValue Arg,
2758                                     SDLoc dl, SelectionDAG &DAG,
2759                                     const CCValAssign &VA,
2760                                     ISD::ArgFlagsTy Flags) const {
2761   unsigned LocMemOffset = VA.getLocMemOffset();
2762   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2763   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2764   if (Flags.isByVal())
2765     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2766
2767   return DAG.getStore(Chain, dl, Arg, PtrOff,
2768                       MachinePointerInfo::getStack(LocMemOffset),
2769                       false, false, 0);
2770 }
2771
2772 /// Emit a load of return address if tail call
2773 /// optimization is performed and it is required.
2774 SDValue
2775 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2776                                            SDValue &OutRetAddr, SDValue Chain,
2777                                            bool IsTailCall, bool Is64Bit,
2778                                            int FPDiff, SDLoc dl) const {
2779   // Adjust the Return address stack slot.
2780   EVT VT = getPointerTy();
2781   OutRetAddr = getReturnAddressFrameIndex(DAG);
2782
2783   // Load the "old" Return address.
2784   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2785                            false, false, false, 0);
2786   return SDValue(OutRetAddr.getNode(), 1);
2787 }
2788
2789 /// Emit a store of the return address if tail call
2790 /// optimization is performed and it is required (FPDiff!=0).
2791 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2792                                         SDValue Chain, SDValue RetAddrFrIdx,
2793                                         EVT PtrVT, unsigned SlotSize,
2794                                         int FPDiff, SDLoc dl) {
2795   // Store the return address to the appropriate stack slot.
2796   if (!FPDiff) return Chain;
2797   // Calculate the new stack slot for the return address.
2798   int NewReturnAddrFI =
2799     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2800                                          false);
2801   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2802   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2803                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2804                        false, false, 0);
2805   return Chain;
2806 }
2807
2808 SDValue
2809 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2810                              SmallVectorImpl<SDValue> &InVals) const {
2811   SelectionDAG &DAG                     = CLI.DAG;
2812   SDLoc &dl                             = CLI.DL;
2813   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2814   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2815   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2816   SDValue Chain                         = CLI.Chain;
2817   SDValue Callee                        = CLI.Callee;
2818   CallingConv::ID CallConv              = CLI.CallConv;
2819   bool &isTailCall                      = CLI.IsTailCall;
2820   bool isVarArg                         = CLI.IsVarArg;
2821
2822   MachineFunction &MF = DAG.getMachineFunction();
2823   bool Is64Bit        = Subtarget->is64Bit();
2824   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2825   StructReturnType SR = callIsStructReturn(Outs);
2826   bool IsSibcall      = false;
2827   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2828   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2829
2830   if (Attr.getValueAsString() == "true")
2831     isTailCall = false;
2832
2833   if (Subtarget->isPICStyleGOT() &&
2834       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2835     // If we are using a GOT, disable tail calls to external symbols with
2836     // default visibility. Tail calling such a symbol requires using a GOT
2837     // relocation, which forces early binding of the symbol. This breaks code
2838     // that require lazy function symbol resolution. Using musttail or
2839     // GuaranteedTailCallOpt will override this.
2840     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2841     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2842                G->getGlobal()->hasDefaultVisibility()))
2843       isTailCall = false;
2844   }
2845
2846   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2847   if (IsMustTail) {
2848     // Force this to be a tail call.  The verifier rules are enough to ensure
2849     // that we can lower this successfully without moving the return address
2850     // around.
2851     isTailCall = true;
2852   } else if (isTailCall) {
2853     // Check if it's really possible to do a tail call.
2854     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2855                     isVarArg, SR != NotStructReturn,
2856                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2857                     Outs, OutVals, Ins, DAG);
2858
2859     // Sibcalls are automatically detected tailcalls which do not require
2860     // ABI changes.
2861     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2862       IsSibcall = true;
2863
2864     if (isTailCall)
2865       ++NumTailCalls;
2866   }
2867
2868   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2869          "Var args not supported with calling convention fastcc, ghc or hipe");
2870
2871   // Analyze operands of the call, assigning locations to each operand.
2872   SmallVector<CCValAssign, 16> ArgLocs;
2873   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2874
2875   // Allocate shadow area for Win64
2876   if (IsWin64)
2877     CCInfo.AllocateStack(32, 8);
2878
2879   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2880
2881   // Get a count of how many bytes are to be pushed on the stack.
2882   unsigned NumBytes = CCInfo.getNextStackOffset();
2883   if (IsSibcall)
2884     // This is a sibcall. The memory operands are available in caller's
2885     // own caller's stack.
2886     NumBytes = 0;
2887   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2888            IsTailCallConvention(CallConv))
2889     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2890
2891   int FPDiff = 0;
2892   if (isTailCall && !IsSibcall && !IsMustTail) {
2893     // Lower arguments at fp - stackoffset + fpdiff.
2894     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2895
2896     FPDiff = NumBytesCallerPushed - NumBytes;
2897
2898     // Set the delta of movement of the returnaddr stackslot.
2899     // But only set if delta is greater than previous delta.
2900     if (FPDiff < X86Info->getTCReturnAddrDelta())
2901       X86Info->setTCReturnAddrDelta(FPDiff);
2902   }
2903
2904   unsigned NumBytesToPush = NumBytes;
2905   unsigned NumBytesToPop = NumBytes;
2906
2907   // If we have an inalloca argument, all stack space has already been allocated
2908   // for us and be right at the top of the stack.  We don't support multiple
2909   // arguments passed in memory when using inalloca.
2910   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2911     NumBytesToPush = 0;
2912     if (!ArgLocs.back().isMemLoc())
2913       report_fatal_error("cannot use inalloca attribute on a register "
2914                          "parameter");
2915     if (ArgLocs.back().getLocMemOffset() != 0)
2916       report_fatal_error("any parameter with the inalloca attribute must be "
2917                          "the only memory argument");
2918   }
2919
2920   if (!IsSibcall)
2921     Chain = DAG.getCALLSEQ_START(
2922         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2923
2924   SDValue RetAddrFrIdx;
2925   // Load return address for tail calls.
2926   if (isTailCall && FPDiff)
2927     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2928                                     Is64Bit, FPDiff, dl);
2929
2930   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2931   SmallVector<SDValue, 8> MemOpChains;
2932   SDValue StackPtr;
2933
2934   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2935   // of tail call optimization arguments are handle later.
2936   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2937   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2938     // Skip inalloca arguments, they have already been written.
2939     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2940     if (Flags.isInAlloca())
2941       continue;
2942
2943     CCValAssign &VA = ArgLocs[i];
2944     EVT RegVT = VA.getLocVT();
2945     SDValue Arg = OutVals[i];
2946     bool isByVal = Flags.isByVal();
2947
2948     // Promote the value if needed.
2949     switch (VA.getLocInfo()) {
2950     default: llvm_unreachable("Unknown loc info!");
2951     case CCValAssign::Full: break;
2952     case CCValAssign::SExt:
2953       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2954       break;
2955     case CCValAssign::ZExt:
2956       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2957       break;
2958     case CCValAssign::AExt:
2959       if (Arg.getValueType().isVector() &&
2960           Arg.getValueType().getScalarType() == MVT::i1)
2961         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2962       else if (RegVT.is128BitVector()) {
2963         // Special case: passing MMX values in XMM registers.
2964         Arg = DAG.getBitcast(MVT::i64, Arg);
2965         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2966         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2967       } else
2968         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2969       break;
2970     case CCValAssign::BCvt:
2971       Arg = DAG.getBitcast(RegVT, Arg);
2972       break;
2973     case CCValAssign::Indirect: {
2974       // Store the argument.
2975       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2976       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2977       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2978                            MachinePointerInfo::getFixedStack(FI),
2979                            false, false, 0);
2980       Arg = SpillSlot;
2981       break;
2982     }
2983     }
2984
2985     if (VA.isRegLoc()) {
2986       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2987       if (isVarArg && IsWin64) {
2988         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2989         // shadow reg if callee is a varargs function.
2990         unsigned ShadowReg = 0;
2991         switch (VA.getLocReg()) {
2992         case X86::XMM0: ShadowReg = X86::RCX; break;
2993         case X86::XMM1: ShadowReg = X86::RDX; break;
2994         case X86::XMM2: ShadowReg = X86::R8; break;
2995         case X86::XMM3: ShadowReg = X86::R9; break;
2996         }
2997         if (ShadowReg)
2998           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2999       }
3000     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3001       assert(VA.isMemLoc());
3002       if (!StackPtr.getNode())
3003         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3004                                       getPointerTy());
3005       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3006                                              dl, DAG, VA, Flags));
3007     }
3008   }
3009
3010   if (!MemOpChains.empty())
3011     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3012
3013   if (Subtarget->isPICStyleGOT()) {
3014     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3015     // GOT pointer.
3016     if (!isTailCall) {
3017       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
3018                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
3019     } else {
3020       // If we are tail calling and generating PIC/GOT style code load the
3021       // address of the callee into ECX. The value in ecx is used as target of
3022       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3023       // for tail calls on PIC/GOT architectures. Normally we would just put the
3024       // address of GOT into ebx and then call target@PLT. But for tail calls
3025       // ebx would be restored (since ebx is callee saved) before jumping to the
3026       // target@PLT.
3027
3028       // Note: The actual moving to ECX is done further down.
3029       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3030       if (G && !G->getGlobal()->hasLocalLinkage() &&
3031           G->getGlobal()->hasDefaultVisibility())
3032         Callee = LowerGlobalAddress(Callee, DAG);
3033       else if (isa<ExternalSymbolSDNode>(Callee))
3034         Callee = LowerExternalSymbol(Callee, DAG);
3035     }
3036   }
3037
3038   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3039     // From AMD64 ABI document:
3040     // For calls that may call functions that use varargs or stdargs
3041     // (prototype-less calls or calls to functions containing ellipsis (...) in
3042     // the declaration) %al is used as hidden argument to specify the number
3043     // of SSE registers used. The contents of %al do not need to match exactly
3044     // the number of registers, but must be an ubound on the number of SSE
3045     // registers used and is in the range 0 - 8 inclusive.
3046
3047     // Count the number of XMM registers allocated.
3048     static const MCPhysReg XMMArgRegs[] = {
3049       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3050       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3051     };
3052     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3053     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3054            && "SSE registers cannot be used when SSE is disabled");
3055
3056     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3057                                         DAG.getConstant(NumXMMRegs, dl,
3058                                                         MVT::i8)));
3059   }
3060
3061   if (isVarArg && IsMustTail) {
3062     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3063     for (const auto &F : Forwards) {
3064       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3065       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3066     }
3067   }
3068
3069   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3070   // don't need this because the eligibility check rejects calls that require
3071   // shuffling arguments passed in memory.
3072   if (!IsSibcall && isTailCall) {
3073     // Force all the incoming stack arguments to be loaded from the stack
3074     // before any new outgoing arguments are stored to the stack, because the
3075     // outgoing stack slots may alias the incoming argument stack slots, and
3076     // the alias isn't otherwise explicit. This is slightly more conservative
3077     // than necessary, because it means that each store effectively depends
3078     // on every argument instead of just those arguments it would clobber.
3079     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3080
3081     SmallVector<SDValue, 8> MemOpChains2;
3082     SDValue FIN;
3083     int FI = 0;
3084     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3085       CCValAssign &VA = ArgLocs[i];
3086       if (VA.isRegLoc())
3087         continue;
3088       assert(VA.isMemLoc());
3089       SDValue Arg = OutVals[i];
3090       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3091       // Skip inalloca arguments.  They don't require any work.
3092       if (Flags.isInAlloca())
3093         continue;
3094       // Create frame index.
3095       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3096       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3097       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3098       FIN = DAG.getFrameIndex(FI, getPointerTy());
3099
3100       if (Flags.isByVal()) {
3101         // Copy relative to framepointer.
3102         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3103         if (!StackPtr.getNode())
3104           StackPtr = DAG.getCopyFromReg(Chain, dl,
3105                                         RegInfo->getStackRegister(),
3106                                         getPointerTy());
3107         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3108
3109         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3110                                                          ArgChain,
3111                                                          Flags, DAG, dl));
3112       } else {
3113         // Store relative to framepointer.
3114         MemOpChains2.push_back(
3115           DAG.getStore(ArgChain, dl, Arg, FIN,
3116                        MachinePointerInfo::getFixedStack(FI),
3117                        false, false, 0));
3118       }
3119     }
3120
3121     if (!MemOpChains2.empty())
3122       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3123
3124     // Store the return address to the appropriate stack slot.
3125     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3126                                      getPointerTy(), RegInfo->getSlotSize(),
3127                                      FPDiff, dl);
3128   }
3129
3130   // Build a sequence of copy-to-reg nodes chained together with token chain
3131   // and flag operands which copy the outgoing args into registers.
3132   SDValue InFlag;
3133   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3134     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3135                              RegsToPass[i].second, InFlag);
3136     InFlag = Chain.getValue(1);
3137   }
3138
3139   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3140     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3141     // In the 64-bit large code model, we have to make all calls
3142     // through a register, since the call instruction's 32-bit
3143     // pc-relative offset may not be large enough to hold the whole
3144     // address.
3145   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3146     // If the callee is a GlobalAddress node (quite common, every direct call
3147     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3148     // it.
3149     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3150
3151     // We should use extra load for direct calls to dllimported functions in
3152     // non-JIT mode.
3153     const GlobalValue *GV = G->getGlobal();
3154     if (!GV->hasDLLImportStorageClass()) {
3155       unsigned char OpFlags = 0;
3156       bool ExtraLoad = false;
3157       unsigned WrapperKind = ISD::DELETED_NODE;
3158
3159       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3160       // external symbols most go through the PLT in PIC mode.  If the symbol
3161       // has hidden or protected visibility, or if it is static or local, then
3162       // we don't need to use the PLT - we can directly call it.
3163       if (Subtarget->isTargetELF() &&
3164           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3165           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3166         OpFlags = X86II::MO_PLT;
3167       } else if (Subtarget->isPICStyleStubAny() &&
3168                  !GV->isStrongDefinitionForLinker() &&
3169                  (!Subtarget->getTargetTriple().isMacOSX() ||
3170                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3171         // PC-relative references to external symbols should go through $stub,
3172         // unless we're building with the leopard linker or later, which
3173         // automatically synthesizes these stubs.
3174         OpFlags = X86II::MO_DARWIN_STUB;
3175       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3176                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3177         // If the function is marked as non-lazy, generate an indirect call
3178         // which loads from the GOT directly. This avoids runtime overhead
3179         // at the cost of eager binding (and one extra byte of encoding).
3180         OpFlags = X86II::MO_GOTPCREL;
3181         WrapperKind = X86ISD::WrapperRIP;
3182         ExtraLoad = true;
3183       }
3184
3185       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3186                                           G->getOffset(), OpFlags);
3187
3188       // Add a wrapper if needed.
3189       if (WrapperKind != ISD::DELETED_NODE)
3190         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3191       // Add extra indirection if needed.
3192       if (ExtraLoad)
3193         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3194                              MachinePointerInfo::getGOT(),
3195                              false, false, false, 0);
3196     }
3197   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3198     unsigned char OpFlags = 0;
3199
3200     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3201     // external symbols should go through the PLT.
3202     if (Subtarget->isTargetELF() &&
3203         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3204       OpFlags = X86II::MO_PLT;
3205     } else if (Subtarget->isPICStyleStubAny() &&
3206                (!Subtarget->getTargetTriple().isMacOSX() ||
3207                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3208       // PC-relative references to external symbols should go through $stub,
3209       // unless we're building with the leopard linker or later, which
3210       // automatically synthesizes these stubs.
3211       OpFlags = X86II::MO_DARWIN_STUB;
3212     }
3213
3214     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3215                                          OpFlags);
3216   } else if (Subtarget->isTarget64BitILP32() &&
3217              Callee->getValueType(0) == MVT::i32) {
3218     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3219     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3220   }
3221
3222   // Returns a chain & a flag for retval copy to use.
3223   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3224   SmallVector<SDValue, 8> Ops;
3225
3226   if (!IsSibcall && isTailCall) {
3227     Chain = DAG.getCALLSEQ_END(Chain,
3228                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3229                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3230     InFlag = Chain.getValue(1);
3231   }
3232
3233   Ops.push_back(Chain);
3234   Ops.push_back(Callee);
3235
3236   if (isTailCall)
3237     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3238
3239   // Add argument registers to the end of the list so that they are known live
3240   // into the call.
3241   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3242     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3243                                   RegsToPass[i].second.getValueType()));
3244
3245   // Add a register mask operand representing the call-preserved registers.
3246   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3247   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3248   assert(Mask && "Missing call preserved mask for calling convention");
3249   Ops.push_back(DAG.getRegisterMask(Mask));
3250
3251   if (InFlag.getNode())
3252     Ops.push_back(InFlag);
3253
3254   if (isTailCall) {
3255     // We used to do:
3256     //// If this is the first return lowered for this function, add the regs
3257     //// to the liveout set for the function.
3258     // This isn't right, although it's probably harmless on x86; liveouts
3259     // should be computed from returns not tail calls.  Consider a void
3260     // function making a tail call to a function returning int.
3261     MF.getFrameInfo()->setHasTailCall();
3262     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3263   }
3264
3265   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3266   InFlag = Chain.getValue(1);
3267
3268   // Create the CALLSEQ_END node.
3269   unsigned NumBytesForCalleeToPop;
3270   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3271                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3272     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3273   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3274            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3275            SR == StackStructReturn)
3276     // If this is a call to a struct-return function, the callee
3277     // pops the hidden struct pointer, so we have to push it back.
3278     // This is common for Darwin/X86, Linux & Mingw32 targets.
3279     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3280     NumBytesForCalleeToPop = 4;
3281   else
3282     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3283
3284   // Returns a flag for retval copy to use.
3285   if (!IsSibcall) {
3286     Chain = DAG.getCALLSEQ_END(Chain,
3287                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3288                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3289                                                      true),
3290                                InFlag, dl);
3291     InFlag = Chain.getValue(1);
3292   }
3293
3294   // Handle result values, copying them out of physregs into vregs that we
3295   // return.
3296   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3297                          Ins, dl, DAG, InVals);
3298 }
3299
3300 //===----------------------------------------------------------------------===//
3301 //                Fast Calling Convention (tail call) implementation
3302 //===----------------------------------------------------------------------===//
3303
3304 //  Like std call, callee cleans arguments, convention except that ECX is
3305 //  reserved for storing the tail called function address. Only 2 registers are
3306 //  free for argument passing (inreg). Tail call optimization is performed
3307 //  provided:
3308 //                * tailcallopt is enabled
3309 //                * caller/callee are fastcc
3310 //  On X86_64 architecture with GOT-style position independent code only local
3311 //  (within module) calls are supported at the moment.
3312 //  To keep the stack aligned according to platform abi the function
3313 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3314 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3315 //  If a tail called function callee has more arguments than the caller the
3316 //  caller needs to make sure that there is room to move the RETADDR to. This is
3317 //  achieved by reserving an area the size of the argument delta right after the
3318 //  original RETADDR, but before the saved framepointer or the spilled registers
3319 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3320 //  stack layout:
3321 //    arg1
3322 //    arg2
3323 //    RETADDR
3324 //    [ new RETADDR
3325 //      move area ]
3326 //    (possible EBP)
3327 //    ESI
3328 //    EDI
3329 //    local1 ..
3330
3331 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3332 /// for a 16 byte align requirement.
3333 unsigned
3334 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3335                                                SelectionDAG& DAG) const {
3336   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3337   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3338   unsigned StackAlignment = TFI.getStackAlignment();
3339   uint64_t AlignMask = StackAlignment - 1;
3340   int64_t Offset = StackSize;
3341   unsigned SlotSize = RegInfo->getSlotSize();
3342   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3343     // Number smaller than 12 so just add the difference.
3344     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3345   } else {
3346     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3347     Offset = ((~AlignMask) & Offset) + StackAlignment +
3348       (StackAlignment-SlotSize);
3349   }
3350   return Offset;
3351 }
3352
3353 /// MatchingStackOffset - Return true if the given stack call argument is
3354 /// already available in the same position (relatively) of the caller's
3355 /// incoming argument stack.
3356 static
3357 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3358                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3359                          const X86InstrInfo *TII) {
3360   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3361   int FI = INT_MAX;
3362   if (Arg.getOpcode() == ISD::CopyFromReg) {
3363     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3364     if (!TargetRegisterInfo::isVirtualRegister(VR))
3365       return false;
3366     MachineInstr *Def = MRI->getVRegDef(VR);
3367     if (!Def)
3368       return false;
3369     if (!Flags.isByVal()) {
3370       if (!TII->isLoadFromStackSlot(Def, FI))
3371         return false;
3372     } else {
3373       unsigned Opcode = Def->getOpcode();
3374       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3375            Opcode == X86::LEA64_32r) &&
3376           Def->getOperand(1).isFI()) {
3377         FI = Def->getOperand(1).getIndex();
3378         Bytes = Flags.getByValSize();
3379       } else
3380         return false;
3381     }
3382   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3383     if (Flags.isByVal())
3384       // ByVal argument is passed in as a pointer but it's now being
3385       // dereferenced. e.g.
3386       // define @foo(%struct.X* %A) {
3387       //   tail call @bar(%struct.X* byval %A)
3388       // }
3389       return false;
3390     SDValue Ptr = Ld->getBasePtr();
3391     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3392     if (!FINode)
3393       return false;
3394     FI = FINode->getIndex();
3395   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3396     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3397     FI = FINode->getIndex();
3398     Bytes = Flags.getByValSize();
3399   } else
3400     return false;
3401
3402   assert(FI != INT_MAX);
3403   if (!MFI->isFixedObjectIndex(FI))
3404     return false;
3405   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3406 }
3407
3408 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3409 /// for tail call optimization. Targets which want to do tail call
3410 /// optimization should implement this function.
3411 bool
3412 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3413                                                      CallingConv::ID CalleeCC,
3414                                                      bool isVarArg,
3415                                                      bool isCalleeStructRet,
3416                                                      bool isCallerStructRet,
3417                                                      Type *RetTy,
3418                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3419                                     const SmallVectorImpl<SDValue> &OutVals,
3420                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3421                                                      SelectionDAG &DAG) const {
3422   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3423     return false;
3424
3425   // If -tailcallopt is specified, make fastcc functions tail-callable.
3426   const MachineFunction &MF = DAG.getMachineFunction();
3427   const Function *CallerF = MF.getFunction();
3428
3429   // If the function return type is x86_fp80 and the callee return type is not,
3430   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3431   // perform a tailcall optimization here.
3432   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3433     return false;
3434
3435   CallingConv::ID CallerCC = CallerF->getCallingConv();
3436   bool CCMatch = CallerCC == CalleeCC;
3437   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3438   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3439
3440   // Win64 functions have extra shadow space for argument homing. Don't do the
3441   // sibcall if the caller and callee have mismatched expectations for this
3442   // space.
3443   if (IsCalleeWin64 != IsCallerWin64)
3444     return false;
3445
3446   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3447     if (IsTailCallConvention(CalleeCC) && CCMatch)
3448       return true;
3449     return false;
3450   }
3451
3452   // Look for obvious safe cases to perform tail call optimization that do not
3453   // require ABI changes. This is what gcc calls sibcall.
3454
3455   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3456   // emit a special epilogue.
3457   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3458   if (RegInfo->needsStackRealignment(MF))
3459     return false;
3460
3461   // Also avoid sibcall optimization if either caller or callee uses struct
3462   // return semantics.
3463   if (isCalleeStructRet || isCallerStructRet)
3464     return false;
3465
3466   // An stdcall/thiscall caller is expected to clean up its arguments; the
3467   // callee isn't going to do that.
3468   // FIXME: this is more restrictive than needed. We could produce a tailcall
3469   // when the stack adjustment matches. For example, with a thiscall that takes
3470   // only one argument.
3471   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3472                    CallerCC == CallingConv::X86_ThisCall))
3473     return false;
3474
3475   // Do not sibcall optimize vararg calls unless all arguments are passed via
3476   // registers.
3477   if (isVarArg && !Outs.empty()) {
3478
3479     // Optimizing for varargs on Win64 is unlikely to be safe without
3480     // additional testing.
3481     if (IsCalleeWin64 || IsCallerWin64)
3482       return false;
3483
3484     SmallVector<CCValAssign, 16> ArgLocs;
3485     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3486                    *DAG.getContext());
3487
3488     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3489     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3490       if (!ArgLocs[i].isRegLoc())
3491         return false;
3492   }
3493
3494   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3495   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3496   // this into a sibcall.
3497   bool Unused = false;
3498   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3499     if (!Ins[i].Used) {
3500       Unused = true;
3501       break;
3502     }
3503   }
3504   if (Unused) {
3505     SmallVector<CCValAssign, 16> RVLocs;
3506     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3507                    *DAG.getContext());
3508     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3509     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3510       CCValAssign &VA = RVLocs[i];
3511       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3512         return false;
3513     }
3514   }
3515
3516   // If the calling conventions do not match, then we'd better make sure the
3517   // results are returned in the same way as what the caller expects.
3518   if (!CCMatch) {
3519     SmallVector<CCValAssign, 16> RVLocs1;
3520     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3521                     *DAG.getContext());
3522     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3523
3524     SmallVector<CCValAssign, 16> RVLocs2;
3525     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3526                     *DAG.getContext());
3527     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3528
3529     if (RVLocs1.size() != RVLocs2.size())
3530       return false;
3531     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3532       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3533         return false;
3534       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3535         return false;
3536       if (RVLocs1[i].isRegLoc()) {
3537         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3538           return false;
3539       } else {
3540         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3541           return false;
3542       }
3543     }
3544   }
3545
3546   // If the callee takes no arguments then go on to check the results of the
3547   // call.
3548   if (!Outs.empty()) {
3549     // Check if stack adjustment is needed. For now, do not do this if any
3550     // argument is passed on the stack.
3551     SmallVector<CCValAssign, 16> ArgLocs;
3552     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3553                    *DAG.getContext());
3554
3555     // Allocate shadow area for Win64
3556     if (IsCalleeWin64)
3557       CCInfo.AllocateStack(32, 8);
3558
3559     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3560     if (CCInfo.getNextStackOffset()) {
3561       MachineFunction &MF = DAG.getMachineFunction();
3562       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3563         return false;
3564
3565       // Check if the arguments are already laid out in the right way as
3566       // the caller's fixed stack objects.
3567       MachineFrameInfo *MFI = MF.getFrameInfo();
3568       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3569       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3570       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3571         CCValAssign &VA = ArgLocs[i];
3572         SDValue Arg = OutVals[i];
3573         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3574         if (VA.getLocInfo() == CCValAssign::Indirect)
3575           return false;
3576         if (!VA.isRegLoc()) {
3577           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3578                                    MFI, MRI, TII))
3579             return false;
3580         }
3581       }
3582     }
3583
3584     // If the tailcall address may be in a register, then make sure it's
3585     // possible to register allocate for it. In 32-bit, the call address can
3586     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3587     // callee-saved registers are restored. These happen to be the same
3588     // registers used to pass 'inreg' arguments so watch out for those.
3589     if (!Subtarget->is64Bit() &&
3590         ((!isa<GlobalAddressSDNode>(Callee) &&
3591           !isa<ExternalSymbolSDNode>(Callee)) ||
3592          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3593       unsigned NumInRegs = 0;
3594       // In PIC we need an extra register to formulate the address computation
3595       // for the callee.
3596       unsigned MaxInRegs =
3597         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3598
3599       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3600         CCValAssign &VA = ArgLocs[i];
3601         if (!VA.isRegLoc())
3602           continue;
3603         unsigned Reg = VA.getLocReg();
3604         switch (Reg) {
3605         default: break;
3606         case X86::EAX: case X86::EDX: case X86::ECX:
3607           if (++NumInRegs == MaxInRegs)
3608             return false;
3609           break;
3610         }
3611       }
3612     }
3613   }
3614
3615   return true;
3616 }
3617
3618 FastISel *
3619 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3620                                   const TargetLibraryInfo *libInfo) const {
3621   return X86::createFastISel(funcInfo, libInfo);
3622 }
3623
3624 //===----------------------------------------------------------------------===//
3625 //                           Other Lowering Hooks
3626 //===----------------------------------------------------------------------===//
3627
3628 static bool MayFoldLoad(SDValue Op) {
3629   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3630 }
3631
3632 static bool MayFoldIntoStore(SDValue Op) {
3633   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3634 }
3635
3636 static bool isTargetShuffle(unsigned Opcode) {
3637   switch(Opcode) {
3638   default: return false;
3639   case X86ISD::BLENDI:
3640   case X86ISD::PSHUFB:
3641   case X86ISD::PSHUFD:
3642   case X86ISD::PSHUFHW:
3643   case X86ISD::PSHUFLW:
3644   case X86ISD::SHUFP:
3645   case X86ISD::PALIGNR:
3646   case X86ISD::MOVLHPS:
3647   case X86ISD::MOVLHPD:
3648   case X86ISD::MOVHLPS:
3649   case X86ISD::MOVLPS:
3650   case X86ISD::MOVLPD:
3651   case X86ISD::MOVSHDUP:
3652   case X86ISD::MOVSLDUP:
3653   case X86ISD::MOVDDUP:
3654   case X86ISD::MOVSS:
3655   case X86ISD::MOVSD:
3656   case X86ISD::UNPCKL:
3657   case X86ISD::UNPCKH:
3658   case X86ISD::VPERMILPI:
3659   case X86ISD::VPERM2X128:
3660   case X86ISD::VPERMI:
3661     return true;
3662   }
3663 }
3664
3665 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3666                                     SDValue V1, unsigned TargetMask,
3667                                     SelectionDAG &DAG) {
3668   switch(Opc) {
3669   default: llvm_unreachable("Unknown x86 shuffle node");
3670   case X86ISD::PSHUFD:
3671   case X86ISD::PSHUFHW:
3672   case X86ISD::PSHUFLW:
3673   case X86ISD::VPERMILPI:
3674   case X86ISD::VPERMI:
3675     return DAG.getNode(Opc, dl, VT, V1,
3676                        DAG.getConstant(TargetMask, dl, MVT::i8));
3677   }
3678 }
3679
3680 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3681                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3682   switch(Opc) {
3683   default: llvm_unreachable("Unknown x86 shuffle node");
3684   case X86ISD::MOVLHPS:
3685   case X86ISD::MOVLHPD:
3686   case X86ISD::MOVHLPS:
3687   case X86ISD::MOVLPS:
3688   case X86ISD::MOVLPD:
3689   case X86ISD::MOVSS:
3690   case X86ISD::MOVSD:
3691   case X86ISD::UNPCKL:
3692   case X86ISD::UNPCKH:
3693     return DAG.getNode(Opc, dl, VT, V1, V2);
3694   }
3695 }
3696
3697 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3698   MachineFunction &MF = DAG.getMachineFunction();
3699   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3700   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3701   int ReturnAddrIndex = FuncInfo->getRAIndex();
3702
3703   if (ReturnAddrIndex == 0) {
3704     // Set up a frame object for the return address.
3705     unsigned SlotSize = RegInfo->getSlotSize();
3706     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3707                                                            -(int64_t)SlotSize,
3708                                                            false);
3709     FuncInfo->setRAIndex(ReturnAddrIndex);
3710   }
3711
3712   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3713 }
3714
3715 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3716                                        bool hasSymbolicDisplacement) {
3717   // Offset should fit into 32 bit immediate field.
3718   if (!isInt<32>(Offset))
3719     return false;
3720
3721   // If we don't have a symbolic displacement - we don't have any extra
3722   // restrictions.
3723   if (!hasSymbolicDisplacement)
3724     return true;
3725
3726   // FIXME: Some tweaks might be needed for medium code model.
3727   if (M != CodeModel::Small && M != CodeModel::Kernel)
3728     return false;
3729
3730   // For small code model we assume that latest object is 16MB before end of 31
3731   // bits boundary. We may also accept pretty large negative constants knowing
3732   // that all objects are in the positive half of address space.
3733   if (M == CodeModel::Small && Offset < 16*1024*1024)
3734     return true;
3735
3736   // For kernel code model we know that all object resist in the negative half
3737   // of 32bits address space. We may not accept negative offsets, since they may
3738   // be just off and we may accept pretty large positive ones.
3739   if (M == CodeModel::Kernel && Offset >= 0)
3740     return true;
3741
3742   return false;
3743 }
3744
3745 /// isCalleePop - Determines whether the callee is required to pop its
3746 /// own arguments. Callee pop is necessary to support tail calls.
3747 bool X86::isCalleePop(CallingConv::ID CallingConv,
3748                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3749   switch (CallingConv) {
3750   default:
3751     return false;
3752   case CallingConv::X86_StdCall:
3753   case CallingConv::X86_FastCall:
3754   case CallingConv::X86_ThisCall:
3755     return !is64Bit;
3756   case CallingConv::Fast:
3757   case CallingConv::GHC:
3758   case CallingConv::HiPE:
3759     if (IsVarArg)
3760       return false;
3761     return TailCallOpt;
3762   }
3763 }
3764
3765 /// \brief Return true if the condition is an unsigned comparison operation.
3766 static bool isX86CCUnsigned(unsigned X86CC) {
3767   switch (X86CC) {
3768   default: llvm_unreachable("Invalid integer condition!");
3769   case X86::COND_E:     return true;
3770   case X86::COND_G:     return false;
3771   case X86::COND_GE:    return false;
3772   case X86::COND_L:     return false;
3773   case X86::COND_LE:    return false;
3774   case X86::COND_NE:    return true;
3775   case X86::COND_B:     return true;
3776   case X86::COND_A:     return true;
3777   case X86::COND_BE:    return true;
3778   case X86::COND_AE:    return true;
3779   }
3780   llvm_unreachable("covered switch fell through?!");
3781 }
3782
3783 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3784 /// specific condition code, returning the condition code and the LHS/RHS of the
3785 /// comparison to make.
3786 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3787                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3788   if (!isFP) {
3789     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3790       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3791         // X > -1   -> X == 0, jump !sign.
3792         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3793         return X86::COND_NS;
3794       }
3795       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3796         // X < 0   -> X == 0, jump on sign.
3797         return X86::COND_S;
3798       }
3799       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3800         // X < 1   -> X <= 0
3801         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3802         return X86::COND_LE;
3803       }
3804     }
3805
3806     switch (SetCCOpcode) {
3807     default: llvm_unreachable("Invalid integer condition!");
3808     case ISD::SETEQ:  return X86::COND_E;
3809     case ISD::SETGT:  return X86::COND_G;
3810     case ISD::SETGE:  return X86::COND_GE;
3811     case ISD::SETLT:  return X86::COND_L;
3812     case ISD::SETLE:  return X86::COND_LE;
3813     case ISD::SETNE:  return X86::COND_NE;
3814     case ISD::SETULT: return X86::COND_B;
3815     case ISD::SETUGT: return X86::COND_A;
3816     case ISD::SETULE: return X86::COND_BE;
3817     case ISD::SETUGE: return X86::COND_AE;
3818     }
3819   }
3820
3821   // First determine if it is required or is profitable to flip the operands.
3822
3823   // If LHS is a foldable load, but RHS is not, flip the condition.
3824   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3825       !ISD::isNON_EXTLoad(RHS.getNode())) {
3826     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3827     std::swap(LHS, RHS);
3828   }
3829
3830   switch (SetCCOpcode) {
3831   default: break;
3832   case ISD::SETOLT:
3833   case ISD::SETOLE:
3834   case ISD::SETUGT:
3835   case ISD::SETUGE:
3836     std::swap(LHS, RHS);
3837     break;
3838   }
3839
3840   // On a floating point condition, the flags are set as follows:
3841   // ZF  PF  CF   op
3842   //  0 | 0 | 0 | X > Y
3843   //  0 | 0 | 1 | X < Y
3844   //  1 | 0 | 0 | X == Y
3845   //  1 | 1 | 1 | unordered
3846   switch (SetCCOpcode) {
3847   default: llvm_unreachable("Condcode should be pre-legalized away");
3848   case ISD::SETUEQ:
3849   case ISD::SETEQ:   return X86::COND_E;
3850   case ISD::SETOLT:              // flipped
3851   case ISD::SETOGT:
3852   case ISD::SETGT:   return X86::COND_A;
3853   case ISD::SETOLE:              // flipped
3854   case ISD::SETOGE:
3855   case ISD::SETGE:   return X86::COND_AE;
3856   case ISD::SETUGT:              // flipped
3857   case ISD::SETULT:
3858   case ISD::SETLT:   return X86::COND_B;
3859   case ISD::SETUGE:              // flipped
3860   case ISD::SETULE:
3861   case ISD::SETLE:   return X86::COND_BE;
3862   case ISD::SETONE:
3863   case ISD::SETNE:   return X86::COND_NE;
3864   case ISD::SETUO:   return X86::COND_P;
3865   case ISD::SETO:    return X86::COND_NP;
3866   case ISD::SETOEQ:
3867   case ISD::SETUNE:  return X86::COND_INVALID;
3868   }
3869 }
3870
3871 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3872 /// code. Current x86 isa includes the following FP cmov instructions:
3873 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3874 static bool hasFPCMov(unsigned X86CC) {
3875   switch (X86CC) {
3876   default:
3877     return false;
3878   case X86::COND_B:
3879   case X86::COND_BE:
3880   case X86::COND_E:
3881   case X86::COND_P:
3882   case X86::COND_A:
3883   case X86::COND_AE:
3884   case X86::COND_NE:
3885   case X86::COND_NP:
3886     return true;
3887   }
3888 }
3889
3890 /// isFPImmLegal - Returns true if the target can instruction select the
3891 /// specified FP immediate natively. If false, the legalizer will
3892 /// materialize the FP immediate as a load from a constant pool.
3893 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3894   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3895     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3896       return true;
3897   }
3898   return false;
3899 }
3900
3901 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3902                                               ISD::LoadExtType ExtTy,
3903                                               EVT NewVT) const {
3904   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3905   // relocation target a movq or addq instruction: don't let the load shrink.
3906   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3907   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3908     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3909       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3910   return true;
3911 }
3912
3913 /// \brief Returns true if it is beneficial to convert a load of a constant
3914 /// to just the constant itself.
3915 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3916                                                           Type *Ty) const {
3917   assert(Ty->isIntegerTy());
3918
3919   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3920   if (BitSize == 0 || BitSize > 64)
3921     return false;
3922   return true;
3923 }
3924
3925 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3926                                                 unsigned Index) const {
3927   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3928     return false;
3929
3930   return (Index == 0 || Index == ResVT.getVectorNumElements());
3931 }
3932
3933 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3934   // Speculate cttz only if we can directly use TZCNT.
3935   return Subtarget->hasBMI();
3936 }
3937
3938 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3939   // Speculate ctlz only if we can directly use LZCNT.
3940   return Subtarget->hasLZCNT();
3941 }
3942
3943 /// isUndefInRange - Return true if every element in Mask, beginning
3944 /// from position Pos and ending in Pos+Size is undef.
3945 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3946   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3947     if (0 <= Mask[i])
3948       return false;
3949   return true;
3950 }
3951
3952 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3953 /// the specified range (L, H].
3954 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3955   return (Val < 0) || (Val >= Low && Val < Hi);
3956 }
3957
3958 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3959 /// specified value.
3960 static bool isUndefOrEqual(int Val, int CmpVal) {
3961   return (Val < 0 || Val == CmpVal);
3962 }
3963
3964 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3965 /// from position Pos and ending in Pos+Size, falls within the specified
3966 /// sequential range (Low, Low+Size]. or is undef.
3967 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3968                                        unsigned Pos, unsigned Size, int Low) {
3969   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3970     if (!isUndefOrEqual(Mask[i], Low))
3971       return false;
3972   return true;
3973 }
3974
3975 /// isVEXTRACTIndex - Return true if the specified
3976 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3977 /// suitable for instruction that extract 128 or 256 bit vectors
3978 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3979   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3980   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3981     return false;
3982
3983   // The index should be aligned on a vecWidth-bit boundary.
3984   uint64_t Index =
3985     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3986
3987   MVT VT = N->getSimpleValueType(0);
3988   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3989   bool Result = (Index * ElSize) % vecWidth == 0;
3990
3991   return Result;
3992 }
3993
3994 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3995 /// operand specifies a subvector insert that is suitable for input to
3996 /// insertion of 128 or 256-bit subvectors
3997 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3998   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3999   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4000     return false;
4001   // The index should be aligned on a vecWidth-bit boundary.
4002   uint64_t Index =
4003     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4004
4005   MVT VT = N->getSimpleValueType(0);
4006   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4007   bool Result = (Index * ElSize) % vecWidth == 0;
4008
4009   return Result;
4010 }
4011
4012 bool X86::isVINSERT128Index(SDNode *N) {
4013   return isVINSERTIndex(N, 128);
4014 }
4015
4016 bool X86::isVINSERT256Index(SDNode *N) {
4017   return isVINSERTIndex(N, 256);
4018 }
4019
4020 bool X86::isVEXTRACT128Index(SDNode *N) {
4021   return isVEXTRACTIndex(N, 128);
4022 }
4023
4024 bool X86::isVEXTRACT256Index(SDNode *N) {
4025   return isVEXTRACTIndex(N, 256);
4026 }
4027
4028 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4029   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4030   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4031     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4032
4033   uint64_t Index =
4034     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4035
4036   MVT VecVT = N->getOperand(0).getSimpleValueType();
4037   MVT ElVT = VecVT.getVectorElementType();
4038
4039   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4040   return Index / NumElemsPerChunk;
4041 }
4042
4043 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4044   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4045   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4046     llvm_unreachable("Illegal insert subvector for VINSERT");
4047
4048   uint64_t Index =
4049     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4050
4051   MVT VecVT = N->getSimpleValueType(0);
4052   MVT ElVT = VecVT.getVectorElementType();
4053
4054   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4055   return Index / NumElemsPerChunk;
4056 }
4057
4058 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4059 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4060 /// and VINSERTI128 instructions.
4061 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4062   return getExtractVEXTRACTImmediate(N, 128);
4063 }
4064
4065 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4066 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4067 /// and VINSERTI64x4 instructions.
4068 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4069   return getExtractVEXTRACTImmediate(N, 256);
4070 }
4071
4072 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4073 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4074 /// and VINSERTI128 instructions.
4075 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4076   return getInsertVINSERTImmediate(N, 128);
4077 }
4078
4079 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4080 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4081 /// and VINSERTI64x4 instructions.
4082 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4083   return getInsertVINSERTImmediate(N, 256);
4084 }
4085
4086 /// isZero - Returns true if Elt is a constant integer zero
4087 static bool isZero(SDValue V) {
4088   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4089   return C && C->isNullValue();
4090 }
4091
4092 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4093 /// constant +0.0.
4094 bool X86::isZeroNode(SDValue Elt) {
4095   if (isZero(Elt))
4096     return true;
4097   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4098     return CFP->getValueAPF().isPosZero();
4099   return false;
4100 }
4101
4102 /// getZeroVector - Returns a vector of specified type with all zero elements.
4103 ///
4104 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4105                              SelectionDAG &DAG, SDLoc dl) {
4106   assert(VT.isVector() && "Expected a vector type");
4107
4108   // Always build SSE zero vectors as <4 x i32> bitcasted
4109   // to their dest type. This ensures they get CSE'd.
4110   SDValue Vec;
4111   if (VT.is128BitVector()) {  // SSE
4112     if (Subtarget->hasSSE2()) {  // SSE2
4113       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4114       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4115     } else { // SSE1
4116       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4117       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4118     }
4119   } else if (VT.is256BitVector()) { // AVX
4120     if (Subtarget->hasInt256()) { // AVX2
4121       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4122       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4123       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4124     } else {
4125       // 256-bit logic and arithmetic instructions in AVX are all
4126       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4127       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4128       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4129       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4130     }
4131   } else if (VT.is512BitVector()) { // AVX-512
4132       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4133       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4134                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4135       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4136   } else if (VT.getScalarType() == MVT::i1) {
4137
4138     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4139             && "Unexpected vector type");
4140     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4141             && "Unexpected vector type");
4142     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4143     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4144     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4145   } else
4146     llvm_unreachable("Unexpected vector type");
4147
4148   return DAG.getBitcast(VT, Vec);
4149 }
4150
4151 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4152                                 SelectionDAG &DAG, SDLoc dl,
4153                                 unsigned vectorWidth) {
4154   assert((vectorWidth == 128 || vectorWidth == 256) &&
4155          "Unsupported vector width");
4156   EVT VT = Vec.getValueType();
4157   EVT ElVT = VT.getVectorElementType();
4158   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4159   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4160                                   VT.getVectorNumElements()/Factor);
4161
4162   // Extract from UNDEF is UNDEF.
4163   if (Vec.getOpcode() == ISD::UNDEF)
4164     return DAG.getUNDEF(ResultVT);
4165
4166   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4167   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4168
4169   // This is the index of the first element of the vectorWidth-bit chunk
4170   // we want.
4171   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4172                                * ElemsPerChunk);
4173
4174   // If the input is a buildvector just emit a smaller one.
4175   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4176     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4177                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4178                                     ElemsPerChunk));
4179
4180   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4181   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4182 }
4183
4184 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4185 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4186 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4187 /// instructions or a simple subregister reference. Idx is an index in the
4188 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4189 /// lowering EXTRACT_VECTOR_ELT operations easier.
4190 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4191                                    SelectionDAG &DAG, SDLoc dl) {
4192   assert((Vec.getValueType().is256BitVector() ||
4193           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4194   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4195 }
4196
4197 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4198 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4199                                    SelectionDAG &DAG, SDLoc dl) {
4200   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4201   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4202 }
4203
4204 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4205                                unsigned IdxVal, SelectionDAG &DAG,
4206                                SDLoc dl, unsigned vectorWidth) {
4207   assert((vectorWidth == 128 || vectorWidth == 256) &&
4208          "Unsupported vector width");
4209   // Inserting UNDEF is Result
4210   if (Vec.getOpcode() == ISD::UNDEF)
4211     return Result;
4212   EVT VT = Vec.getValueType();
4213   EVT ElVT = VT.getVectorElementType();
4214   EVT ResultVT = Result.getValueType();
4215
4216   // Insert the relevant vectorWidth bits.
4217   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4218
4219   // This is the index of the first element of the vectorWidth-bit chunk
4220   // we want.
4221   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4222                                * ElemsPerChunk);
4223
4224   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4225   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4226 }
4227
4228 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4229 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4230 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4231 /// simple superregister reference.  Idx is an index in the 128 bits
4232 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4233 /// lowering INSERT_VECTOR_ELT operations easier.
4234 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4235                                   SelectionDAG &DAG, SDLoc dl) {
4236   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4237
4238   // For insertion into the zero index (low half) of a 256-bit vector, it is
4239   // more efficient to generate a blend with immediate instead of an insert*128.
4240   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4241   // extend the subvector to the size of the result vector. Make sure that
4242   // we are not recursing on that node by checking for undef here.
4243   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4244       Result.getOpcode() != ISD::UNDEF) {
4245     EVT ResultVT = Result.getValueType();
4246     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4247     SDValue Undef = DAG.getUNDEF(ResultVT);
4248     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4249                                  Vec, ZeroIndex);
4250
4251     // The blend instruction, and therefore its mask, depend on the data type.
4252     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4253     if (ScalarType.isFloatingPoint()) {
4254       // Choose either vblendps (float) or vblendpd (double).
4255       unsigned ScalarSize = ScalarType.getSizeInBits();
4256       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4257       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4258       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4259       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4260     }
4261
4262     const X86Subtarget &Subtarget =
4263     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4264
4265     // AVX2 is needed for 256-bit integer blend support.
4266     // Integers must be cast to 32-bit because there is only vpblendd;
4267     // vpblendw can't be used for this because it has a handicapped mask.
4268
4269     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4270     // is still more efficient than using the wrong domain vinsertf128 that
4271     // will be created by InsertSubVector().
4272     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4273
4274     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4275     Vec256 = DAG.getBitcast(CastVT, Vec256);
4276     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4277     return DAG.getBitcast(ResultVT, Vec256);
4278   }
4279
4280   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4281 }
4282
4283 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4284                                   SelectionDAG &DAG, SDLoc dl) {
4285   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4286   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4287 }
4288
4289 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4290 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4291 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4292 /// large BUILD_VECTORS.
4293 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4294                                    unsigned NumElems, SelectionDAG &DAG,
4295                                    SDLoc dl) {
4296   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4297   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4298 }
4299
4300 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4301                                    unsigned NumElems, SelectionDAG &DAG,
4302                                    SDLoc dl) {
4303   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4304   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4305 }
4306
4307 /// getOnesVector - Returns a vector of specified type with all bits set.
4308 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4309 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4310 /// Then bitcast to their original type, ensuring they get CSE'd.
4311 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4312                              SDLoc dl) {
4313   assert(VT.isVector() && "Expected a vector type");
4314
4315   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4316   SDValue Vec;
4317   if (VT.is256BitVector()) {
4318     if (HasInt256) { // AVX2
4319       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4320       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4321     } else { // AVX
4322       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4323       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4324     }
4325   } else if (VT.is128BitVector()) {
4326     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4327   } else
4328     llvm_unreachable("Unexpected vector type");
4329
4330   return DAG.getBitcast(VT, Vec);
4331 }
4332
4333 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4334 /// operation of specified width.
4335 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4336                        SDValue V2) {
4337   unsigned NumElems = VT.getVectorNumElements();
4338   SmallVector<int, 8> Mask;
4339   Mask.push_back(NumElems);
4340   for (unsigned i = 1; i != NumElems; ++i)
4341     Mask.push_back(i);
4342   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4343 }
4344
4345 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4346 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4347                           SDValue V2) {
4348   unsigned NumElems = VT.getVectorNumElements();
4349   SmallVector<int, 8> Mask;
4350   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4351     Mask.push_back(i);
4352     Mask.push_back(i + NumElems);
4353   }
4354   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4355 }
4356
4357 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4358 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4359                           SDValue V2) {
4360   unsigned NumElems = VT.getVectorNumElements();
4361   SmallVector<int, 8> Mask;
4362   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4363     Mask.push_back(i + Half);
4364     Mask.push_back(i + NumElems + Half);
4365   }
4366   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4367 }
4368
4369 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4370 /// vector of zero or undef vector.  This produces a shuffle where the low
4371 /// element of V2 is swizzled into the zero/undef vector, landing at element
4372 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4373 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4374                                            bool IsZero,
4375                                            const X86Subtarget *Subtarget,
4376                                            SelectionDAG &DAG) {
4377   MVT VT = V2.getSimpleValueType();
4378   SDValue V1 = IsZero
4379     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4380   unsigned NumElems = VT.getVectorNumElements();
4381   SmallVector<int, 16> MaskVec;
4382   for (unsigned i = 0; i != NumElems; ++i)
4383     // If this is the insertion idx, put the low elt of V2 here.
4384     MaskVec.push_back(i == Idx ? NumElems : i);
4385   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4386 }
4387
4388 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4389 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4390 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4391 /// shuffles which use a single input multiple times, and in those cases it will
4392 /// adjust the mask to only have indices within that single input.
4393 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4394                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4395   unsigned NumElems = VT.getVectorNumElements();
4396   SDValue ImmN;
4397
4398   IsUnary = false;
4399   bool IsFakeUnary = false;
4400   switch(N->getOpcode()) {
4401   case X86ISD::BLENDI:
4402     ImmN = N->getOperand(N->getNumOperands()-1);
4403     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4404     break;
4405   case X86ISD::SHUFP:
4406     ImmN = N->getOperand(N->getNumOperands()-1);
4407     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4408     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4409     break;
4410   case X86ISD::UNPCKH:
4411     DecodeUNPCKHMask(VT, Mask);
4412     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4413     break;
4414   case X86ISD::UNPCKL:
4415     DecodeUNPCKLMask(VT, Mask);
4416     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4417     break;
4418   case X86ISD::MOVHLPS:
4419     DecodeMOVHLPSMask(NumElems, Mask);
4420     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4421     break;
4422   case X86ISD::MOVLHPS:
4423     DecodeMOVLHPSMask(NumElems, Mask);
4424     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4425     break;
4426   case X86ISD::PALIGNR:
4427     ImmN = N->getOperand(N->getNumOperands()-1);
4428     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4429     break;
4430   case X86ISD::PSHUFD:
4431   case X86ISD::VPERMILPI:
4432     ImmN = N->getOperand(N->getNumOperands()-1);
4433     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4434     IsUnary = true;
4435     break;
4436   case X86ISD::PSHUFHW:
4437     ImmN = N->getOperand(N->getNumOperands()-1);
4438     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4439     IsUnary = true;
4440     break;
4441   case X86ISD::PSHUFLW:
4442     ImmN = N->getOperand(N->getNumOperands()-1);
4443     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4444     IsUnary = true;
4445     break;
4446   case X86ISD::PSHUFB: {
4447     IsUnary = true;
4448     SDValue MaskNode = N->getOperand(1);
4449     while (MaskNode->getOpcode() == ISD::BITCAST)
4450       MaskNode = MaskNode->getOperand(0);
4451
4452     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4453       // If we have a build-vector, then things are easy.
4454       EVT VT = MaskNode.getValueType();
4455       assert(VT.isVector() &&
4456              "Can't produce a non-vector with a build_vector!");
4457       if (!VT.isInteger())
4458         return false;
4459
4460       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4461
4462       SmallVector<uint64_t, 32> RawMask;
4463       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4464         SDValue Op = MaskNode->getOperand(i);
4465         if (Op->getOpcode() == ISD::UNDEF) {
4466           RawMask.push_back((uint64_t)SM_SentinelUndef);
4467           continue;
4468         }
4469         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4470         if (!CN)
4471           return false;
4472         APInt MaskElement = CN->getAPIntValue();
4473
4474         // We now have to decode the element which could be any integer size and
4475         // extract each byte of it.
4476         for (int j = 0; j < NumBytesPerElement; ++j) {
4477           // Note that this is x86 and so always little endian: the low byte is
4478           // the first byte of the mask.
4479           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4480           MaskElement = MaskElement.lshr(8);
4481         }
4482       }
4483       DecodePSHUFBMask(RawMask, Mask);
4484       break;
4485     }
4486
4487     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4488     if (!MaskLoad)
4489       return false;
4490
4491     SDValue Ptr = MaskLoad->getBasePtr();
4492     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4493         Ptr->getOpcode() == X86ISD::WrapperRIP)
4494       Ptr = Ptr->getOperand(0);
4495
4496     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4497     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4498       return false;
4499
4500     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4501       DecodePSHUFBMask(C, Mask);
4502       if (Mask.empty())
4503         return false;
4504       break;
4505     }
4506
4507     return false;
4508   }
4509   case X86ISD::VPERMI:
4510     ImmN = N->getOperand(N->getNumOperands()-1);
4511     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4512     IsUnary = true;
4513     break;
4514   case X86ISD::MOVSS:
4515   case X86ISD::MOVSD:
4516     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4517     break;
4518   case X86ISD::VPERM2X128:
4519     ImmN = N->getOperand(N->getNumOperands()-1);
4520     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4521     if (Mask.empty()) return false;
4522     break;
4523   case X86ISD::MOVSLDUP:
4524     DecodeMOVSLDUPMask(VT, Mask);
4525     IsUnary = true;
4526     break;
4527   case X86ISD::MOVSHDUP:
4528     DecodeMOVSHDUPMask(VT, Mask);
4529     IsUnary = true;
4530     break;
4531   case X86ISD::MOVDDUP:
4532     DecodeMOVDDUPMask(VT, Mask);
4533     IsUnary = true;
4534     break;
4535   case X86ISD::MOVLHPD:
4536   case X86ISD::MOVLPD:
4537   case X86ISD::MOVLPS:
4538     // Not yet implemented
4539     return false;
4540   default: llvm_unreachable("unknown target shuffle node");
4541   }
4542
4543   // If we have a fake unary shuffle, the shuffle mask is spread across two
4544   // inputs that are actually the same node. Re-map the mask to always point
4545   // into the first input.
4546   if (IsFakeUnary)
4547     for (int &M : Mask)
4548       if (M >= (int)Mask.size())
4549         M -= Mask.size();
4550
4551   return true;
4552 }
4553
4554 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4555 /// element of the result of the vector shuffle.
4556 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4557                                    unsigned Depth) {
4558   if (Depth == 6)
4559     return SDValue();  // Limit search depth.
4560
4561   SDValue V = SDValue(N, 0);
4562   EVT VT = V.getValueType();
4563   unsigned Opcode = V.getOpcode();
4564
4565   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4566   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4567     int Elt = SV->getMaskElt(Index);
4568
4569     if (Elt < 0)
4570       return DAG.getUNDEF(VT.getVectorElementType());
4571
4572     unsigned NumElems = VT.getVectorNumElements();
4573     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4574                                          : SV->getOperand(1);
4575     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4576   }
4577
4578   // Recurse into target specific vector shuffles to find scalars.
4579   if (isTargetShuffle(Opcode)) {
4580     MVT ShufVT = V.getSimpleValueType();
4581     unsigned NumElems = ShufVT.getVectorNumElements();
4582     SmallVector<int, 16> ShuffleMask;
4583     bool IsUnary;
4584
4585     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4586       return SDValue();
4587
4588     int Elt = ShuffleMask[Index];
4589     if (Elt < 0)
4590       return DAG.getUNDEF(ShufVT.getVectorElementType());
4591
4592     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4593                                          : N->getOperand(1);
4594     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4595                                Depth+1);
4596   }
4597
4598   // Actual nodes that may contain scalar elements
4599   if (Opcode == ISD::BITCAST) {
4600     V = V.getOperand(0);
4601     EVT SrcVT = V.getValueType();
4602     unsigned NumElems = VT.getVectorNumElements();
4603
4604     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4605       return SDValue();
4606   }
4607
4608   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4609     return (Index == 0) ? V.getOperand(0)
4610                         : DAG.getUNDEF(VT.getVectorElementType());
4611
4612   if (V.getOpcode() == ISD::BUILD_VECTOR)
4613     return V.getOperand(Index);
4614
4615   return SDValue();
4616 }
4617
4618 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4619 ///
4620 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4621                                        unsigned NumNonZero, unsigned NumZero,
4622                                        SelectionDAG &DAG,
4623                                        const X86Subtarget* Subtarget,
4624                                        const TargetLowering &TLI) {
4625   if (NumNonZero > 8)
4626     return SDValue();
4627
4628   SDLoc dl(Op);
4629   SDValue V;
4630   bool First = true;
4631
4632   // SSE4.1 - use PINSRB to insert each byte directly.
4633   if (Subtarget->hasSSE41()) {
4634     for (unsigned i = 0; i < 16; ++i) {
4635       bool isNonZero = (NonZeros & (1 << i)) != 0;
4636       if (isNonZero) {
4637         if (First) {
4638           if (NumZero)
4639             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4640           else
4641             V = DAG.getUNDEF(MVT::v16i8);
4642           First = false;
4643         }
4644         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4645                         MVT::v16i8, V, Op.getOperand(i),
4646                         DAG.getIntPtrConstant(i, dl));
4647       }
4648     }
4649
4650     return V;
4651   }
4652
4653   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4654   for (unsigned i = 0; i < 16; ++i) {
4655     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4656     if (ThisIsNonZero && First) {
4657       if (NumZero)
4658         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4659       else
4660         V = DAG.getUNDEF(MVT::v8i16);
4661       First = false;
4662     }
4663
4664     if ((i & 1) != 0) {
4665       SDValue ThisElt, LastElt;
4666       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4667       if (LastIsNonZero) {
4668         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4669                               MVT::i16, Op.getOperand(i-1));
4670       }
4671       if (ThisIsNonZero) {
4672         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4673         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4674                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4675         if (LastIsNonZero)
4676           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4677       } else
4678         ThisElt = LastElt;
4679
4680       if (ThisElt.getNode())
4681         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4682                         DAG.getIntPtrConstant(i/2, dl));
4683     }
4684   }
4685
4686   return DAG.getBitcast(MVT::v16i8, V);
4687 }
4688
4689 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4690 ///
4691 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4692                                      unsigned NumNonZero, unsigned NumZero,
4693                                      SelectionDAG &DAG,
4694                                      const X86Subtarget* Subtarget,
4695                                      const TargetLowering &TLI) {
4696   if (NumNonZero > 4)
4697     return SDValue();
4698
4699   SDLoc dl(Op);
4700   SDValue V;
4701   bool First = true;
4702   for (unsigned i = 0; i < 8; ++i) {
4703     bool isNonZero = (NonZeros & (1 << i)) != 0;
4704     if (isNonZero) {
4705       if (First) {
4706         if (NumZero)
4707           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4708         else
4709           V = DAG.getUNDEF(MVT::v8i16);
4710         First = false;
4711       }
4712       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4713                       MVT::v8i16, V, Op.getOperand(i),
4714                       DAG.getIntPtrConstant(i, dl));
4715     }
4716   }
4717
4718   return V;
4719 }
4720
4721 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4722 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4723                                      const X86Subtarget *Subtarget,
4724                                      const TargetLowering &TLI) {
4725   // Find all zeroable elements.
4726   std::bitset<4> Zeroable;
4727   for (int i=0; i < 4; ++i) {
4728     SDValue Elt = Op->getOperand(i);
4729     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4730   }
4731   assert(Zeroable.size() - Zeroable.count() > 1 &&
4732          "We expect at least two non-zero elements!");
4733
4734   // We only know how to deal with build_vector nodes where elements are either
4735   // zeroable or extract_vector_elt with constant index.
4736   SDValue FirstNonZero;
4737   unsigned FirstNonZeroIdx;
4738   for (unsigned i=0; i < 4; ++i) {
4739     if (Zeroable[i])
4740       continue;
4741     SDValue Elt = Op->getOperand(i);
4742     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4743         !isa<ConstantSDNode>(Elt.getOperand(1)))
4744       return SDValue();
4745     // Make sure that this node is extracting from a 128-bit vector.
4746     MVT VT = Elt.getOperand(0).getSimpleValueType();
4747     if (!VT.is128BitVector())
4748       return SDValue();
4749     if (!FirstNonZero.getNode()) {
4750       FirstNonZero = Elt;
4751       FirstNonZeroIdx = i;
4752     }
4753   }
4754
4755   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4756   SDValue V1 = FirstNonZero.getOperand(0);
4757   MVT VT = V1.getSimpleValueType();
4758
4759   // See if this build_vector can be lowered as a blend with zero.
4760   SDValue Elt;
4761   unsigned EltMaskIdx, EltIdx;
4762   int Mask[4];
4763   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4764     if (Zeroable[EltIdx]) {
4765       // The zero vector will be on the right hand side.
4766       Mask[EltIdx] = EltIdx+4;
4767       continue;
4768     }
4769
4770     Elt = Op->getOperand(EltIdx);
4771     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4772     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4773     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4774       break;
4775     Mask[EltIdx] = EltIdx;
4776   }
4777
4778   if (EltIdx == 4) {
4779     // Let the shuffle legalizer deal with blend operations.
4780     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4781     if (V1.getSimpleValueType() != VT)
4782       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4783     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4784   }
4785
4786   // See if we can lower this build_vector to a INSERTPS.
4787   if (!Subtarget->hasSSE41())
4788     return SDValue();
4789
4790   SDValue V2 = Elt.getOperand(0);
4791   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4792     V1 = SDValue();
4793
4794   bool CanFold = true;
4795   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4796     if (Zeroable[i])
4797       continue;
4798
4799     SDValue Current = Op->getOperand(i);
4800     SDValue SrcVector = Current->getOperand(0);
4801     if (!V1.getNode())
4802       V1 = SrcVector;
4803     CanFold = SrcVector == V1 &&
4804       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4805   }
4806
4807   if (!CanFold)
4808     return SDValue();
4809
4810   assert(V1.getNode() && "Expected at least two non-zero elements!");
4811   if (V1.getSimpleValueType() != MVT::v4f32)
4812     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4813   if (V2.getSimpleValueType() != MVT::v4f32)
4814     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4815
4816   // Ok, we can emit an INSERTPS instruction.
4817   unsigned ZMask = Zeroable.to_ulong();
4818
4819   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4820   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4821   SDLoc DL(Op);
4822   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4823                                DAG.getIntPtrConstant(InsertPSMask, DL));
4824   return DAG.getBitcast(VT, Result);
4825 }
4826
4827 /// Return a vector logical shift node.
4828 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4829                          unsigned NumBits, SelectionDAG &DAG,
4830                          const TargetLowering &TLI, SDLoc dl) {
4831   assert(VT.is128BitVector() && "Unknown type for VShift");
4832   MVT ShVT = MVT::v2i64;
4833   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4834   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4835   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4836   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4837   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4838   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4839 }
4840
4841 static SDValue
4842 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4843
4844   // Check if the scalar load can be widened into a vector load. And if
4845   // the address is "base + cst" see if the cst can be "absorbed" into
4846   // the shuffle mask.
4847   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4848     SDValue Ptr = LD->getBasePtr();
4849     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4850       return SDValue();
4851     EVT PVT = LD->getValueType(0);
4852     if (PVT != MVT::i32 && PVT != MVT::f32)
4853       return SDValue();
4854
4855     int FI = -1;
4856     int64_t Offset = 0;
4857     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4858       FI = FINode->getIndex();
4859       Offset = 0;
4860     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4861                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4862       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4863       Offset = Ptr.getConstantOperandVal(1);
4864       Ptr = Ptr.getOperand(0);
4865     } else {
4866       return SDValue();
4867     }
4868
4869     // FIXME: 256-bit vector instructions don't require a strict alignment,
4870     // improve this code to support it better.
4871     unsigned RequiredAlign = VT.getSizeInBits()/8;
4872     SDValue Chain = LD->getChain();
4873     // Make sure the stack object alignment is at least 16 or 32.
4874     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4875     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4876       if (MFI->isFixedObjectIndex(FI)) {
4877         // Can't change the alignment. FIXME: It's possible to compute
4878         // the exact stack offset and reference FI + adjust offset instead.
4879         // If someone *really* cares about this. That's the way to implement it.
4880         return SDValue();
4881       } else {
4882         MFI->setObjectAlignment(FI, RequiredAlign);
4883       }
4884     }
4885
4886     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4887     // Ptr + (Offset & ~15).
4888     if (Offset < 0)
4889       return SDValue();
4890     if ((Offset % RequiredAlign) & 3)
4891       return SDValue();
4892     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4893     if (StartOffset) {
4894       SDLoc DL(Ptr);
4895       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4896                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4897     }
4898
4899     int EltNo = (Offset - StartOffset) >> 2;
4900     unsigned NumElems = VT.getVectorNumElements();
4901
4902     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4903     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4904                              LD->getPointerInfo().getWithOffset(StartOffset),
4905                              false, false, false, 0);
4906
4907     SmallVector<int, 8> Mask(NumElems, EltNo);
4908
4909     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4910   }
4911
4912   return SDValue();
4913 }
4914
4915 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4916 /// elements can be replaced by a single large load which has the same value as
4917 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4918 ///
4919 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4920 ///
4921 /// FIXME: we'd also like to handle the case where the last elements are zero
4922 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4923 /// There's even a handy isZeroNode for that purpose.
4924 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4925                                         SDLoc &DL, SelectionDAG &DAG,
4926                                         bool isAfterLegalize) {
4927   unsigned NumElems = Elts.size();
4928
4929   LoadSDNode *LDBase = nullptr;
4930   unsigned LastLoadedElt = -1U;
4931
4932   // For each element in the initializer, see if we've found a load or an undef.
4933   // If we don't find an initial load element, or later load elements are
4934   // non-consecutive, bail out.
4935   for (unsigned i = 0; i < NumElems; ++i) {
4936     SDValue Elt = Elts[i];
4937     // Look through a bitcast.
4938     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4939       Elt = Elt.getOperand(0);
4940     if (!Elt.getNode() ||
4941         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4942       return SDValue();
4943     if (!LDBase) {
4944       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4945         return SDValue();
4946       LDBase = cast<LoadSDNode>(Elt.getNode());
4947       LastLoadedElt = i;
4948       continue;
4949     }
4950     if (Elt.getOpcode() == ISD::UNDEF)
4951       continue;
4952
4953     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4954     EVT LdVT = Elt.getValueType();
4955     // Each loaded element must be the correct fractional portion of the
4956     // requested vector load.
4957     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4958       return SDValue();
4959     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4960       return SDValue();
4961     LastLoadedElt = i;
4962   }
4963
4964   // If we have found an entire vector of loads and undefs, then return a large
4965   // load of the entire vector width starting at the base pointer.  If we found
4966   // consecutive loads for the low half, generate a vzext_load node.
4967   if (LastLoadedElt == NumElems - 1) {
4968     assert(LDBase && "Did not find base load for merging consecutive loads");
4969     EVT EltVT = LDBase->getValueType(0);
4970     // Ensure that the input vector size for the merged loads matches the
4971     // cumulative size of the input elements.
4972     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4973       return SDValue();
4974
4975     if (isAfterLegalize &&
4976         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4977       return SDValue();
4978
4979     SDValue NewLd = SDValue();
4980
4981     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4982                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4983                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4984                         LDBase->getAlignment());
4985
4986     if (LDBase->hasAnyUseOfValue(1)) {
4987       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4988                                      SDValue(LDBase, 1),
4989                                      SDValue(NewLd.getNode(), 1));
4990       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4991       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4992                              SDValue(NewLd.getNode(), 1));
4993     }
4994
4995     return NewLd;
4996   }
4997
4998   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4999   //of a v4i32 / v4f32. It's probably worth generalizing.
5000   EVT EltVT = VT.getVectorElementType();
5001   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5002       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5003     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5004     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5005     SDValue ResNode =
5006         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5007                                 LDBase->getPointerInfo(),
5008                                 LDBase->getAlignment(),
5009                                 false/*isVolatile*/, true/*ReadMem*/,
5010                                 false/*WriteMem*/);
5011
5012     // Make sure the newly-created LOAD is in the same position as LDBase in
5013     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5014     // update uses of LDBase's output chain to use the TokenFactor.
5015     if (LDBase->hasAnyUseOfValue(1)) {
5016       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5017                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5018       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5019       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5020                              SDValue(ResNode.getNode(), 1));
5021     }
5022
5023     return DAG.getBitcast(VT, ResNode);
5024   }
5025   return SDValue();
5026 }
5027
5028 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5029 /// to generate a splat value for the following cases:
5030 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5031 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5032 /// a scalar load, or a constant.
5033 /// The VBROADCAST node is returned when a pattern is found,
5034 /// or SDValue() otherwise.
5035 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5036                                     SelectionDAG &DAG) {
5037   // VBROADCAST requires AVX.
5038   // TODO: Splats could be generated for non-AVX CPUs using SSE
5039   // instructions, but there's less potential gain for only 128-bit vectors.
5040   if (!Subtarget->hasAVX())
5041     return SDValue();
5042
5043   MVT VT = Op.getSimpleValueType();
5044   SDLoc dl(Op);
5045
5046   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5047          "Unsupported vector type for broadcast.");
5048
5049   SDValue Ld;
5050   bool ConstSplatVal;
5051
5052   switch (Op.getOpcode()) {
5053     default:
5054       // Unknown pattern found.
5055       return SDValue();
5056
5057     case ISD::BUILD_VECTOR: {
5058       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5059       BitVector UndefElements;
5060       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5061
5062       // We need a splat of a single value to use broadcast, and it doesn't
5063       // make any sense if the value is only in one element of the vector.
5064       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5065         return SDValue();
5066
5067       Ld = Splat;
5068       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5069                        Ld.getOpcode() == ISD::ConstantFP);
5070
5071       // Make sure that all of the users of a non-constant load are from the
5072       // BUILD_VECTOR node.
5073       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5074         return SDValue();
5075       break;
5076     }
5077
5078     case ISD::VECTOR_SHUFFLE: {
5079       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5080
5081       // Shuffles must have a splat mask where the first element is
5082       // broadcasted.
5083       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5084         return SDValue();
5085
5086       SDValue Sc = Op.getOperand(0);
5087       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5088           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5089
5090         if (!Subtarget->hasInt256())
5091           return SDValue();
5092
5093         // Use the register form of the broadcast instruction available on AVX2.
5094         if (VT.getSizeInBits() >= 256)
5095           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5096         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5097       }
5098
5099       Ld = Sc.getOperand(0);
5100       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5101                        Ld.getOpcode() == ISD::ConstantFP);
5102
5103       // The scalar_to_vector node and the suspected
5104       // load node must have exactly one user.
5105       // Constants may have multiple users.
5106
5107       // AVX-512 has register version of the broadcast
5108       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5109         Ld.getValueType().getSizeInBits() >= 32;
5110       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5111           !hasRegVer))
5112         return SDValue();
5113       break;
5114     }
5115   }
5116
5117   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5118   bool IsGE256 = (VT.getSizeInBits() >= 256);
5119
5120   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5121   // instruction to save 8 or more bytes of constant pool data.
5122   // TODO: If multiple splats are generated to load the same constant,
5123   // it may be detrimental to overall size. There needs to be a way to detect
5124   // that condition to know if this is truly a size win.
5125   const Function *F = DAG.getMachineFunction().getFunction();
5126   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5127
5128   // Handle broadcasting a single constant scalar from the constant pool
5129   // into a vector.
5130   // On Sandybridge (no AVX2), it is still better to load a constant vector
5131   // from the constant pool and not to broadcast it from a scalar.
5132   // But override that restriction when optimizing for size.
5133   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5134   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5135     EVT CVT = Ld.getValueType();
5136     assert(!CVT.isVector() && "Must not broadcast a vector type");
5137
5138     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5139     // For size optimization, also splat v2f64 and v2i64, and for size opt
5140     // with AVX2, also splat i8 and i16.
5141     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5142     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5143         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5144       const Constant *C = nullptr;
5145       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5146         C = CI->getConstantIntValue();
5147       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5148         C = CF->getConstantFPValue();
5149
5150       assert(C && "Invalid constant type");
5151
5152       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5153       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5154       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5155       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5156                        MachinePointerInfo::getConstantPool(),
5157                        false, false, false, Alignment);
5158
5159       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5160     }
5161   }
5162
5163   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5164
5165   // Handle AVX2 in-register broadcasts.
5166   if (!IsLoad && Subtarget->hasInt256() &&
5167       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5168     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5169
5170   // The scalar source must be a normal load.
5171   if (!IsLoad)
5172     return SDValue();
5173
5174   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5175       (Subtarget->hasVLX() && ScalarSize == 64))
5176     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5177
5178   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5179   // double since there is no vbroadcastsd xmm
5180   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5181     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5182       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5183   }
5184
5185   // Unsupported broadcast.
5186   return SDValue();
5187 }
5188
5189 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5190 /// underlying vector and index.
5191 ///
5192 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5193 /// index.
5194 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5195                                          SDValue ExtIdx) {
5196   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5197   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5198     return Idx;
5199
5200   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5201   // lowered this:
5202   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5203   // to:
5204   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5205   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5206   //                           undef)
5207   //                       Constant<0>)
5208   // In this case the vector is the extract_subvector expression and the index
5209   // is 2, as specified by the shuffle.
5210   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5211   SDValue ShuffleVec = SVOp->getOperand(0);
5212   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5213   assert(ShuffleVecVT.getVectorElementType() ==
5214          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5215
5216   int ShuffleIdx = SVOp->getMaskElt(Idx);
5217   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5218     ExtractedFromVec = ShuffleVec;
5219     return ShuffleIdx;
5220   }
5221   return Idx;
5222 }
5223
5224 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5225   MVT VT = Op.getSimpleValueType();
5226
5227   // Skip if insert_vec_elt is not supported.
5228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5229   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5230     return SDValue();
5231
5232   SDLoc DL(Op);
5233   unsigned NumElems = Op.getNumOperands();
5234
5235   SDValue VecIn1;
5236   SDValue VecIn2;
5237   SmallVector<unsigned, 4> InsertIndices;
5238   SmallVector<int, 8> Mask(NumElems, -1);
5239
5240   for (unsigned i = 0; i != NumElems; ++i) {
5241     unsigned Opc = Op.getOperand(i).getOpcode();
5242
5243     if (Opc == ISD::UNDEF)
5244       continue;
5245
5246     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5247       // Quit if more than 1 elements need inserting.
5248       if (InsertIndices.size() > 1)
5249         return SDValue();
5250
5251       InsertIndices.push_back(i);
5252       continue;
5253     }
5254
5255     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5256     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5257     // Quit if non-constant index.
5258     if (!isa<ConstantSDNode>(ExtIdx))
5259       return SDValue();
5260     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5261
5262     // Quit if extracted from vector of different type.
5263     if (ExtractedFromVec.getValueType() != VT)
5264       return SDValue();
5265
5266     if (!VecIn1.getNode())
5267       VecIn1 = ExtractedFromVec;
5268     else if (VecIn1 != ExtractedFromVec) {
5269       if (!VecIn2.getNode())
5270         VecIn2 = ExtractedFromVec;
5271       else if (VecIn2 != ExtractedFromVec)
5272         // Quit if more than 2 vectors to shuffle
5273         return SDValue();
5274     }
5275
5276     if (ExtractedFromVec == VecIn1)
5277       Mask[i] = Idx;
5278     else if (ExtractedFromVec == VecIn2)
5279       Mask[i] = Idx + NumElems;
5280   }
5281
5282   if (!VecIn1.getNode())
5283     return SDValue();
5284
5285   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5286   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5287   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5288     unsigned Idx = InsertIndices[i];
5289     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5290                      DAG.getIntPtrConstant(Idx, DL));
5291   }
5292
5293   return NV;
5294 }
5295
5296 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5297   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5298          Op.getScalarValueSizeInBits() == 1 &&
5299          "Can not convert non-constant vector");
5300   uint64_t Immediate = 0;
5301   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5302     SDValue In = Op.getOperand(idx);
5303     if (In.getOpcode() != ISD::UNDEF)
5304       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5305   }
5306   SDLoc dl(Op);
5307   MVT VT =
5308    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5309   return DAG.getConstant(Immediate, dl, VT);
5310 }
5311 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5312 SDValue
5313 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5314
5315   MVT VT = Op.getSimpleValueType();
5316   assert((VT.getVectorElementType() == MVT::i1) &&
5317          "Unexpected type in LowerBUILD_VECTORvXi1!");
5318
5319   SDLoc dl(Op);
5320   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5321     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5322     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5323     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5324   }
5325
5326   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5327     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5328     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5329     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5330   }
5331
5332   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5333     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5334     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5335       return DAG.getBitcast(VT, Imm);
5336     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5337     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5338                         DAG.getIntPtrConstant(0, dl));
5339   }
5340
5341   // Vector has one or more non-const elements
5342   uint64_t Immediate = 0;
5343   SmallVector<unsigned, 16> NonConstIdx;
5344   bool IsSplat = true;
5345   bool HasConstElts = false;
5346   int SplatIdx = -1;
5347   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5348     SDValue In = Op.getOperand(idx);
5349     if (In.getOpcode() == ISD::UNDEF)
5350       continue;
5351     if (!isa<ConstantSDNode>(In))
5352       NonConstIdx.push_back(idx);
5353     else {
5354       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5355       HasConstElts = true;
5356     }
5357     if (SplatIdx == -1)
5358       SplatIdx = idx;
5359     else if (In != Op.getOperand(SplatIdx))
5360       IsSplat = false;
5361   }
5362
5363   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5364   if (IsSplat)
5365     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5366                        DAG.getConstant(1, dl, VT),
5367                        DAG.getConstant(0, dl, VT));
5368
5369   // insert elements one by one
5370   SDValue DstVec;
5371   SDValue Imm;
5372   if (Immediate) {
5373     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5374     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5375   }
5376   else if (HasConstElts)
5377     Imm = DAG.getConstant(0, dl, VT);
5378   else
5379     Imm = DAG.getUNDEF(VT);
5380   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5381     DstVec = DAG.getBitcast(VT, Imm);
5382   else {
5383     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5384     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5385                          DAG.getIntPtrConstant(0, dl));
5386   }
5387
5388   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5389     unsigned InsertIdx = NonConstIdx[i];
5390     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5391                          Op.getOperand(InsertIdx),
5392                          DAG.getIntPtrConstant(InsertIdx, dl));
5393   }
5394   return DstVec;
5395 }
5396
5397 /// \brief Return true if \p N implements a horizontal binop and return the
5398 /// operands for the horizontal binop into V0 and V1.
5399 ///
5400 /// This is a helper function of LowerToHorizontalOp().
5401 /// This function checks that the build_vector \p N in input implements a
5402 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5403 /// operation to match.
5404 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5405 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5406 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5407 /// arithmetic sub.
5408 ///
5409 /// This function only analyzes elements of \p N whose indices are
5410 /// in range [BaseIdx, LastIdx).
5411 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5412                               SelectionDAG &DAG,
5413                               unsigned BaseIdx, unsigned LastIdx,
5414                               SDValue &V0, SDValue &V1) {
5415   EVT VT = N->getValueType(0);
5416
5417   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5418   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5419          "Invalid Vector in input!");
5420
5421   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5422   bool CanFold = true;
5423   unsigned ExpectedVExtractIdx = BaseIdx;
5424   unsigned NumElts = LastIdx - BaseIdx;
5425   V0 = DAG.getUNDEF(VT);
5426   V1 = DAG.getUNDEF(VT);
5427
5428   // Check if N implements a horizontal binop.
5429   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5430     SDValue Op = N->getOperand(i + BaseIdx);
5431
5432     // Skip UNDEFs.
5433     if (Op->getOpcode() == ISD::UNDEF) {
5434       // Update the expected vector extract index.
5435       if (i * 2 == NumElts)
5436         ExpectedVExtractIdx = BaseIdx;
5437       ExpectedVExtractIdx += 2;
5438       continue;
5439     }
5440
5441     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5442
5443     if (!CanFold)
5444       break;
5445
5446     SDValue Op0 = Op.getOperand(0);
5447     SDValue Op1 = Op.getOperand(1);
5448
5449     // Try to match the following pattern:
5450     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5451     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5452         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5453         Op0.getOperand(0) == Op1.getOperand(0) &&
5454         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5455         isa<ConstantSDNode>(Op1.getOperand(1)));
5456     if (!CanFold)
5457       break;
5458
5459     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5460     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5461
5462     if (i * 2 < NumElts) {
5463       if (V0.getOpcode() == ISD::UNDEF) {
5464         V0 = Op0.getOperand(0);
5465         if (V0.getValueType() != VT)
5466           return false;
5467       }
5468     } else {
5469       if (V1.getOpcode() == ISD::UNDEF) {
5470         V1 = Op0.getOperand(0);
5471         if (V1.getValueType() != VT)
5472           return false;
5473       }
5474       if (i * 2 == NumElts)
5475         ExpectedVExtractIdx = BaseIdx;
5476     }
5477
5478     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5479     if (I0 == ExpectedVExtractIdx)
5480       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5481     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5482       // Try to match the following dag sequence:
5483       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5484       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5485     } else
5486       CanFold = false;
5487
5488     ExpectedVExtractIdx += 2;
5489   }
5490
5491   return CanFold;
5492 }
5493
5494 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5495 /// a concat_vector.
5496 ///
5497 /// This is a helper function of LowerToHorizontalOp().
5498 /// This function expects two 256-bit vectors called V0 and V1.
5499 /// At first, each vector is split into two separate 128-bit vectors.
5500 /// Then, the resulting 128-bit vectors are used to implement two
5501 /// horizontal binary operations.
5502 ///
5503 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5504 ///
5505 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5506 /// the two new horizontal binop.
5507 /// When Mode is set, the first horizontal binop dag node would take as input
5508 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5509 /// horizontal binop dag node would take as input the lower 128-bit of V1
5510 /// and the upper 128-bit of V1.
5511 ///   Example:
5512 ///     HADD V0_LO, V0_HI
5513 ///     HADD V1_LO, V1_HI
5514 ///
5515 /// Otherwise, the first horizontal binop dag node takes as input the lower
5516 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5517 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5518 ///   Example:
5519 ///     HADD V0_LO, V1_LO
5520 ///     HADD V0_HI, V1_HI
5521 ///
5522 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5523 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5524 /// the upper 128-bits of the result.
5525 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5526                                      SDLoc DL, SelectionDAG &DAG,
5527                                      unsigned X86Opcode, bool Mode,
5528                                      bool isUndefLO, bool isUndefHI) {
5529   EVT VT = V0.getValueType();
5530   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5531          "Invalid nodes in input!");
5532
5533   unsigned NumElts = VT.getVectorNumElements();
5534   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5535   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5536   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5537   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5538   EVT NewVT = V0_LO.getValueType();
5539
5540   SDValue LO = DAG.getUNDEF(NewVT);
5541   SDValue HI = DAG.getUNDEF(NewVT);
5542
5543   if (Mode) {
5544     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5545     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5546       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5547     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5548       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5549   } else {
5550     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5551     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5552                        V1_LO->getOpcode() != ISD::UNDEF))
5553       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5554
5555     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5556                        V1_HI->getOpcode() != ISD::UNDEF))
5557       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5558   }
5559
5560   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5561 }
5562
5563 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5564 /// node.
5565 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5566                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5567   EVT VT = BV->getValueType(0);
5568   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5569       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5570     return SDValue();
5571
5572   SDLoc DL(BV);
5573   unsigned NumElts = VT.getVectorNumElements();
5574   SDValue InVec0 = DAG.getUNDEF(VT);
5575   SDValue InVec1 = DAG.getUNDEF(VT);
5576
5577   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5578           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5579
5580   // Odd-numbered elements in the input build vector are obtained from
5581   // adding two integer/float elements.
5582   // Even-numbered elements in the input build vector are obtained from
5583   // subtracting two integer/float elements.
5584   unsigned ExpectedOpcode = ISD::FSUB;
5585   unsigned NextExpectedOpcode = ISD::FADD;
5586   bool AddFound = false;
5587   bool SubFound = false;
5588
5589   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5590     SDValue Op = BV->getOperand(i);
5591
5592     // Skip 'undef' values.
5593     unsigned Opcode = Op.getOpcode();
5594     if (Opcode == ISD::UNDEF) {
5595       std::swap(ExpectedOpcode, NextExpectedOpcode);
5596       continue;
5597     }
5598
5599     // Early exit if we found an unexpected opcode.
5600     if (Opcode != ExpectedOpcode)
5601       return SDValue();
5602
5603     SDValue Op0 = Op.getOperand(0);
5604     SDValue Op1 = Op.getOperand(1);
5605
5606     // Try to match the following pattern:
5607     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5608     // Early exit if we cannot match that sequence.
5609     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5610         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5611         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5612         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5613         Op0.getOperand(1) != Op1.getOperand(1))
5614       return SDValue();
5615
5616     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5617     if (I0 != i)
5618       return SDValue();
5619
5620     // We found a valid add/sub node. Update the information accordingly.
5621     if (i & 1)
5622       AddFound = true;
5623     else
5624       SubFound = true;
5625
5626     // Update InVec0 and InVec1.
5627     if (InVec0.getOpcode() == ISD::UNDEF) {
5628       InVec0 = Op0.getOperand(0);
5629       if (InVec0.getValueType() != VT)
5630         return SDValue();
5631     }
5632     if (InVec1.getOpcode() == ISD::UNDEF) {
5633       InVec1 = Op1.getOperand(0);
5634       if (InVec1.getValueType() != VT)
5635         return SDValue();
5636     }
5637
5638     // Make sure that operands in input to each add/sub node always
5639     // come from a same pair of vectors.
5640     if (InVec0 != Op0.getOperand(0)) {
5641       if (ExpectedOpcode == ISD::FSUB)
5642         return SDValue();
5643
5644       // FADD is commutable. Try to commute the operands
5645       // and then test again.
5646       std::swap(Op0, Op1);
5647       if (InVec0 != Op0.getOperand(0))
5648         return SDValue();
5649     }
5650
5651     if (InVec1 != Op1.getOperand(0))
5652       return SDValue();
5653
5654     // Update the pair of expected opcodes.
5655     std::swap(ExpectedOpcode, NextExpectedOpcode);
5656   }
5657
5658   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5659   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5660       InVec1.getOpcode() != ISD::UNDEF)
5661     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5662
5663   return SDValue();
5664 }
5665
5666 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5667 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5668                                    const X86Subtarget *Subtarget,
5669                                    SelectionDAG &DAG) {
5670   EVT VT = BV->getValueType(0);
5671   unsigned NumElts = VT.getVectorNumElements();
5672   unsigned NumUndefsLO = 0;
5673   unsigned NumUndefsHI = 0;
5674   unsigned Half = NumElts/2;
5675
5676   // Count the number of UNDEF operands in the build_vector in input.
5677   for (unsigned i = 0, e = Half; i != e; ++i)
5678     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5679       NumUndefsLO++;
5680
5681   for (unsigned i = Half, e = NumElts; i != e; ++i)
5682     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5683       NumUndefsHI++;
5684
5685   // Early exit if this is either a build_vector of all UNDEFs or all the
5686   // operands but one are UNDEF.
5687   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5688     return SDValue();
5689
5690   SDLoc DL(BV);
5691   SDValue InVec0, InVec1;
5692   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5693     // Try to match an SSE3 float HADD/HSUB.
5694     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5695       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5696
5697     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5698       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5699   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5700     // Try to match an SSSE3 integer HADD/HSUB.
5701     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5702       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5703
5704     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5705       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5706   }
5707
5708   if (!Subtarget->hasAVX())
5709     return SDValue();
5710
5711   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5712     // Try to match an AVX horizontal add/sub of packed single/double
5713     // precision floating point values from 256-bit vectors.
5714     SDValue InVec2, InVec3;
5715     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5716         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5717         ((InVec0.getOpcode() == ISD::UNDEF ||
5718           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5719         ((InVec1.getOpcode() == ISD::UNDEF ||
5720           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5721       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5722
5723     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5724         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5725         ((InVec0.getOpcode() == ISD::UNDEF ||
5726           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5727         ((InVec1.getOpcode() == ISD::UNDEF ||
5728           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5729       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5730   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5731     // Try to match an AVX2 horizontal add/sub of signed integers.
5732     SDValue InVec2, InVec3;
5733     unsigned X86Opcode;
5734     bool CanFold = true;
5735
5736     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5737         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5738         ((InVec0.getOpcode() == ISD::UNDEF ||
5739           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5740         ((InVec1.getOpcode() == ISD::UNDEF ||
5741           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5742       X86Opcode = X86ISD::HADD;
5743     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5744         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5745         ((InVec0.getOpcode() == ISD::UNDEF ||
5746           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5747         ((InVec1.getOpcode() == ISD::UNDEF ||
5748           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5749       X86Opcode = X86ISD::HSUB;
5750     else
5751       CanFold = false;
5752
5753     if (CanFold) {
5754       // Fold this build_vector into a single horizontal add/sub.
5755       // Do this only if the target has AVX2.
5756       if (Subtarget->hasAVX2())
5757         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5758
5759       // Do not try to expand this build_vector into a pair of horizontal
5760       // add/sub if we can emit a pair of scalar add/sub.
5761       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5762         return SDValue();
5763
5764       // Convert this build_vector into a pair of horizontal binop followed by
5765       // a concat vector.
5766       bool isUndefLO = NumUndefsLO == Half;
5767       bool isUndefHI = NumUndefsHI == Half;
5768       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5769                                    isUndefLO, isUndefHI);
5770     }
5771   }
5772
5773   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5774        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5775     unsigned X86Opcode;
5776     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5777       X86Opcode = X86ISD::HADD;
5778     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5779       X86Opcode = X86ISD::HSUB;
5780     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5781       X86Opcode = X86ISD::FHADD;
5782     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5783       X86Opcode = X86ISD::FHSUB;
5784     else
5785       return SDValue();
5786
5787     // Don't try to expand this build_vector into a pair of horizontal add/sub
5788     // if we can simply emit a pair of scalar add/sub.
5789     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5790       return SDValue();
5791
5792     // Convert this build_vector into two horizontal add/sub followed by
5793     // a concat vector.
5794     bool isUndefLO = NumUndefsLO == Half;
5795     bool isUndefHI = NumUndefsHI == Half;
5796     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5797                                  isUndefLO, isUndefHI);
5798   }
5799
5800   return SDValue();
5801 }
5802
5803 SDValue
5804 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5805   SDLoc dl(Op);
5806
5807   MVT VT = Op.getSimpleValueType();
5808   MVT ExtVT = VT.getVectorElementType();
5809   unsigned NumElems = Op.getNumOperands();
5810
5811   // Generate vectors for predicate vectors.
5812   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5813     return LowerBUILD_VECTORvXi1(Op, DAG);
5814
5815   // Vectors containing all zeros can be matched by pxor and xorps later
5816   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5817     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5818     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5819     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5820       return Op;
5821
5822     return getZeroVector(VT, Subtarget, DAG, dl);
5823   }
5824
5825   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5826   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5827   // vpcmpeqd on 256-bit vectors.
5828   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5829     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5830       return Op;
5831
5832     if (!VT.is512BitVector())
5833       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5834   }
5835
5836   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5837   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5838     return AddSub;
5839   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5840     return HorizontalOp;
5841   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5842     return Broadcast;
5843
5844   unsigned EVTBits = ExtVT.getSizeInBits();
5845
5846   unsigned NumZero  = 0;
5847   unsigned NumNonZero = 0;
5848   unsigned NonZeros = 0;
5849   bool IsAllConstants = true;
5850   SmallSet<SDValue, 8> Values;
5851   for (unsigned i = 0; i < NumElems; ++i) {
5852     SDValue Elt = Op.getOperand(i);
5853     if (Elt.getOpcode() == ISD::UNDEF)
5854       continue;
5855     Values.insert(Elt);
5856     if (Elt.getOpcode() != ISD::Constant &&
5857         Elt.getOpcode() != ISD::ConstantFP)
5858       IsAllConstants = false;
5859     if (X86::isZeroNode(Elt))
5860       NumZero++;
5861     else {
5862       NonZeros |= (1 << i);
5863       NumNonZero++;
5864     }
5865   }
5866
5867   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5868   if (NumNonZero == 0)
5869     return DAG.getUNDEF(VT);
5870
5871   // Special case for single non-zero, non-undef, element.
5872   if (NumNonZero == 1) {
5873     unsigned Idx = countTrailingZeros(NonZeros);
5874     SDValue Item = Op.getOperand(Idx);
5875
5876     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5877     // the value are obviously zero, truncate the value to i32 and do the
5878     // insertion that way.  Only do this if the value is non-constant or if the
5879     // value is a constant being inserted into element 0.  It is cheaper to do
5880     // a constant pool load than it is to do a movd + shuffle.
5881     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5882         (!IsAllConstants || Idx == 0)) {
5883       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5884         // Handle SSE only.
5885         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5886         EVT VecVT = MVT::v4i32;
5887
5888         // Truncate the value (which may itself be a constant) to i32, and
5889         // convert it to a vector with movd (S2V+shuffle to zero extend).
5890         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5891         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5892         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5893                                       Item, Idx * 2, true, Subtarget, DAG));
5894       }
5895     }
5896
5897     // If we have a constant or non-constant insertion into the low element of
5898     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5899     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5900     // depending on what the source datatype is.
5901     if (Idx == 0) {
5902       if (NumZero == 0)
5903         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5904
5905       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5906           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5907         if (VT.is512BitVector()) {
5908           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5909           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5910                              Item, DAG.getIntPtrConstant(0, dl));
5911         }
5912         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5913                "Expected an SSE value type!");
5914         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5915         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5916         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5917       }
5918
5919       // We can't directly insert an i8 or i16 into a vector, so zero extend
5920       // it to i32 first.
5921       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5922         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5923         if (VT.is256BitVector()) {
5924           if (Subtarget->hasAVX()) {
5925             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5926             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5927           } else {
5928             // Without AVX, we need to extend to a 128-bit vector and then
5929             // insert into the 256-bit vector.
5930             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5931             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5932             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5933           }
5934         } else {
5935           assert(VT.is128BitVector() && "Expected an SSE value type!");
5936           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5937           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5938         }
5939         return DAG.getBitcast(VT, Item);
5940       }
5941     }
5942
5943     // Is it a vector logical left shift?
5944     if (NumElems == 2 && Idx == 1 &&
5945         X86::isZeroNode(Op.getOperand(0)) &&
5946         !X86::isZeroNode(Op.getOperand(1))) {
5947       unsigned NumBits = VT.getSizeInBits();
5948       return getVShift(true, VT,
5949                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5950                                    VT, Op.getOperand(1)),
5951                        NumBits/2, DAG, *this, dl);
5952     }
5953
5954     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5955       return SDValue();
5956
5957     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5958     // is a non-constant being inserted into an element other than the low one,
5959     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5960     // movd/movss) to move this into the low element, then shuffle it into
5961     // place.
5962     if (EVTBits == 32) {
5963       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5964       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5965     }
5966   }
5967
5968   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5969   if (Values.size() == 1) {
5970     if (EVTBits == 32) {
5971       // Instead of a shuffle like this:
5972       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5973       // Check if it's possible to issue this instead.
5974       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5975       unsigned Idx = countTrailingZeros(NonZeros);
5976       SDValue Item = Op.getOperand(Idx);
5977       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5978         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5979     }
5980     return SDValue();
5981   }
5982
5983   // A vector full of immediates; various special cases are already
5984   // handled, so this is best done with a single constant-pool load.
5985   if (IsAllConstants)
5986     return SDValue();
5987
5988   // For AVX-length vectors, see if we can use a vector load to get all of the
5989   // elements, otherwise build the individual 128-bit pieces and use
5990   // shuffles to put them in place.
5991   if (VT.is256BitVector() || VT.is512BitVector()) {
5992     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5993
5994     // Check for a build vector of consecutive loads.
5995     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5996       return LD;
5997
5998     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5999
6000     // Build both the lower and upper subvector.
6001     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6002                                 makeArrayRef(&V[0], NumElems/2));
6003     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6004                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6005
6006     // Recreate the wider vector with the lower and upper part.
6007     if (VT.is256BitVector())
6008       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6009     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6010   }
6011
6012   // Let legalizer expand 2-wide build_vectors.
6013   if (EVTBits == 64) {
6014     if (NumNonZero == 1) {
6015       // One half is zero or undef.
6016       unsigned Idx = countTrailingZeros(NonZeros);
6017       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6018                                  Op.getOperand(Idx));
6019       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6020     }
6021     return SDValue();
6022   }
6023
6024   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6025   if (EVTBits == 8 && NumElems == 16)
6026     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6027                                         Subtarget, *this))
6028       return V;
6029
6030   if (EVTBits == 16 && NumElems == 8)
6031     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6032                                       Subtarget, *this))
6033       return V;
6034
6035   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6036   if (EVTBits == 32 && NumElems == 4)
6037     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6038       return V;
6039
6040   // If element VT is == 32 bits, turn it into a number of shuffles.
6041   SmallVector<SDValue, 8> V(NumElems);
6042   if (NumElems == 4 && NumZero > 0) {
6043     for (unsigned i = 0; i < 4; ++i) {
6044       bool isZero = !(NonZeros & (1 << i));
6045       if (isZero)
6046         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6047       else
6048         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6049     }
6050
6051     for (unsigned i = 0; i < 2; ++i) {
6052       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6053         default: break;
6054         case 0:
6055           V[i] = V[i*2];  // Must be a zero vector.
6056           break;
6057         case 1:
6058           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6059           break;
6060         case 2:
6061           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6062           break;
6063         case 3:
6064           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6065           break;
6066       }
6067     }
6068
6069     bool Reverse1 = (NonZeros & 0x3) == 2;
6070     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6071     int MaskVec[] = {
6072       Reverse1 ? 1 : 0,
6073       Reverse1 ? 0 : 1,
6074       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6075       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6076     };
6077     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6078   }
6079
6080   if (Values.size() > 1 && VT.is128BitVector()) {
6081     // Check for a build vector of consecutive loads.
6082     for (unsigned i = 0; i < NumElems; ++i)
6083       V[i] = Op.getOperand(i);
6084
6085     // Check for elements which are consecutive loads.
6086     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6087       return LD;
6088
6089     // Check for a build vector from mostly shuffle plus few inserting.
6090     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6091       return Sh;
6092
6093     // For SSE 4.1, use insertps to put the high elements into the low element.
6094     if (Subtarget->hasSSE41()) {
6095       SDValue Result;
6096       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6097         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6098       else
6099         Result = DAG.getUNDEF(VT);
6100
6101       for (unsigned i = 1; i < NumElems; ++i) {
6102         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6103         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6104                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6105       }
6106       return Result;
6107     }
6108
6109     // Otherwise, expand into a number of unpckl*, start by extending each of
6110     // our (non-undef) elements to the full vector width with the element in the
6111     // bottom slot of the vector (which generates no code for SSE).
6112     for (unsigned i = 0; i < NumElems; ++i) {
6113       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6114         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6115       else
6116         V[i] = DAG.getUNDEF(VT);
6117     }
6118
6119     // Next, we iteratively mix elements, e.g. for v4f32:
6120     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6121     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6122     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6123     unsigned EltStride = NumElems >> 1;
6124     while (EltStride != 0) {
6125       for (unsigned i = 0; i < EltStride; ++i) {
6126         // If V[i+EltStride] is undef and this is the first round of mixing,
6127         // then it is safe to just drop this shuffle: V[i] is already in the
6128         // right place, the one element (since it's the first round) being
6129         // inserted as undef can be dropped.  This isn't safe for successive
6130         // rounds because they will permute elements within both vectors.
6131         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6132             EltStride == NumElems/2)
6133           continue;
6134
6135         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6136       }
6137       EltStride >>= 1;
6138     }
6139     return V[0];
6140   }
6141   return SDValue();
6142 }
6143
6144 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6145 // to create 256-bit vectors from two other 128-bit ones.
6146 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6147   SDLoc dl(Op);
6148   MVT ResVT = Op.getSimpleValueType();
6149
6150   assert((ResVT.is256BitVector() ||
6151           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6152
6153   SDValue V1 = Op.getOperand(0);
6154   SDValue V2 = Op.getOperand(1);
6155   unsigned NumElems = ResVT.getVectorNumElements();
6156   if (ResVT.is256BitVector())
6157     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6158
6159   if (Op.getNumOperands() == 4) {
6160     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6161                                 ResVT.getVectorNumElements()/2);
6162     SDValue V3 = Op.getOperand(2);
6163     SDValue V4 = Op.getOperand(3);
6164     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6165       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6166   }
6167   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6168 }
6169
6170 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6171                                        const X86Subtarget *Subtarget,
6172                                        SelectionDAG & DAG) {
6173   SDLoc dl(Op);
6174   MVT ResVT = Op.getSimpleValueType();
6175   unsigned NumOfOperands = Op.getNumOperands();
6176
6177   assert(isPowerOf2_32(NumOfOperands) &&
6178          "Unexpected number of operands in CONCAT_VECTORS");
6179
6180   if (NumOfOperands > 2) {
6181     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6182                                   ResVT.getVectorNumElements()/2);
6183     SmallVector<SDValue, 2> Ops;
6184     for (unsigned i = 0; i < NumOfOperands/2; i++)
6185       Ops.push_back(Op.getOperand(i));
6186     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6187     Ops.clear();
6188     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6189       Ops.push_back(Op.getOperand(i));
6190     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6191     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6192   }
6193
6194   SDValue V1 = Op.getOperand(0);
6195   SDValue V2 = Op.getOperand(1);
6196   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6197   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6198
6199   if (IsZeroV1 && IsZeroV2)
6200     return getZeroVector(ResVT, Subtarget, DAG, dl);
6201
6202   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6203   SDValue Undef = DAG.getUNDEF(ResVT);
6204   unsigned NumElems = ResVT.getVectorNumElements();
6205   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6206
6207   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6208   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6209   if (IsZeroV1)
6210     return V2;
6211
6212   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6213   // Zero the upper bits of V1
6214   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6215   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6216   if (IsZeroV2)
6217     return V1;
6218   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6219 }
6220
6221 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6222                                    const X86Subtarget *Subtarget,
6223                                    SelectionDAG &DAG) {
6224   MVT VT = Op.getSimpleValueType();
6225   if (VT.getVectorElementType() == MVT::i1)
6226     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6227
6228   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6229          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6230           Op.getNumOperands() == 4)));
6231
6232   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6233   // from two other 128-bit ones.
6234
6235   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6236   return LowerAVXCONCAT_VECTORS(Op, DAG);
6237 }
6238
6239
6240 //===----------------------------------------------------------------------===//
6241 // Vector shuffle lowering
6242 //
6243 // This is an experimental code path for lowering vector shuffles on x86. It is
6244 // designed to handle arbitrary vector shuffles and blends, gracefully
6245 // degrading performance as necessary. It works hard to recognize idiomatic
6246 // shuffles and lower them to optimal instruction patterns without leaving
6247 // a framework that allows reasonably efficient handling of all vector shuffle
6248 // patterns.
6249 //===----------------------------------------------------------------------===//
6250
6251 /// \brief Tiny helper function to identify a no-op mask.
6252 ///
6253 /// This is a somewhat boring predicate function. It checks whether the mask
6254 /// array input, which is assumed to be a single-input shuffle mask of the kind
6255 /// used by the X86 shuffle instructions (not a fully general
6256 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6257 /// in-place shuffle are 'no-op's.
6258 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6259   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6260     if (Mask[i] != -1 && Mask[i] != i)
6261       return false;
6262   return true;
6263 }
6264
6265 /// \brief Helper function to classify a mask as a single-input mask.
6266 ///
6267 /// This isn't a generic single-input test because in the vector shuffle
6268 /// lowering we canonicalize single inputs to be the first input operand. This
6269 /// means we can more quickly test for a single input by only checking whether
6270 /// an input from the second operand exists. We also assume that the size of
6271 /// mask corresponds to the size of the input vectors which isn't true in the
6272 /// fully general case.
6273 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6274   for (int M : Mask)
6275     if (M >= (int)Mask.size())
6276       return false;
6277   return true;
6278 }
6279
6280 /// \brief Test whether there are elements crossing 128-bit lanes in this
6281 /// shuffle mask.
6282 ///
6283 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6284 /// and we routinely test for these.
6285 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6286   int LaneSize = 128 / VT.getScalarSizeInBits();
6287   int Size = Mask.size();
6288   for (int i = 0; i < Size; ++i)
6289     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6290       return true;
6291   return false;
6292 }
6293
6294 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6295 ///
6296 /// This checks a shuffle mask to see if it is performing the same
6297 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6298 /// that it is also not lane-crossing. It may however involve a blend from the
6299 /// same lane of a second vector.
6300 ///
6301 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6302 /// non-trivial to compute in the face of undef lanes. The representation is
6303 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6304 /// entries from both V1 and V2 inputs to the wider mask.
6305 static bool
6306 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6307                                 SmallVectorImpl<int> &RepeatedMask) {
6308   int LaneSize = 128 / VT.getScalarSizeInBits();
6309   RepeatedMask.resize(LaneSize, -1);
6310   int Size = Mask.size();
6311   for (int i = 0; i < Size; ++i) {
6312     if (Mask[i] < 0)
6313       continue;
6314     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6315       // This entry crosses lanes, so there is no way to model this shuffle.
6316       return false;
6317
6318     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6319     if (RepeatedMask[i % LaneSize] == -1)
6320       // This is the first non-undef entry in this slot of a 128-bit lane.
6321       RepeatedMask[i % LaneSize] =
6322           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6323     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6324       // Found a mismatch with the repeated mask.
6325       return false;
6326   }
6327   return true;
6328 }
6329
6330 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6331 /// arguments.
6332 ///
6333 /// This is a fast way to test a shuffle mask against a fixed pattern:
6334 ///
6335 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6336 ///
6337 /// It returns true if the mask is exactly as wide as the argument list, and
6338 /// each element of the mask is either -1 (signifying undef) or the value given
6339 /// in the argument.
6340 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6341                                 ArrayRef<int> ExpectedMask) {
6342   if (Mask.size() != ExpectedMask.size())
6343     return false;
6344
6345   int Size = Mask.size();
6346
6347   // If the values are build vectors, we can look through them to find
6348   // equivalent inputs that make the shuffles equivalent.
6349   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6350   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6351
6352   for (int i = 0; i < Size; ++i)
6353     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6354       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6355       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6356       if (!MaskBV || !ExpectedBV ||
6357           MaskBV->getOperand(Mask[i] % Size) !=
6358               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6359         return false;
6360     }
6361
6362   return true;
6363 }
6364
6365 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6366 ///
6367 /// This helper function produces an 8-bit shuffle immediate corresponding to
6368 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6369 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6370 /// example.
6371 ///
6372 /// NB: We rely heavily on "undef" masks preserving the input lane.
6373 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6374                                           SelectionDAG &DAG) {
6375   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6376   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6377   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6378   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6379   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6380
6381   unsigned Imm = 0;
6382   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6383   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6384   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6385   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6386   return DAG.getConstant(Imm, DL, MVT::i8);
6387 }
6388
6389 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6390 ///
6391 /// This is used as a fallback approach when first class blend instructions are
6392 /// unavailable. Currently it is only suitable for integer vectors, but could
6393 /// be generalized for floating point vectors if desirable.
6394 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6395                                             SDValue V2, ArrayRef<int> Mask,
6396                                             SelectionDAG &DAG) {
6397   assert(VT.isInteger() && "Only supports integer vector types!");
6398   MVT EltVT = VT.getScalarType();
6399   int NumEltBits = EltVT.getSizeInBits();
6400   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6401   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6402                                     EltVT);
6403   SmallVector<SDValue, 16> MaskOps;
6404   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6405     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6406       return SDValue(); // Shuffled input!
6407     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6408   }
6409
6410   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6411   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6412   // We have to cast V2 around.
6413   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6414   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6415                                       DAG.getBitcast(MaskVT, V1Mask),
6416                                       DAG.getBitcast(MaskVT, V2)));
6417   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6418 }
6419
6420 /// \brief Try to emit a blend instruction for a shuffle.
6421 ///
6422 /// This doesn't do any checks for the availability of instructions for blending
6423 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6424 /// be matched in the backend with the type given. What it does check for is
6425 /// that the shuffle mask is in fact a blend.
6426 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6427                                          SDValue V2, ArrayRef<int> Mask,
6428                                          const X86Subtarget *Subtarget,
6429                                          SelectionDAG &DAG) {
6430   unsigned BlendMask = 0;
6431   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6432     if (Mask[i] >= Size) {
6433       if (Mask[i] != i + Size)
6434         return SDValue(); // Shuffled V2 input!
6435       BlendMask |= 1u << i;
6436       continue;
6437     }
6438     if (Mask[i] >= 0 && Mask[i] != i)
6439       return SDValue(); // Shuffled V1 input!
6440   }
6441   switch (VT.SimpleTy) {
6442   case MVT::v2f64:
6443   case MVT::v4f32:
6444   case MVT::v4f64:
6445   case MVT::v8f32:
6446     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6447                        DAG.getConstant(BlendMask, DL, MVT::i8));
6448
6449   case MVT::v4i64:
6450   case MVT::v8i32:
6451     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6452     // FALLTHROUGH
6453   case MVT::v2i64:
6454   case MVT::v4i32:
6455     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6456     // that instruction.
6457     if (Subtarget->hasAVX2()) {
6458       // Scale the blend by the number of 32-bit dwords per element.
6459       int Scale =  VT.getScalarSizeInBits() / 32;
6460       BlendMask = 0;
6461       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6462         if (Mask[i] >= Size)
6463           for (int j = 0; j < Scale; ++j)
6464             BlendMask |= 1u << (i * Scale + j);
6465
6466       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6467       V1 = DAG.getBitcast(BlendVT, V1);
6468       V2 = DAG.getBitcast(BlendVT, V2);
6469       return DAG.getBitcast(
6470           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6471                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6472     }
6473     // FALLTHROUGH
6474   case MVT::v8i16: {
6475     // For integer shuffles we need to expand the mask and cast the inputs to
6476     // v8i16s prior to blending.
6477     int Scale = 8 / VT.getVectorNumElements();
6478     BlendMask = 0;
6479     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6480       if (Mask[i] >= Size)
6481         for (int j = 0; j < Scale; ++j)
6482           BlendMask |= 1u << (i * Scale + j);
6483
6484     V1 = DAG.getBitcast(MVT::v8i16, V1);
6485     V2 = DAG.getBitcast(MVT::v8i16, V2);
6486     return DAG.getBitcast(VT,
6487                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6488                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6489   }
6490
6491   case MVT::v16i16: {
6492     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6493     SmallVector<int, 8> RepeatedMask;
6494     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6495       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6496       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6497       BlendMask = 0;
6498       for (int i = 0; i < 8; ++i)
6499         if (RepeatedMask[i] >= 16)
6500           BlendMask |= 1u << i;
6501       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6502                          DAG.getConstant(BlendMask, DL, MVT::i8));
6503     }
6504   }
6505     // FALLTHROUGH
6506   case MVT::v16i8:
6507   case MVT::v32i8: {
6508     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6509            "256-bit byte-blends require AVX2 support!");
6510
6511     // Scale the blend by the number of bytes per element.
6512     int Scale = VT.getScalarSizeInBits() / 8;
6513
6514     // This form of blend is always done on bytes. Compute the byte vector
6515     // type.
6516     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6517
6518     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6519     // mix of LLVM's code generator and the x86 backend. We tell the code
6520     // generator that boolean values in the elements of an x86 vector register
6521     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6522     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6523     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6524     // of the element (the remaining are ignored) and 0 in that high bit would
6525     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6526     // the LLVM model for boolean values in vector elements gets the relevant
6527     // bit set, it is set backwards and over constrained relative to x86's
6528     // actual model.
6529     SmallVector<SDValue, 32> VSELECTMask;
6530     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6531       for (int j = 0; j < Scale; ++j)
6532         VSELECTMask.push_back(
6533             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6534                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6535                                           MVT::i8));
6536
6537     V1 = DAG.getBitcast(BlendVT, V1);
6538     V2 = DAG.getBitcast(BlendVT, V2);
6539     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6540                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6541                                                       BlendVT, VSELECTMask),
6542                                           V1, V2));
6543   }
6544
6545   default:
6546     llvm_unreachable("Not a supported integer vector type!");
6547   }
6548 }
6549
6550 /// \brief Try to lower as a blend of elements from two inputs followed by
6551 /// a single-input permutation.
6552 ///
6553 /// This matches the pattern where we can blend elements from two inputs and
6554 /// then reduce the shuffle to a single-input permutation.
6555 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6556                                                    SDValue V2,
6557                                                    ArrayRef<int> Mask,
6558                                                    SelectionDAG &DAG) {
6559   // We build up the blend mask while checking whether a blend is a viable way
6560   // to reduce the shuffle.
6561   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6562   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6563
6564   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6565     if (Mask[i] < 0)
6566       continue;
6567
6568     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6569
6570     if (BlendMask[Mask[i] % Size] == -1)
6571       BlendMask[Mask[i] % Size] = Mask[i];
6572     else if (BlendMask[Mask[i] % Size] != Mask[i])
6573       return SDValue(); // Can't blend in the needed input!
6574
6575     PermuteMask[i] = Mask[i] % Size;
6576   }
6577
6578   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6579   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6580 }
6581
6582 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6583 /// blends and permutes.
6584 ///
6585 /// This matches the extremely common pattern for handling combined
6586 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6587 /// operations. It will try to pick the best arrangement of shuffles and
6588 /// blends.
6589 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6590                                                           SDValue V1,
6591                                                           SDValue V2,
6592                                                           ArrayRef<int> Mask,
6593                                                           SelectionDAG &DAG) {
6594   // Shuffle the input elements into the desired positions in V1 and V2 and
6595   // blend them together.
6596   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6597   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6598   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6599   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6600     if (Mask[i] >= 0 && Mask[i] < Size) {
6601       V1Mask[i] = Mask[i];
6602       BlendMask[i] = i;
6603     } else if (Mask[i] >= Size) {
6604       V2Mask[i] = Mask[i] - Size;
6605       BlendMask[i] = i + Size;
6606     }
6607
6608   // Try to lower with the simpler initial blend strategy unless one of the
6609   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6610   // shuffle may be able to fold with a load or other benefit. However, when
6611   // we'll have to do 2x as many shuffles in order to achieve this, blending
6612   // first is a better strategy.
6613   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6614     if (SDValue BlendPerm =
6615             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6616       return BlendPerm;
6617
6618   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6619   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6620   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6621 }
6622
6623 /// \brief Try to lower a vector shuffle as a byte rotation.
6624 ///
6625 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6626 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6627 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6628 /// try to generically lower a vector shuffle through such an pattern. It
6629 /// does not check for the profitability of lowering either as PALIGNR or
6630 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6631 /// This matches shuffle vectors that look like:
6632 ///
6633 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6634 ///
6635 /// Essentially it concatenates V1 and V2, shifts right by some number of
6636 /// elements, and takes the low elements as the result. Note that while this is
6637 /// specified as a *right shift* because x86 is little-endian, it is a *left
6638 /// rotate* of the vector lanes.
6639 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6640                                               SDValue V2,
6641                                               ArrayRef<int> Mask,
6642                                               const X86Subtarget *Subtarget,
6643                                               SelectionDAG &DAG) {
6644   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6645
6646   int NumElts = Mask.size();
6647   int NumLanes = VT.getSizeInBits() / 128;
6648   int NumLaneElts = NumElts / NumLanes;
6649
6650   // We need to detect various ways of spelling a rotation:
6651   //   [11, 12, 13, 14, 15,  0,  1,  2]
6652   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6653   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6654   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6655   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6656   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6657   int Rotation = 0;
6658   SDValue Lo, Hi;
6659   for (int l = 0; l < NumElts; l += NumLaneElts) {
6660     for (int i = 0; i < NumLaneElts; ++i) {
6661       if (Mask[l + i] == -1)
6662         continue;
6663       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6664
6665       // Get the mod-Size index and lane correct it.
6666       int LaneIdx = (Mask[l + i] % NumElts) - l;
6667       // Make sure it was in this lane.
6668       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6669         return SDValue();
6670
6671       // Determine where a rotated vector would have started.
6672       int StartIdx = i - LaneIdx;
6673       if (StartIdx == 0)
6674         // The identity rotation isn't interesting, stop.
6675         return SDValue();
6676
6677       // If we found the tail of a vector the rotation must be the missing
6678       // front. If we found the head of a vector, it must be how much of the
6679       // head.
6680       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6681
6682       if (Rotation == 0)
6683         Rotation = CandidateRotation;
6684       else if (Rotation != CandidateRotation)
6685         // The rotations don't match, so we can't match this mask.
6686         return SDValue();
6687
6688       // Compute which value this mask is pointing at.
6689       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6690
6691       // Compute which of the two target values this index should be assigned
6692       // to. This reflects whether the high elements are remaining or the low
6693       // elements are remaining.
6694       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6695
6696       // Either set up this value if we've not encountered it before, or check
6697       // that it remains consistent.
6698       if (!TargetV)
6699         TargetV = MaskV;
6700       else if (TargetV != MaskV)
6701         // This may be a rotation, but it pulls from the inputs in some
6702         // unsupported interleaving.
6703         return SDValue();
6704     }
6705   }
6706
6707   // Check that we successfully analyzed the mask, and normalize the results.
6708   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6709   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6710   if (!Lo)
6711     Lo = Hi;
6712   else if (!Hi)
6713     Hi = Lo;
6714
6715   // The actual rotate instruction rotates bytes, so we need to scale the
6716   // rotation based on how many bytes are in the vector lane.
6717   int Scale = 16 / NumLaneElts;
6718
6719   // SSSE3 targets can use the palignr instruction.
6720   if (Subtarget->hasSSSE3()) {
6721     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6722     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6723     Lo = DAG.getBitcast(AlignVT, Lo);
6724     Hi = DAG.getBitcast(AlignVT, Hi);
6725
6726     return DAG.getBitcast(
6727         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6728                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6729   }
6730
6731   assert(VT.getSizeInBits() == 128 &&
6732          "Rotate-based lowering only supports 128-bit lowering!");
6733   assert(Mask.size() <= 16 &&
6734          "Can shuffle at most 16 bytes in a 128-bit vector!");
6735
6736   // Default SSE2 implementation
6737   int LoByteShift = 16 - Rotation * Scale;
6738   int HiByteShift = Rotation * Scale;
6739
6740   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6741   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6742   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6743
6744   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6745                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6746   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6747                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6748   return DAG.getBitcast(VT,
6749                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6750 }
6751
6752 /// \brief Compute whether each element of a shuffle is zeroable.
6753 ///
6754 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6755 /// Either it is an undef element in the shuffle mask, the element of the input
6756 /// referenced is undef, or the element of the input referenced is known to be
6757 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6758 /// as many lanes with this technique as possible to simplify the remaining
6759 /// shuffle.
6760 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6761                                                      SDValue V1, SDValue V2) {
6762   SmallBitVector Zeroable(Mask.size(), false);
6763
6764   while (V1.getOpcode() == ISD::BITCAST)
6765     V1 = V1->getOperand(0);
6766   while (V2.getOpcode() == ISD::BITCAST)
6767     V2 = V2->getOperand(0);
6768
6769   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6770   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6771
6772   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6773     int M = Mask[i];
6774     // Handle the easy cases.
6775     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6776       Zeroable[i] = true;
6777       continue;
6778     }
6779
6780     // If this is an index into a build_vector node (which has the same number
6781     // of elements), dig out the input value and use it.
6782     SDValue V = M < Size ? V1 : V2;
6783     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6784       continue;
6785
6786     SDValue Input = V.getOperand(M % Size);
6787     // The UNDEF opcode check really should be dead code here, but not quite
6788     // worth asserting on (it isn't invalid, just unexpected).
6789     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6790       Zeroable[i] = true;
6791   }
6792
6793   return Zeroable;
6794 }
6795
6796 /// \brief Try to emit a bitmask instruction for a shuffle.
6797 ///
6798 /// This handles cases where we can model a blend exactly as a bitmask due to
6799 /// one of the inputs being zeroable.
6800 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6801                                            SDValue V2, ArrayRef<int> Mask,
6802                                            SelectionDAG &DAG) {
6803   MVT EltVT = VT.getScalarType();
6804   int NumEltBits = EltVT.getSizeInBits();
6805   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6806   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6807   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6808                                     IntEltVT);
6809   if (EltVT.isFloatingPoint()) {
6810     Zero = DAG.getBitcast(EltVT, Zero);
6811     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6812   }
6813   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6814   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6815   SDValue V;
6816   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6817     if (Zeroable[i])
6818       continue;
6819     if (Mask[i] % Size != i)
6820       return SDValue(); // Not a blend.
6821     if (!V)
6822       V = Mask[i] < Size ? V1 : V2;
6823     else if (V != (Mask[i] < Size ? V1 : V2))
6824       return SDValue(); // Can only let one input through the mask.
6825
6826     VMaskOps[i] = AllOnes;
6827   }
6828   if (!V)
6829     return SDValue(); // No non-zeroable elements!
6830
6831   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6832   V = DAG.getNode(VT.isFloatingPoint()
6833                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6834                   DL, VT, V, VMask);
6835   return V;
6836 }
6837
6838 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6839 ///
6840 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6841 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6842 /// matches elements from one of the input vectors shuffled to the left or
6843 /// right with zeroable elements 'shifted in'. It handles both the strictly
6844 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6845 /// quad word lane.
6846 ///
6847 /// PSHL : (little-endian) left bit shift.
6848 /// [ zz, 0, zz,  2 ]
6849 /// [ -1, 4, zz, -1 ]
6850 /// PSRL : (little-endian) right bit shift.
6851 /// [  1, zz,  3, zz]
6852 /// [ -1, -1,  7, zz]
6853 /// PSLLDQ : (little-endian) left byte shift
6854 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6855 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6856 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6857 /// PSRLDQ : (little-endian) right byte shift
6858 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6859 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6860 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6861 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6862                                          SDValue V2, ArrayRef<int> Mask,
6863                                          SelectionDAG &DAG) {
6864   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6865
6866   int Size = Mask.size();
6867   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6868
6869   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6870     for (int i = 0; i < Size; i += Scale)
6871       for (int j = 0; j < Shift; ++j)
6872         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6873           return false;
6874
6875     return true;
6876   };
6877
6878   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6879     for (int i = 0; i != Size; i += Scale) {
6880       unsigned Pos = Left ? i + Shift : i;
6881       unsigned Low = Left ? i : i + Shift;
6882       unsigned Len = Scale - Shift;
6883       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6884                                       Low + (V == V1 ? 0 : Size)))
6885         return SDValue();
6886     }
6887
6888     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6889     bool ByteShift = ShiftEltBits > 64;
6890     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6891                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6892     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6893
6894     // Normalize the scale for byte shifts to still produce an i64 element
6895     // type.
6896     Scale = ByteShift ? Scale / 2 : Scale;
6897
6898     // We need to round trip through the appropriate type for the shift.
6899     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6900     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6901     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6902            "Illegal integer vector type");
6903     V = DAG.getBitcast(ShiftVT, V);
6904
6905     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6906                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6907     return DAG.getBitcast(VT, V);
6908   };
6909
6910   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6911   // keep doubling the size of the integer elements up to that. We can
6912   // then shift the elements of the integer vector by whole multiples of
6913   // their width within the elements of the larger integer vector. Test each
6914   // multiple to see if we can find a match with the moved element indices
6915   // and that the shifted in elements are all zeroable.
6916   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6917     for (int Shift = 1; Shift != Scale; ++Shift)
6918       for (bool Left : {true, false})
6919         if (CheckZeros(Shift, Scale, Left))
6920           for (SDValue V : {V1, V2})
6921             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6922               return Match;
6923
6924   // no match
6925   return SDValue();
6926 }
6927
6928 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6929 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6930                                            SDValue V2, ArrayRef<int> Mask,
6931                                            SelectionDAG &DAG) {
6932   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6933   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6934
6935   int Size = Mask.size();
6936   int HalfSize = Size / 2;
6937   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6938
6939   // Upper half must be undefined.
6940   if (!isUndefInRange(Mask, HalfSize, HalfSize))
6941     return SDValue();
6942
6943   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6944   // Remainder of lower half result is zero and upper half is all undef.
6945   auto LowerAsEXTRQ = [&]() {
6946     // Determine the extraction length from the part of the
6947     // lower half that isn't zeroable.
6948     int Len = HalfSize;
6949     for (; Len >= 0; --Len)
6950       if (!Zeroable[Len - 1])
6951         break;
6952     assert(Len > 0 && "Zeroable shuffle mask");
6953
6954     // Attempt to match first Len sequential elements from the lower half.
6955     SDValue Src;
6956     int Idx = -1;
6957     for (int i = 0; i != Len; ++i) {
6958       int M = Mask[i];
6959       if (M < 0)
6960         continue;
6961       SDValue &V = (M < Size ? V1 : V2);
6962       M = M % Size;
6963
6964       // All mask elements must be in the lower half.
6965       if (M > HalfSize)
6966         return SDValue();
6967
6968       if (Idx < 0 || (Src == V && Idx == (M - i))) {
6969         Src = V;
6970         Idx = M - i;
6971         continue;
6972       }
6973       return SDValue();
6974     }
6975
6976     if (Idx < 0)
6977       return SDValue();
6978
6979     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
6980     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
6981     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
6982     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
6983                        DAG.getConstant(BitLen, DL, MVT::i8),
6984                        DAG.getConstant(BitIdx, DL, MVT::i8));
6985   };
6986
6987   if (SDValue ExtrQ = LowerAsEXTRQ())
6988     return ExtrQ;
6989
6990   // INSERTQ: Extract lowest Len elements from lower half of second source and
6991   // insert over first source, starting at Idx.
6992   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
6993   auto LowerAsInsertQ = [&]() {
6994     for (int Idx = 0; Idx != HalfSize; ++Idx) {
6995       SDValue Base;
6996
6997       // Attempt to match first source from mask before insertion point.
6998       if (isUndefInRange(Mask, 0, Idx)) {
6999         /* EMPTY */
7000       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7001         Base = V1;
7002       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7003         Base = V2;
7004       } else {
7005         continue;
7006       }
7007
7008       // Extend the extraction length looking to match both the insertion of
7009       // the second source and the remaining elements of the first.
7010       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7011         SDValue Insert;
7012         int Len = Hi - Idx;
7013
7014         // Match insertion.
7015         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7016           Insert = V1;
7017         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7018           Insert = V2;
7019         } else {
7020           continue;
7021         }
7022
7023         // Match the remaining elements of the lower half.
7024         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7025           /* EMPTY */
7026         } else if ((!Base || (Base == V1)) &&
7027                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7028           Base = V1;
7029         } else if ((!Base || (Base == V2)) &&
7030                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7031                                               Size + Hi)) {
7032           Base = V2;
7033         } else {
7034           continue;
7035         }
7036
7037         // We may not have a base (first source) - this can safely be undefined.
7038         if (!Base)
7039           Base = DAG.getUNDEF(VT);
7040
7041         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7042         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7043         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7044                            DAG.getConstant(BitLen, DL, MVT::i8),
7045                            DAG.getConstant(BitIdx, DL, MVT::i8));
7046       }
7047     }
7048
7049     return SDValue();
7050   };
7051
7052   if (SDValue InsertQ = LowerAsInsertQ())
7053     return InsertQ;
7054
7055   return SDValue();
7056 }
7057
7058 /// \brief Lower a vector shuffle as a zero or any extension.
7059 ///
7060 /// Given a specific number of elements, element bit width, and extension
7061 /// stride, produce either a zero or any extension based on the available
7062 /// features of the subtarget.
7063 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7064     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7065     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7066   assert(Scale > 1 && "Need a scale to extend.");
7067   int NumElements = VT.getVectorNumElements();
7068   int EltBits = VT.getScalarSizeInBits();
7069   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7070          "Only 8, 16, and 32 bit elements can be extended.");
7071   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7072
7073   // Found a valid zext mask! Try various lowering strategies based on the
7074   // input type and available ISA extensions.
7075   if (Subtarget->hasSSE41()) {
7076     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7077                                  NumElements / Scale);
7078     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7079   }
7080
7081   // For any extends we can cheat for larger element sizes and use shuffle
7082   // instructions that can fold with a load and/or copy.
7083   if (AnyExt && EltBits == 32) {
7084     int PSHUFDMask[4] = {0, -1, 1, -1};
7085     return DAG.getBitcast(
7086         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7087                         DAG.getBitcast(MVT::v4i32, InputV),
7088                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7089   }
7090   if (AnyExt && EltBits == 16 && Scale > 2) {
7091     int PSHUFDMask[4] = {0, -1, 0, -1};
7092     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7093                          DAG.getBitcast(MVT::v4i32, InputV),
7094                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7095     int PSHUFHWMask[4] = {1, -1, -1, -1};
7096     return DAG.getBitcast(
7097         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7098                         DAG.getBitcast(MVT::v8i16, InputV),
7099                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7100   }
7101
7102   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7103   // to 64-bits.
7104   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7105     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7106     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7107
7108     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7109                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7110                                          DAG.getConstant(EltBits, DL, MVT::i8),
7111                                          DAG.getConstant(0, DL, MVT::i8)));
7112     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7113       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7114
7115     SDValue Hi =
7116         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7117                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7118                                 DAG.getConstant(EltBits, DL, MVT::i8),
7119                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7120     return DAG.getNode(ISD::BITCAST, DL, VT,
7121                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7122   }
7123
7124   // If this would require more than 2 unpack instructions to expand, use
7125   // pshufb when available. We can only use more than 2 unpack instructions
7126   // when zero extending i8 elements which also makes it easier to use pshufb.
7127   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7128     assert(NumElements == 16 && "Unexpected byte vector width!");
7129     SDValue PSHUFBMask[16];
7130     for (int i = 0; i < 16; ++i)
7131       PSHUFBMask[i] =
7132           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7133     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7134     return DAG.getBitcast(VT,
7135                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7136                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7137                                                   MVT::v16i8, PSHUFBMask)));
7138   }
7139
7140   // Otherwise emit a sequence of unpacks.
7141   do {
7142     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7143     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7144                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7145     InputV = DAG.getBitcast(InputVT, InputV);
7146     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7147     Scale /= 2;
7148     EltBits *= 2;
7149     NumElements /= 2;
7150   } while (Scale > 1);
7151   return DAG.getBitcast(VT, InputV);
7152 }
7153
7154 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7155 ///
7156 /// This routine will try to do everything in its power to cleverly lower
7157 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7158 /// check for the profitability of this lowering,  it tries to aggressively
7159 /// match this pattern. It will use all of the micro-architectural details it
7160 /// can to emit an efficient lowering. It handles both blends with all-zero
7161 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7162 /// masking out later).
7163 ///
7164 /// The reason we have dedicated lowering for zext-style shuffles is that they
7165 /// are both incredibly common and often quite performance sensitive.
7166 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7167     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7168     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7169   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7170
7171   int Bits = VT.getSizeInBits();
7172   int NumElements = VT.getVectorNumElements();
7173   assert(VT.getScalarSizeInBits() <= 32 &&
7174          "Exceeds 32-bit integer zero extension limit");
7175   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7176
7177   // Define a helper function to check a particular ext-scale and lower to it if
7178   // valid.
7179   auto Lower = [&](int Scale) -> SDValue {
7180     SDValue InputV;
7181     bool AnyExt = true;
7182     for (int i = 0; i < NumElements; ++i) {
7183       if (Mask[i] == -1)
7184         continue; // Valid anywhere but doesn't tell us anything.
7185       if (i % Scale != 0) {
7186         // Each of the extended elements need to be zeroable.
7187         if (!Zeroable[i])
7188           return SDValue();
7189
7190         // We no longer are in the anyext case.
7191         AnyExt = false;
7192         continue;
7193       }
7194
7195       // Each of the base elements needs to be consecutive indices into the
7196       // same input vector.
7197       SDValue V = Mask[i] < NumElements ? V1 : V2;
7198       if (!InputV)
7199         InputV = V;
7200       else if (InputV != V)
7201         return SDValue(); // Flip-flopping inputs.
7202
7203       if (Mask[i] % NumElements != i / Scale)
7204         return SDValue(); // Non-consecutive strided elements.
7205     }
7206
7207     // If we fail to find an input, we have a zero-shuffle which should always
7208     // have already been handled.
7209     // FIXME: Maybe handle this here in case during blending we end up with one?
7210     if (!InputV)
7211       return SDValue();
7212
7213     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7214         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7215   };
7216
7217   // The widest scale possible for extending is to a 64-bit integer.
7218   assert(Bits % 64 == 0 &&
7219          "The number of bits in a vector must be divisible by 64 on x86!");
7220   int NumExtElements = Bits / 64;
7221
7222   // Each iteration, try extending the elements half as much, but into twice as
7223   // many elements.
7224   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7225     assert(NumElements % NumExtElements == 0 &&
7226            "The input vector size must be divisible by the extended size.");
7227     if (SDValue V = Lower(NumElements / NumExtElements))
7228       return V;
7229   }
7230
7231   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7232   if (Bits != 128)
7233     return SDValue();
7234
7235   // Returns one of the source operands if the shuffle can be reduced to a
7236   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7237   auto CanZExtLowHalf = [&]() {
7238     for (int i = NumElements / 2; i != NumElements; ++i)
7239       if (!Zeroable[i])
7240         return SDValue();
7241     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7242       return V1;
7243     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7244       return V2;
7245     return SDValue();
7246   };
7247
7248   if (SDValue V = CanZExtLowHalf()) {
7249     V = DAG.getBitcast(MVT::v2i64, V);
7250     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7251     return DAG.getBitcast(VT, V);
7252   }
7253
7254   // No viable ext lowering found.
7255   return SDValue();
7256 }
7257
7258 /// \brief Try to get a scalar value for a specific element of a vector.
7259 ///
7260 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7261 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7262                                               SelectionDAG &DAG) {
7263   MVT VT = V.getSimpleValueType();
7264   MVT EltVT = VT.getVectorElementType();
7265   while (V.getOpcode() == ISD::BITCAST)
7266     V = V.getOperand(0);
7267   // If the bitcasts shift the element size, we can't extract an equivalent
7268   // element from it.
7269   MVT NewVT = V.getSimpleValueType();
7270   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7271     return SDValue();
7272
7273   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7274       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7275     // Ensure the scalar operand is the same size as the destination.
7276     // FIXME: Add support for scalar truncation where possible.
7277     SDValue S = V.getOperand(Idx);
7278     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7279       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7280   }
7281
7282   return SDValue();
7283 }
7284
7285 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7286 ///
7287 /// This is particularly important because the set of instructions varies
7288 /// significantly based on whether the operand is a load or not.
7289 static bool isShuffleFoldableLoad(SDValue V) {
7290   while (V.getOpcode() == ISD::BITCAST)
7291     V = V.getOperand(0);
7292
7293   return ISD::isNON_EXTLoad(V.getNode());
7294 }
7295
7296 /// \brief Try to lower insertion of a single element into a zero vector.
7297 ///
7298 /// This is a common pattern that we have especially efficient patterns to lower
7299 /// across all subtarget feature sets.
7300 static SDValue lowerVectorShuffleAsElementInsertion(
7301     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7302     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7303   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7304   MVT ExtVT = VT;
7305   MVT EltVT = VT.getVectorElementType();
7306
7307   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7308                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7309                 Mask.begin();
7310   bool IsV1Zeroable = true;
7311   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7312     if (i != V2Index && !Zeroable[i]) {
7313       IsV1Zeroable = false;
7314       break;
7315     }
7316
7317   // Check for a single input from a SCALAR_TO_VECTOR node.
7318   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7319   // all the smarts here sunk into that routine. However, the current
7320   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7321   // vector shuffle lowering is dead.
7322   if (SDValue V2S = getScalarValueForVectorElement(
7323           V2, Mask[V2Index] - Mask.size(), DAG)) {
7324     // We need to zext the scalar if it is smaller than an i32.
7325     V2S = DAG.getBitcast(EltVT, V2S);
7326     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7327       // Using zext to expand a narrow element won't work for non-zero
7328       // insertions.
7329       if (!IsV1Zeroable)
7330         return SDValue();
7331
7332       // Zero-extend directly to i32.
7333       ExtVT = MVT::v4i32;
7334       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7335     }
7336     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7337   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7338              EltVT == MVT::i16) {
7339     // Either not inserting from the low element of the input or the input
7340     // element size is too small to use VZEXT_MOVL to clear the high bits.
7341     return SDValue();
7342   }
7343
7344   if (!IsV1Zeroable) {
7345     // If V1 can't be treated as a zero vector we have fewer options to lower
7346     // this. We can't support integer vectors or non-zero targets cheaply, and
7347     // the V1 elements can't be permuted in any way.
7348     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7349     if (!VT.isFloatingPoint() || V2Index != 0)
7350       return SDValue();
7351     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7352     V1Mask[V2Index] = -1;
7353     if (!isNoopShuffleMask(V1Mask))
7354       return SDValue();
7355     // This is essentially a special case blend operation, but if we have
7356     // general purpose blend operations, they are always faster. Bail and let
7357     // the rest of the lowering handle these as blends.
7358     if (Subtarget->hasSSE41())
7359       return SDValue();
7360
7361     // Otherwise, use MOVSD or MOVSS.
7362     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7363            "Only two types of floating point element types to handle!");
7364     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7365                        ExtVT, V1, V2);
7366   }
7367
7368   // This lowering only works for the low element with floating point vectors.
7369   if (VT.isFloatingPoint() && V2Index != 0)
7370     return SDValue();
7371
7372   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7373   if (ExtVT != VT)
7374     V2 = DAG.getBitcast(VT, V2);
7375
7376   if (V2Index != 0) {
7377     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7378     // the desired position. Otherwise it is more efficient to do a vector
7379     // shift left. We know that we can do a vector shift left because all
7380     // the inputs are zero.
7381     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7382       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7383       V2Shuffle[V2Index] = 0;
7384       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7385     } else {
7386       V2 = DAG.getBitcast(MVT::v2i64, V2);
7387       V2 = DAG.getNode(
7388           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7389           DAG.getConstant(
7390               V2Index * EltVT.getSizeInBits()/8, DL,
7391               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7392       V2 = DAG.getBitcast(VT, V2);
7393     }
7394   }
7395   return V2;
7396 }
7397
7398 /// \brief Try to lower broadcast of a single element.
7399 ///
7400 /// For convenience, this code also bundles all of the subtarget feature set
7401 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7402 /// a convenient way to factor it out.
7403 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7404                                              ArrayRef<int> Mask,
7405                                              const X86Subtarget *Subtarget,
7406                                              SelectionDAG &DAG) {
7407   if (!Subtarget->hasAVX())
7408     return SDValue();
7409   if (VT.isInteger() && !Subtarget->hasAVX2())
7410     return SDValue();
7411
7412   // Check that the mask is a broadcast.
7413   int BroadcastIdx = -1;
7414   for (int M : Mask)
7415     if (M >= 0 && BroadcastIdx == -1)
7416       BroadcastIdx = M;
7417     else if (M >= 0 && M != BroadcastIdx)
7418       return SDValue();
7419
7420   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7421                                             "a sorted mask where the broadcast "
7422                                             "comes from V1.");
7423
7424   // Go up the chain of (vector) values to find a scalar load that we can
7425   // combine with the broadcast.
7426   for (;;) {
7427     switch (V.getOpcode()) {
7428     case ISD::CONCAT_VECTORS: {
7429       int OperandSize = Mask.size() / V.getNumOperands();
7430       V = V.getOperand(BroadcastIdx / OperandSize);
7431       BroadcastIdx %= OperandSize;
7432       continue;
7433     }
7434
7435     case ISD::INSERT_SUBVECTOR: {
7436       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7437       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7438       if (!ConstantIdx)
7439         break;
7440
7441       int BeginIdx = (int)ConstantIdx->getZExtValue();
7442       int EndIdx =
7443           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7444       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7445         BroadcastIdx -= BeginIdx;
7446         V = VInner;
7447       } else {
7448         V = VOuter;
7449       }
7450       continue;
7451     }
7452     }
7453     break;
7454   }
7455
7456   // Check if this is a broadcast of a scalar. We special case lowering
7457   // for scalars so that we can more effectively fold with loads.
7458   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7459       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7460     V = V.getOperand(BroadcastIdx);
7461
7462     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7463     // Only AVX2 has register broadcasts.
7464     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7465       return SDValue();
7466   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7467     // We can't broadcast from a vector register without AVX2, and we can only
7468     // broadcast from the zero-element of a vector register.
7469     return SDValue();
7470   }
7471
7472   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7473 }
7474
7475 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7476 // INSERTPS when the V1 elements are already in the correct locations
7477 // because otherwise we can just always use two SHUFPS instructions which
7478 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7479 // perform INSERTPS if a single V1 element is out of place and all V2
7480 // elements are zeroable.
7481 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7482                                             ArrayRef<int> Mask,
7483                                             SelectionDAG &DAG) {
7484   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7485   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7486   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7487   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7488
7489   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7490
7491   unsigned ZMask = 0;
7492   int V1DstIndex = -1;
7493   int V2DstIndex = -1;
7494   bool V1UsedInPlace = false;
7495
7496   for (int i = 0; i < 4; ++i) {
7497     // Synthesize a zero mask from the zeroable elements (includes undefs).
7498     if (Zeroable[i]) {
7499       ZMask |= 1 << i;
7500       continue;
7501     }
7502
7503     // Flag if we use any V1 inputs in place.
7504     if (i == Mask[i]) {
7505       V1UsedInPlace = true;
7506       continue;
7507     }
7508
7509     // We can only insert a single non-zeroable element.
7510     if (V1DstIndex != -1 || V2DstIndex != -1)
7511       return SDValue();
7512
7513     if (Mask[i] < 4) {
7514       // V1 input out of place for insertion.
7515       V1DstIndex = i;
7516     } else {
7517       // V2 input for insertion.
7518       V2DstIndex = i;
7519     }
7520   }
7521
7522   // Don't bother if we have no (non-zeroable) element for insertion.
7523   if (V1DstIndex == -1 && V2DstIndex == -1)
7524     return SDValue();
7525
7526   // Determine element insertion src/dst indices. The src index is from the
7527   // start of the inserted vector, not the start of the concatenated vector.
7528   unsigned V2SrcIndex = 0;
7529   if (V1DstIndex != -1) {
7530     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7531     // and don't use the original V2 at all.
7532     V2SrcIndex = Mask[V1DstIndex];
7533     V2DstIndex = V1DstIndex;
7534     V2 = V1;
7535   } else {
7536     V2SrcIndex = Mask[V2DstIndex] - 4;
7537   }
7538
7539   // If no V1 inputs are used in place, then the result is created only from
7540   // the zero mask and the V2 insertion - so remove V1 dependency.
7541   if (!V1UsedInPlace)
7542     V1 = DAG.getUNDEF(MVT::v4f32);
7543
7544   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7545   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7546
7547   // Insert the V2 element into the desired position.
7548   SDLoc DL(Op);
7549   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7550                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7551 }
7552
7553 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7554 /// UNPCK instruction.
7555 ///
7556 /// This specifically targets cases where we end up with alternating between
7557 /// the two inputs, and so can permute them into something that feeds a single
7558 /// UNPCK instruction. Note that this routine only targets integer vectors
7559 /// because for floating point vectors we have a generalized SHUFPS lowering
7560 /// strategy that handles everything that doesn't *exactly* match an unpack,
7561 /// making this clever lowering unnecessary.
7562 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7563                                           SDValue V2, ArrayRef<int> Mask,
7564                                           SelectionDAG &DAG) {
7565   assert(!VT.isFloatingPoint() &&
7566          "This routine only supports integer vectors.");
7567   assert(!isSingleInputShuffleMask(Mask) &&
7568          "This routine should only be used when blending two inputs.");
7569   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7570
7571   int Size = Mask.size();
7572
7573   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7574     return M >= 0 && M % Size < Size / 2;
7575   });
7576   int NumHiInputs = std::count_if(
7577       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7578
7579   bool UnpackLo = NumLoInputs >= NumHiInputs;
7580
7581   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7582     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7583     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7584
7585     for (int i = 0; i < Size; ++i) {
7586       if (Mask[i] < 0)
7587         continue;
7588
7589       // Each element of the unpack contains Scale elements from this mask.
7590       int UnpackIdx = i / Scale;
7591
7592       // We only handle the case where V1 feeds the first slots of the unpack.
7593       // We rely on canonicalization to ensure this is the case.
7594       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7595         return SDValue();
7596
7597       // Setup the mask for this input. The indexing is tricky as we have to
7598       // handle the unpack stride.
7599       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7600       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7601           Mask[i] % Size;
7602     }
7603
7604     // If we will have to shuffle both inputs to use the unpack, check whether
7605     // we can just unpack first and shuffle the result. If so, skip this unpack.
7606     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7607         !isNoopShuffleMask(V2Mask))
7608       return SDValue();
7609
7610     // Shuffle the inputs into place.
7611     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7612     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7613
7614     // Cast the inputs to the type we will use to unpack them.
7615     V1 = DAG.getBitcast(UnpackVT, V1);
7616     V2 = DAG.getBitcast(UnpackVT, V2);
7617
7618     // Unpack the inputs and cast the result back to the desired type.
7619     return DAG.getBitcast(
7620         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7621                         UnpackVT, V1, V2));
7622   };
7623
7624   // We try each unpack from the largest to the smallest to try and find one
7625   // that fits this mask.
7626   int OrigNumElements = VT.getVectorNumElements();
7627   int OrigScalarSize = VT.getScalarSizeInBits();
7628   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7629     int Scale = ScalarSize / OrigScalarSize;
7630     int NumElements = OrigNumElements / Scale;
7631     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7632     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7633       return Unpack;
7634   }
7635
7636   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7637   // initial unpack.
7638   if (NumLoInputs == 0 || NumHiInputs == 0) {
7639     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7640            "We have to have *some* inputs!");
7641     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7642
7643     // FIXME: We could consider the total complexity of the permute of each
7644     // possible unpacking. Or at the least we should consider how many
7645     // half-crossings are created.
7646     // FIXME: We could consider commuting the unpacks.
7647
7648     SmallVector<int, 32> PermMask;
7649     PermMask.assign(Size, -1);
7650     for (int i = 0; i < Size; ++i) {
7651       if (Mask[i] < 0)
7652         continue;
7653
7654       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7655
7656       PermMask[i] =
7657           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7658     }
7659     return DAG.getVectorShuffle(
7660         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7661                             DL, VT, V1, V2),
7662         DAG.getUNDEF(VT), PermMask);
7663   }
7664
7665   return SDValue();
7666 }
7667
7668 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7669 ///
7670 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7671 /// support for floating point shuffles but not integer shuffles. These
7672 /// instructions will incur a domain crossing penalty on some chips though so
7673 /// it is better to avoid lowering through this for integer vectors where
7674 /// possible.
7675 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7676                                        const X86Subtarget *Subtarget,
7677                                        SelectionDAG &DAG) {
7678   SDLoc DL(Op);
7679   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7680   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7681   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7682   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7683   ArrayRef<int> Mask = SVOp->getMask();
7684   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7685
7686   if (isSingleInputShuffleMask(Mask)) {
7687     // Use low duplicate instructions for masks that match their pattern.
7688     if (Subtarget->hasSSE3())
7689       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7690         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7691
7692     // Straight shuffle of a single input vector. Simulate this by using the
7693     // single input as both of the "inputs" to this instruction..
7694     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7695
7696     if (Subtarget->hasAVX()) {
7697       // If we have AVX, we can use VPERMILPS which will allow folding a load
7698       // into the shuffle.
7699       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7700                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7701     }
7702
7703     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7704                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7705   }
7706   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7707   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7708
7709   // If we have a single input, insert that into V1 if we can do so cheaply.
7710   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7711     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7712             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7713       return Insertion;
7714     // Try inverting the insertion since for v2 masks it is easy to do and we
7715     // can't reliably sort the mask one way or the other.
7716     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7717                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7718     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7719             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7720       return Insertion;
7721   }
7722
7723   // Try to use one of the special instruction patterns to handle two common
7724   // blend patterns if a zero-blend above didn't work.
7725   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7726       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7727     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7728       // We can either use a special instruction to load over the low double or
7729       // to move just the low double.
7730       return DAG.getNode(
7731           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7732           DL, MVT::v2f64, V2,
7733           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7734
7735   if (Subtarget->hasSSE41())
7736     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7737                                                   Subtarget, DAG))
7738       return Blend;
7739
7740   // Use dedicated unpack instructions for masks that match their pattern.
7741   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7742     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7743   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7744     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7745
7746   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7747   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7748                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7749 }
7750
7751 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7752 ///
7753 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7754 /// the integer unit to minimize domain crossing penalties. However, for blends
7755 /// it falls back to the floating point shuffle operation with appropriate bit
7756 /// casting.
7757 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7758                                        const X86Subtarget *Subtarget,
7759                                        SelectionDAG &DAG) {
7760   SDLoc DL(Op);
7761   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7762   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7763   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7764   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7765   ArrayRef<int> Mask = SVOp->getMask();
7766   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7767
7768   if (isSingleInputShuffleMask(Mask)) {
7769     // Check for being able to broadcast a single element.
7770     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7771                                                           Mask, Subtarget, DAG))
7772       return Broadcast;
7773
7774     // Straight shuffle of a single input vector. For everything from SSE2
7775     // onward this has a single fast instruction with no scary immediates.
7776     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7777     V1 = DAG.getBitcast(MVT::v4i32, V1);
7778     int WidenedMask[4] = {
7779         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7780         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7781     return DAG.getBitcast(
7782         MVT::v2i64,
7783         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7784                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7785   }
7786   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7787   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7788   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7789   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7790
7791   // If we have a blend of two PACKUS operations an the blend aligns with the
7792   // low and half halves, we can just merge the PACKUS operations. This is
7793   // particularly important as it lets us merge shuffles that this routine itself
7794   // creates.
7795   auto GetPackNode = [](SDValue V) {
7796     while (V.getOpcode() == ISD::BITCAST)
7797       V = V.getOperand(0);
7798
7799     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7800   };
7801   if (SDValue V1Pack = GetPackNode(V1))
7802     if (SDValue V2Pack = GetPackNode(V2))
7803       return DAG.getBitcast(MVT::v2i64,
7804                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7805                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7806                                                      : V1Pack.getOperand(1),
7807                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7808                                                      : V2Pack.getOperand(1)));
7809
7810   // Try to use shift instructions.
7811   if (SDValue Shift =
7812           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7813     return Shift;
7814
7815   // When loading a scalar and then shuffling it into a vector we can often do
7816   // the insertion cheaply.
7817   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7818           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7819     return Insertion;
7820   // Try inverting the insertion since for v2 masks it is easy to do and we
7821   // can't reliably sort the mask one way or the other.
7822   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7823   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7824           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7825     return Insertion;
7826
7827   // We have different paths for blend lowering, but they all must use the
7828   // *exact* same predicate.
7829   bool IsBlendSupported = Subtarget->hasSSE41();
7830   if (IsBlendSupported)
7831     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7832                                                   Subtarget, DAG))
7833       return Blend;
7834
7835   // Use dedicated unpack instructions for masks that match their pattern.
7836   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7837     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7838   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7839     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7840
7841   // Try to use byte rotation instructions.
7842   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7843   if (Subtarget->hasSSSE3())
7844     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7845             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7846       return Rotate;
7847
7848   // If we have direct support for blends, we should lower by decomposing into
7849   // a permute. That will be faster than the domain cross.
7850   if (IsBlendSupported)
7851     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7852                                                       Mask, DAG);
7853
7854   // We implement this with SHUFPD which is pretty lame because it will likely
7855   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7856   // However, all the alternatives are still more cycles and newer chips don't
7857   // have this problem. It would be really nice if x86 had better shuffles here.
7858   V1 = DAG.getBitcast(MVT::v2f64, V1);
7859   V2 = DAG.getBitcast(MVT::v2f64, V2);
7860   return DAG.getBitcast(MVT::v2i64,
7861                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7862 }
7863
7864 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7865 ///
7866 /// This is used to disable more specialized lowerings when the shufps lowering
7867 /// will happen to be efficient.
7868 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7869   // This routine only handles 128-bit shufps.
7870   assert(Mask.size() == 4 && "Unsupported mask size!");
7871
7872   // To lower with a single SHUFPS we need to have the low half and high half
7873   // each requiring a single input.
7874   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7875     return false;
7876   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7877     return false;
7878
7879   return true;
7880 }
7881
7882 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7883 ///
7884 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7885 /// It makes no assumptions about whether this is the *best* lowering, it simply
7886 /// uses it.
7887 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7888                                             ArrayRef<int> Mask, SDValue V1,
7889                                             SDValue V2, SelectionDAG &DAG) {
7890   SDValue LowV = V1, HighV = V2;
7891   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7892
7893   int NumV2Elements =
7894       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7895
7896   if (NumV2Elements == 1) {
7897     int V2Index =
7898         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7899         Mask.begin();
7900
7901     // Compute the index adjacent to V2Index and in the same half by toggling
7902     // the low bit.
7903     int V2AdjIndex = V2Index ^ 1;
7904
7905     if (Mask[V2AdjIndex] == -1) {
7906       // Handles all the cases where we have a single V2 element and an undef.
7907       // This will only ever happen in the high lanes because we commute the
7908       // vector otherwise.
7909       if (V2Index < 2)
7910         std::swap(LowV, HighV);
7911       NewMask[V2Index] -= 4;
7912     } else {
7913       // Handle the case where the V2 element ends up adjacent to a V1 element.
7914       // To make this work, blend them together as the first step.
7915       int V1Index = V2AdjIndex;
7916       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7917       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7918                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7919
7920       // Now proceed to reconstruct the final blend as we have the necessary
7921       // high or low half formed.
7922       if (V2Index < 2) {
7923         LowV = V2;
7924         HighV = V1;
7925       } else {
7926         HighV = V2;
7927       }
7928       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7929       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7930     }
7931   } else if (NumV2Elements == 2) {
7932     if (Mask[0] < 4 && Mask[1] < 4) {
7933       // Handle the easy case where we have V1 in the low lanes and V2 in the
7934       // high lanes.
7935       NewMask[2] -= 4;
7936       NewMask[3] -= 4;
7937     } else if (Mask[2] < 4 && Mask[3] < 4) {
7938       // We also handle the reversed case because this utility may get called
7939       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7940       // arrange things in the right direction.
7941       NewMask[0] -= 4;
7942       NewMask[1] -= 4;
7943       HighV = V1;
7944       LowV = V2;
7945     } else {
7946       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7947       // trying to place elements directly, just blend them and set up the final
7948       // shuffle to place them.
7949
7950       // The first two blend mask elements are for V1, the second two are for
7951       // V2.
7952       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7953                           Mask[2] < 4 ? Mask[2] : Mask[3],
7954                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7955                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7956       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7957                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7958
7959       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7960       // a blend.
7961       LowV = HighV = V1;
7962       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7963       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7964       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7965       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7966     }
7967   }
7968   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7969                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7970 }
7971
7972 /// \brief Lower 4-lane 32-bit floating point shuffles.
7973 ///
7974 /// Uses instructions exclusively from the floating point unit to minimize
7975 /// domain crossing penalties, as these are sufficient to implement all v4f32
7976 /// shuffles.
7977 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7978                                        const X86Subtarget *Subtarget,
7979                                        SelectionDAG &DAG) {
7980   SDLoc DL(Op);
7981   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7982   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7983   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7984   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7985   ArrayRef<int> Mask = SVOp->getMask();
7986   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7987
7988   int NumV2Elements =
7989       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7990
7991   if (NumV2Elements == 0) {
7992     // Check for being able to broadcast a single element.
7993     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7994                                                           Mask, Subtarget, DAG))
7995       return Broadcast;
7996
7997     // Use even/odd duplicate instructions for masks that match their pattern.
7998     if (Subtarget->hasSSE3()) {
7999       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8000         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8001       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8002         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8003     }
8004
8005     if (Subtarget->hasAVX()) {
8006       // If we have AVX, we can use VPERMILPS which will allow folding a load
8007       // into the shuffle.
8008       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8009                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8010     }
8011
8012     // Otherwise, use a straight shuffle of a single input vector. We pass the
8013     // input vector to both operands to simulate this with a SHUFPS.
8014     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8015                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8016   }
8017
8018   // There are special ways we can lower some single-element blends. However, we
8019   // have custom ways we can lower more complex single-element blends below that
8020   // we defer to if both this and BLENDPS fail to match, so restrict this to
8021   // when the V2 input is targeting element 0 of the mask -- that is the fast
8022   // case here.
8023   if (NumV2Elements == 1 && Mask[0] >= 4)
8024     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8025                                                          Mask, Subtarget, DAG))
8026       return V;
8027
8028   if (Subtarget->hasSSE41()) {
8029     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8030                                                   Subtarget, DAG))
8031       return Blend;
8032
8033     // Use INSERTPS if we can complete the shuffle efficiently.
8034     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8035       return V;
8036
8037     if (!isSingleSHUFPSMask(Mask))
8038       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8039               DL, MVT::v4f32, V1, V2, Mask, DAG))
8040         return BlendPerm;
8041   }
8042
8043   // Use dedicated unpack instructions for masks that match their pattern.
8044   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8045     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8046   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8047     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8048   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8049     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8050   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8051     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8052
8053   // Otherwise fall back to a SHUFPS lowering strategy.
8054   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8055 }
8056
8057 /// \brief Lower 4-lane i32 vector shuffles.
8058 ///
8059 /// We try to handle these with integer-domain shuffles where we can, but for
8060 /// blends we use the floating point domain blend instructions.
8061 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8062                                        const X86Subtarget *Subtarget,
8063                                        SelectionDAG &DAG) {
8064   SDLoc DL(Op);
8065   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8066   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8067   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8068   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8069   ArrayRef<int> Mask = SVOp->getMask();
8070   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8071
8072   // Whenever we can lower this as a zext, that instruction is strictly faster
8073   // than any alternative. It also allows us to fold memory operands into the
8074   // shuffle in many cases.
8075   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8076                                                          Mask, Subtarget, DAG))
8077     return ZExt;
8078
8079   int NumV2Elements =
8080       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8081
8082   if (NumV2Elements == 0) {
8083     // Check for being able to broadcast a single element.
8084     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8085                                                           Mask, Subtarget, DAG))
8086       return Broadcast;
8087
8088     // Straight shuffle of a single input vector. For everything from SSE2
8089     // onward this has a single fast instruction with no scary immediates.
8090     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8091     // but we aren't actually going to use the UNPCK instruction because doing
8092     // so prevents folding a load into this instruction or making a copy.
8093     const int UnpackLoMask[] = {0, 0, 1, 1};
8094     const int UnpackHiMask[] = {2, 2, 3, 3};
8095     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8096       Mask = UnpackLoMask;
8097     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8098       Mask = UnpackHiMask;
8099
8100     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8101                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8102   }
8103
8104   // Try to use shift instructions.
8105   if (SDValue Shift =
8106           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8107     return Shift;
8108
8109   // There are special ways we can lower some single-element blends.
8110   if (NumV2Elements == 1)
8111     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8112                                                          Mask, Subtarget, DAG))
8113       return V;
8114
8115   // We have different paths for blend lowering, but they all must use the
8116   // *exact* same predicate.
8117   bool IsBlendSupported = Subtarget->hasSSE41();
8118   if (IsBlendSupported)
8119     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8120                                                   Subtarget, DAG))
8121       return Blend;
8122
8123   if (SDValue Masked =
8124           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8125     return Masked;
8126
8127   // Use dedicated unpack instructions for masks that match their pattern.
8128   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8129     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8130   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8131     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8132   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8133     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8134   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8135     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8136
8137   // Try to use byte rotation instructions.
8138   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8139   if (Subtarget->hasSSSE3())
8140     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8141             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8142       return Rotate;
8143
8144   // If we have direct support for blends, we should lower by decomposing into
8145   // a permute. That will be faster than the domain cross.
8146   if (IsBlendSupported)
8147     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8148                                                       Mask, DAG);
8149
8150   // Try to lower by permuting the inputs into an unpack instruction.
8151   if (SDValue Unpack =
8152           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8153     return Unpack;
8154
8155   // We implement this with SHUFPS because it can blend from two vectors.
8156   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8157   // up the inputs, bypassing domain shift penalties that we would encur if we
8158   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8159   // relevant.
8160   return DAG.getBitcast(
8161       MVT::v4i32,
8162       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8163                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8164 }
8165
8166 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8167 /// shuffle lowering, and the most complex part.
8168 ///
8169 /// The lowering strategy is to try to form pairs of input lanes which are
8170 /// targeted at the same half of the final vector, and then use a dword shuffle
8171 /// to place them onto the right half, and finally unpack the paired lanes into
8172 /// their final position.
8173 ///
8174 /// The exact breakdown of how to form these dword pairs and align them on the
8175 /// correct sides is really tricky. See the comments within the function for
8176 /// more of the details.
8177 ///
8178 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8179 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8180 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8181 /// vector, form the analogous 128-bit 8-element Mask.
8182 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8183     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8184     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8185   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8186   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8187
8188   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8189   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8190   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8191
8192   SmallVector<int, 4> LoInputs;
8193   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8194                [](int M) { return M >= 0; });
8195   std::sort(LoInputs.begin(), LoInputs.end());
8196   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8197   SmallVector<int, 4> HiInputs;
8198   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8199                [](int M) { return M >= 0; });
8200   std::sort(HiInputs.begin(), HiInputs.end());
8201   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8202   int NumLToL =
8203       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8204   int NumHToL = LoInputs.size() - NumLToL;
8205   int NumLToH =
8206       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8207   int NumHToH = HiInputs.size() - NumLToH;
8208   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8209   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8210   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8211   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8212
8213   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8214   // such inputs we can swap two of the dwords across the half mark and end up
8215   // with <=2 inputs to each half in each half. Once there, we can fall through
8216   // to the generic code below. For example:
8217   //
8218   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8219   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8220   //
8221   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8222   // and an existing 2-into-2 on the other half. In this case we may have to
8223   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8224   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8225   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8226   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8227   // half than the one we target for fixing) will be fixed when we re-enter this
8228   // path. We will also combine away any sequence of PSHUFD instructions that
8229   // result into a single instruction. Here is an example of the tricky case:
8230   //
8231   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8232   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8233   //
8234   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8235   //
8236   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8237   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8238   //
8239   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8240   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8241   //
8242   // The result is fine to be handled by the generic logic.
8243   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8244                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8245                           int AOffset, int BOffset) {
8246     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8247            "Must call this with A having 3 or 1 inputs from the A half.");
8248     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8249            "Must call this with B having 1 or 3 inputs from the B half.");
8250     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8251            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8252
8253     // Compute the index of dword with only one word among the three inputs in
8254     // a half by taking the sum of the half with three inputs and subtracting
8255     // the sum of the actual three inputs. The difference is the remaining
8256     // slot.
8257     int ADWord, BDWord;
8258     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8259     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8260     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8261     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8262     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8263     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8264     int TripleNonInputIdx =
8265         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8266     TripleDWord = TripleNonInputIdx / 2;
8267
8268     // We use xor with one to compute the adjacent DWord to whichever one the
8269     // OneInput is in.
8270     OneInputDWord = (OneInput / 2) ^ 1;
8271
8272     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8273     // and BToA inputs. If there is also such a problem with the BToB and AToB
8274     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8275     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8276     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8277     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8278       // Compute how many inputs will be flipped by swapping these DWords. We
8279       // need
8280       // to balance this to ensure we don't form a 3-1 shuffle in the other
8281       // half.
8282       int NumFlippedAToBInputs =
8283           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8284           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8285       int NumFlippedBToBInputs =
8286           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8287           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8288       if ((NumFlippedAToBInputs == 1 &&
8289            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8290           (NumFlippedBToBInputs == 1 &&
8291            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8292         // We choose whether to fix the A half or B half based on whether that
8293         // half has zero flipped inputs. At zero, we may not be able to fix it
8294         // with that half. We also bias towards fixing the B half because that
8295         // will more commonly be the high half, and we have to bias one way.
8296         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8297                                                        ArrayRef<int> Inputs) {
8298           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8299           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8300                                          PinnedIdx ^ 1) != Inputs.end();
8301           // Determine whether the free index is in the flipped dword or the
8302           // unflipped dword based on where the pinned index is. We use this bit
8303           // in an xor to conditionally select the adjacent dword.
8304           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8305           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8306                                              FixFreeIdx) != Inputs.end();
8307           if (IsFixIdxInput == IsFixFreeIdxInput)
8308             FixFreeIdx += 1;
8309           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8310                                         FixFreeIdx) != Inputs.end();
8311           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8312                  "We need to be changing the number of flipped inputs!");
8313           int PSHUFHalfMask[] = {0, 1, 2, 3};
8314           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8315           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8316                           MVT::v8i16, V,
8317                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8318
8319           for (int &M : Mask)
8320             if (M != -1 && M == FixIdx)
8321               M = FixFreeIdx;
8322             else if (M != -1 && M == FixFreeIdx)
8323               M = FixIdx;
8324         };
8325         if (NumFlippedBToBInputs != 0) {
8326           int BPinnedIdx =
8327               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8328           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8329         } else {
8330           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8331           int APinnedIdx =
8332               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8333           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8334         }
8335       }
8336     }
8337
8338     int PSHUFDMask[] = {0, 1, 2, 3};
8339     PSHUFDMask[ADWord] = BDWord;
8340     PSHUFDMask[BDWord] = ADWord;
8341     V = DAG.getBitcast(
8342         VT,
8343         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8344                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8345
8346     // Adjust the mask to match the new locations of A and B.
8347     for (int &M : Mask)
8348       if (M != -1 && M/2 == ADWord)
8349         M = 2 * BDWord + M % 2;
8350       else if (M != -1 && M/2 == BDWord)
8351         M = 2 * ADWord + M % 2;
8352
8353     // Recurse back into this routine to re-compute state now that this isn't
8354     // a 3 and 1 problem.
8355     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8356                                                      DAG);
8357   };
8358   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8359     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8360   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8361     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8362
8363   // At this point there are at most two inputs to the low and high halves from
8364   // each half. That means the inputs can always be grouped into dwords and
8365   // those dwords can then be moved to the correct half with a dword shuffle.
8366   // We use at most one low and one high word shuffle to collect these paired
8367   // inputs into dwords, and finally a dword shuffle to place them.
8368   int PSHUFLMask[4] = {-1, -1, -1, -1};
8369   int PSHUFHMask[4] = {-1, -1, -1, -1};
8370   int PSHUFDMask[4] = {-1, -1, -1, -1};
8371
8372   // First fix the masks for all the inputs that are staying in their
8373   // original halves. This will then dictate the targets of the cross-half
8374   // shuffles.
8375   auto fixInPlaceInputs =
8376       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8377                     MutableArrayRef<int> SourceHalfMask,
8378                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8379     if (InPlaceInputs.empty())
8380       return;
8381     if (InPlaceInputs.size() == 1) {
8382       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8383           InPlaceInputs[0] - HalfOffset;
8384       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8385       return;
8386     }
8387     if (IncomingInputs.empty()) {
8388       // Just fix all of the in place inputs.
8389       for (int Input : InPlaceInputs) {
8390         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8391         PSHUFDMask[Input / 2] = Input / 2;
8392       }
8393       return;
8394     }
8395
8396     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8397     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8398         InPlaceInputs[0] - HalfOffset;
8399     // Put the second input next to the first so that they are packed into
8400     // a dword. We find the adjacent index by toggling the low bit.
8401     int AdjIndex = InPlaceInputs[0] ^ 1;
8402     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8403     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8404     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8405   };
8406   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8407   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8408
8409   // Now gather the cross-half inputs and place them into a free dword of
8410   // their target half.
8411   // FIXME: This operation could almost certainly be simplified dramatically to
8412   // look more like the 3-1 fixing operation.
8413   auto moveInputsToRightHalf = [&PSHUFDMask](
8414       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8415       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8416       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8417       int DestOffset) {
8418     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8419       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8420     };
8421     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8422                                                int Word) {
8423       int LowWord = Word & ~1;
8424       int HighWord = Word | 1;
8425       return isWordClobbered(SourceHalfMask, LowWord) ||
8426              isWordClobbered(SourceHalfMask, HighWord);
8427     };
8428
8429     if (IncomingInputs.empty())
8430       return;
8431
8432     if (ExistingInputs.empty()) {
8433       // Map any dwords with inputs from them into the right half.
8434       for (int Input : IncomingInputs) {
8435         // If the source half mask maps over the inputs, turn those into
8436         // swaps and use the swapped lane.
8437         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8438           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8439             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8440                 Input - SourceOffset;
8441             // We have to swap the uses in our half mask in one sweep.
8442             for (int &M : HalfMask)
8443               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8444                 M = Input;
8445               else if (M == Input)
8446                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8447           } else {
8448             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8449                        Input - SourceOffset &&
8450                    "Previous placement doesn't match!");
8451           }
8452           // Note that this correctly re-maps both when we do a swap and when
8453           // we observe the other side of the swap above. We rely on that to
8454           // avoid swapping the members of the input list directly.
8455           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8456         }
8457
8458         // Map the input's dword into the correct half.
8459         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8460           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8461         else
8462           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8463                      Input / 2 &&
8464                  "Previous placement doesn't match!");
8465       }
8466
8467       // And just directly shift any other-half mask elements to be same-half
8468       // as we will have mirrored the dword containing the element into the
8469       // same position within that half.
8470       for (int &M : HalfMask)
8471         if (M >= SourceOffset && M < SourceOffset + 4) {
8472           M = M - SourceOffset + DestOffset;
8473           assert(M >= 0 && "This should never wrap below zero!");
8474         }
8475       return;
8476     }
8477
8478     // Ensure we have the input in a viable dword of its current half. This
8479     // is particularly tricky because the original position may be clobbered
8480     // by inputs being moved and *staying* in that half.
8481     if (IncomingInputs.size() == 1) {
8482       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8483         int InputFixed = std::find(std::begin(SourceHalfMask),
8484                                    std::end(SourceHalfMask), -1) -
8485                          std::begin(SourceHalfMask) + SourceOffset;
8486         SourceHalfMask[InputFixed - SourceOffset] =
8487             IncomingInputs[0] - SourceOffset;
8488         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8489                      InputFixed);
8490         IncomingInputs[0] = InputFixed;
8491       }
8492     } else if (IncomingInputs.size() == 2) {
8493       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8494           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8495         // We have two non-adjacent or clobbered inputs we need to extract from
8496         // the source half. To do this, we need to map them into some adjacent
8497         // dword slot in the source mask.
8498         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8499                               IncomingInputs[1] - SourceOffset};
8500
8501         // If there is a free slot in the source half mask adjacent to one of
8502         // the inputs, place the other input in it. We use (Index XOR 1) to
8503         // compute an adjacent index.
8504         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8505             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8506           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8507           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8508           InputsFixed[1] = InputsFixed[0] ^ 1;
8509         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8510                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8511           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8512           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8513           InputsFixed[0] = InputsFixed[1] ^ 1;
8514         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8515                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8516           // The two inputs are in the same DWord but it is clobbered and the
8517           // adjacent DWord isn't used at all. Move both inputs to the free
8518           // slot.
8519           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8520           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8521           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8522           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8523         } else {
8524           // The only way we hit this point is if there is no clobbering
8525           // (because there are no off-half inputs to this half) and there is no
8526           // free slot adjacent to one of the inputs. In this case, we have to
8527           // swap an input with a non-input.
8528           for (int i = 0; i < 4; ++i)
8529             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8530                    "We can't handle any clobbers here!");
8531           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8532                  "Cannot have adjacent inputs here!");
8533
8534           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8535           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8536
8537           // We also have to update the final source mask in this case because
8538           // it may need to undo the above swap.
8539           for (int &M : FinalSourceHalfMask)
8540             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8541               M = InputsFixed[1] + SourceOffset;
8542             else if (M == InputsFixed[1] + SourceOffset)
8543               M = (InputsFixed[0] ^ 1) + SourceOffset;
8544
8545           InputsFixed[1] = InputsFixed[0] ^ 1;
8546         }
8547
8548         // Point everything at the fixed inputs.
8549         for (int &M : HalfMask)
8550           if (M == IncomingInputs[0])
8551             M = InputsFixed[0] + SourceOffset;
8552           else if (M == IncomingInputs[1])
8553             M = InputsFixed[1] + SourceOffset;
8554
8555         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8556         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8557       }
8558     } else {
8559       llvm_unreachable("Unhandled input size!");
8560     }
8561
8562     // Now hoist the DWord down to the right half.
8563     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8564     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8565     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8566     for (int &M : HalfMask)
8567       for (int Input : IncomingInputs)
8568         if (M == Input)
8569           M = FreeDWord * 2 + Input % 2;
8570   };
8571   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8572                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8573   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8574                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8575
8576   // Now enact all the shuffles we've computed to move the inputs into their
8577   // target half.
8578   if (!isNoopShuffleMask(PSHUFLMask))
8579     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8580                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8581   if (!isNoopShuffleMask(PSHUFHMask))
8582     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8583                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8584   if (!isNoopShuffleMask(PSHUFDMask))
8585     V = DAG.getBitcast(
8586         VT,
8587         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8588                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8589
8590   // At this point, each half should contain all its inputs, and we can then
8591   // just shuffle them into their final position.
8592   assert(std::count_if(LoMask.begin(), LoMask.end(),
8593                        [](int M) { return M >= 4; }) == 0 &&
8594          "Failed to lift all the high half inputs to the low mask!");
8595   assert(std::count_if(HiMask.begin(), HiMask.end(),
8596                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8597          "Failed to lift all the low half inputs to the high mask!");
8598
8599   // Do a half shuffle for the low mask.
8600   if (!isNoopShuffleMask(LoMask))
8601     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8602                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8603
8604   // Do a half shuffle with the high mask after shifting its values down.
8605   for (int &M : HiMask)
8606     if (M >= 0)
8607       M -= 4;
8608   if (!isNoopShuffleMask(HiMask))
8609     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8610                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8611
8612   return V;
8613 }
8614
8615 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8616 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8617                                           SDValue V2, ArrayRef<int> Mask,
8618                                           SelectionDAG &DAG, bool &V1InUse,
8619                                           bool &V2InUse) {
8620   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8621   SDValue V1Mask[16];
8622   SDValue V2Mask[16];
8623   V1InUse = false;
8624   V2InUse = false;
8625
8626   int Size = Mask.size();
8627   int Scale = 16 / Size;
8628   for (int i = 0; i < 16; ++i) {
8629     if (Mask[i / Scale] == -1) {
8630       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8631     } else {
8632       const int ZeroMask = 0x80;
8633       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8634                                           : ZeroMask;
8635       int V2Idx = Mask[i / Scale] < Size
8636                       ? ZeroMask
8637                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8638       if (Zeroable[i / Scale])
8639         V1Idx = V2Idx = ZeroMask;
8640       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8641       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8642       V1InUse |= (ZeroMask != V1Idx);
8643       V2InUse |= (ZeroMask != V2Idx);
8644     }
8645   }
8646
8647   if (V1InUse)
8648     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8649                      DAG.getBitcast(MVT::v16i8, V1),
8650                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8651   if (V2InUse)
8652     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8653                      DAG.getBitcast(MVT::v16i8, V2),
8654                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8655
8656   // If we need shuffled inputs from both, blend the two.
8657   SDValue V;
8658   if (V1InUse && V2InUse)
8659     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8660   else
8661     V = V1InUse ? V1 : V2;
8662
8663   // Cast the result back to the correct type.
8664   return DAG.getBitcast(VT, V);
8665 }
8666
8667 /// \brief Generic lowering of 8-lane i16 shuffles.
8668 ///
8669 /// This handles both single-input shuffles and combined shuffle/blends with
8670 /// two inputs. The single input shuffles are immediately delegated to
8671 /// a dedicated lowering routine.
8672 ///
8673 /// The blends are lowered in one of three fundamental ways. If there are few
8674 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8675 /// of the input is significantly cheaper when lowered as an interleaving of
8676 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8677 /// halves of the inputs separately (making them have relatively few inputs)
8678 /// and then concatenate them.
8679 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8680                                        const X86Subtarget *Subtarget,
8681                                        SelectionDAG &DAG) {
8682   SDLoc DL(Op);
8683   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8684   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8685   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8686   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8687   ArrayRef<int> OrigMask = SVOp->getMask();
8688   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8689                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8690   MutableArrayRef<int> Mask(MaskStorage);
8691
8692   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8693
8694   // Whenever we can lower this as a zext, that instruction is strictly faster
8695   // than any alternative.
8696   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8697           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8698     return ZExt;
8699
8700   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8701   (void)isV1;
8702   auto isV2 = [](int M) { return M >= 8; };
8703
8704   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8705
8706   if (NumV2Inputs == 0) {
8707     // Check for being able to broadcast a single element.
8708     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8709                                                           Mask, Subtarget, DAG))
8710       return Broadcast;
8711
8712     // Try to use shift instructions.
8713     if (SDValue Shift =
8714             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8715       return Shift;
8716
8717     // Use dedicated unpack instructions for masks that match their pattern.
8718     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8719       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8720     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8721       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8722
8723     // Try to use byte rotation instructions.
8724     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8725                                                         Mask, Subtarget, DAG))
8726       return Rotate;
8727
8728     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8729                                                      Subtarget, DAG);
8730   }
8731
8732   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8733          "All single-input shuffles should be canonicalized to be V1-input "
8734          "shuffles.");
8735
8736   // Try to use shift instructions.
8737   if (SDValue Shift =
8738           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8739     return Shift;
8740
8741   // See if we can use SSE4A Extraction / Insertion.
8742   if (Subtarget->hasSSE4A())
8743     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8744       return V;
8745
8746   // There are special ways we can lower some single-element blends.
8747   if (NumV2Inputs == 1)
8748     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8749                                                          Mask, Subtarget, DAG))
8750       return V;
8751
8752   // We have different paths for blend lowering, but they all must use the
8753   // *exact* same predicate.
8754   bool IsBlendSupported = Subtarget->hasSSE41();
8755   if (IsBlendSupported)
8756     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8757                                                   Subtarget, DAG))
8758       return Blend;
8759
8760   if (SDValue Masked =
8761           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8762     return Masked;
8763
8764   // Use dedicated unpack instructions for masks that match their pattern.
8765   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8766     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8767   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8768     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8769
8770   // Try to use byte rotation instructions.
8771   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8772           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8773     return Rotate;
8774
8775   if (SDValue BitBlend =
8776           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8777     return BitBlend;
8778
8779   if (SDValue Unpack =
8780           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8781     return Unpack;
8782
8783   // If we can't directly blend but can use PSHUFB, that will be better as it
8784   // can both shuffle and set up the inefficient blend.
8785   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8786     bool V1InUse, V2InUse;
8787     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8788                                       V1InUse, V2InUse);
8789   }
8790
8791   // We can always bit-blend if we have to so the fallback strategy is to
8792   // decompose into single-input permutes and blends.
8793   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8794                                                       Mask, DAG);
8795 }
8796
8797 /// \brief Check whether a compaction lowering can be done by dropping even
8798 /// elements and compute how many times even elements must be dropped.
8799 ///
8800 /// This handles shuffles which take every Nth element where N is a power of
8801 /// two. Example shuffle masks:
8802 ///
8803 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8804 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8805 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8806 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8807 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8808 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8809 ///
8810 /// Any of these lanes can of course be undef.
8811 ///
8812 /// This routine only supports N <= 3.
8813 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8814 /// for larger N.
8815 ///
8816 /// \returns N above, or the number of times even elements must be dropped if
8817 /// there is such a number. Otherwise returns zero.
8818 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8819   // Figure out whether we're looping over two inputs or just one.
8820   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8821
8822   // The modulus for the shuffle vector entries is based on whether this is
8823   // a single input or not.
8824   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8825   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8826          "We should only be called with masks with a power-of-2 size!");
8827
8828   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8829
8830   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8831   // and 2^3 simultaneously. This is because we may have ambiguity with
8832   // partially undef inputs.
8833   bool ViableForN[3] = {true, true, true};
8834
8835   for (int i = 0, e = Mask.size(); i < e; ++i) {
8836     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8837     // want.
8838     if (Mask[i] == -1)
8839       continue;
8840
8841     bool IsAnyViable = false;
8842     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8843       if (ViableForN[j]) {
8844         uint64_t N = j + 1;
8845
8846         // The shuffle mask must be equal to (i * 2^N) % M.
8847         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8848           IsAnyViable = true;
8849         else
8850           ViableForN[j] = false;
8851       }
8852     // Early exit if we exhaust the possible powers of two.
8853     if (!IsAnyViable)
8854       break;
8855   }
8856
8857   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8858     if (ViableForN[j])
8859       return j + 1;
8860
8861   // Return 0 as there is no viable power of two.
8862   return 0;
8863 }
8864
8865 /// \brief Generic lowering of v16i8 shuffles.
8866 ///
8867 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8868 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8869 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8870 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8871 /// back together.
8872 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8873                                        const X86Subtarget *Subtarget,
8874                                        SelectionDAG &DAG) {
8875   SDLoc DL(Op);
8876   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8877   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8878   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8879   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8880   ArrayRef<int> Mask = SVOp->getMask();
8881   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8882
8883   // Try to use shift instructions.
8884   if (SDValue Shift =
8885           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8886     return Shift;
8887
8888   // Try to use byte rotation instructions.
8889   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8890           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8891     return Rotate;
8892
8893   // Try to use a zext lowering.
8894   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8895           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8896     return ZExt;
8897
8898   // See if we can use SSE4A Extraction / Insertion.
8899   if (Subtarget->hasSSE4A())
8900     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8901       return V;
8902
8903   int NumV2Elements =
8904       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8905
8906   // For single-input shuffles, there are some nicer lowering tricks we can use.
8907   if (NumV2Elements == 0) {
8908     // Check for being able to broadcast a single element.
8909     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8910                                                           Mask, Subtarget, DAG))
8911       return Broadcast;
8912
8913     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8914     // Notably, this handles splat and partial-splat shuffles more efficiently.
8915     // However, it only makes sense if the pre-duplication shuffle simplifies
8916     // things significantly. Currently, this means we need to be able to
8917     // express the pre-duplication shuffle as an i16 shuffle.
8918     //
8919     // FIXME: We should check for other patterns which can be widened into an
8920     // i16 shuffle as well.
8921     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8922       for (int i = 0; i < 16; i += 2)
8923         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8924           return false;
8925
8926       return true;
8927     };
8928     auto tryToWidenViaDuplication = [&]() -> SDValue {
8929       if (!canWidenViaDuplication(Mask))
8930         return SDValue();
8931       SmallVector<int, 4> LoInputs;
8932       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8933                    [](int M) { return M >= 0 && M < 8; });
8934       std::sort(LoInputs.begin(), LoInputs.end());
8935       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8936                      LoInputs.end());
8937       SmallVector<int, 4> HiInputs;
8938       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8939                    [](int M) { return M >= 8; });
8940       std::sort(HiInputs.begin(), HiInputs.end());
8941       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8942                      HiInputs.end());
8943
8944       bool TargetLo = LoInputs.size() >= HiInputs.size();
8945       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8946       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8947
8948       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8949       SmallDenseMap<int, int, 8> LaneMap;
8950       for (int I : InPlaceInputs) {
8951         PreDupI16Shuffle[I/2] = I/2;
8952         LaneMap[I] = I;
8953       }
8954       int j = TargetLo ? 0 : 4, je = j + 4;
8955       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8956         // Check if j is already a shuffle of this input. This happens when
8957         // there are two adjacent bytes after we move the low one.
8958         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8959           // If we haven't yet mapped the input, search for a slot into which
8960           // we can map it.
8961           while (j < je && PreDupI16Shuffle[j] != -1)
8962             ++j;
8963
8964           if (j == je)
8965             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8966             return SDValue();
8967
8968           // Map this input with the i16 shuffle.
8969           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8970         }
8971
8972         // Update the lane map based on the mapping we ended up with.
8973         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8974       }
8975       V1 = DAG.getBitcast(
8976           MVT::v16i8,
8977           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8978                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8979
8980       // Unpack the bytes to form the i16s that will be shuffled into place.
8981       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8982                        MVT::v16i8, V1, V1);
8983
8984       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8985       for (int i = 0; i < 16; ++i)
8986         if (Mask[i] != -1) {
8987           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8988           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8989           if (PostDupI16Shuffle[i / 2] == -1)
8990             PostDupI16Shuffle[i / 2] = MappedMask;
8991           else
8992             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8993                    "Conflicting entrties in the original shuffle!");
8994         }
8995       return DAG.getBitcast(
8996           MVT::v16i8,
8997           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8998                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8999     };
9000     if (SDValue V = tryToWidenViaDuplication())
9001       return V;
9002   }
9003
9004   // Use dedicated unpack instructions for masks that match their pattern.
9005   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9006                                          0, 16, 1, 17, 2, 18, 3, 19,
9007                                          // High half.
9008                                          4, 20, 5, 21, 6, 22, 7, 23}))
9009     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9010   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9011                                          8, 24, 9, 25, 10, 26, 11, 27,
9012                                          // High half.
9013                                          12, 28, 13, 29, 14, 30, 15, 31}))
9014     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9015
9016   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9017   // with PSHUFB. It is important to do this before we attempt to generate any
9018   // blends but after all of the single-input lowerings. If the single input
9019   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9020   // want to preserve that and we can DAG combine any longer sequences into
9021   // a PSHUFB in the end. But once we start blending from multiple inputs,
9022   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9023   // and there are *very* few patterns that would actually be faster than the
9024   // PSHUFB approach because of its ability to zero lanes.
9025   //
9026   // FIXME: The only exceptions to the above are blends which are exact
9027   // interleavings with direct instructions supporting them. We currently don't
9028   // handle those well here.
9029   if (Subtarget->hasSSSE3()) {
9030     bool V1InUse = false;
9031     bool V2InUse = false;
9032
9033     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9034                                                 DAG, V1InUse, V2InUse);
9035
9036     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9037     // do so. This avoids using them to handle blends-with-zero which is
9038     // important as a single pshufb is significantly faster for that.
9039     if (V1InUse && V2InUse) {
9040       if (Subtarget->hasSSE41())
9041         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9042                                                       Mask, Subtarget, DAG))
9043           return Blend;
9044
9045       // We can use an unpack to do the blending rather than an or in some
9046       // cases. Even though the or may be (very minorly) more efficient, we
9047       // preference this lowering because there are common cases where part of
9048       // the complexity of the shuffles goes away when we do the final blend as
9049       // an unpack.
9050       // FIXME: It might be worth trying to detect if the unpack-feeding
9051       // shuffles will both be pshufb, in which case we shouldn't bother with
9052       // this.
9053       if (SDValue Unpack =
9054               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9055         return Unpack;
9056     }
9057
9058     return PSHUFB;
9059   }
9060
9061   // There are special ways we can lower some single-element blends.
9062   if (NumV2Elements == 1)
9063     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9064                                                          Mask, Subtarget, DAG))
9065       return V;
9066
9067   if (SDValue BitBlend =
9068           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9069     return BitBlend;
9070
9071   // Check whether a compaction lowering can be done. This handles shuffles
9072   // which take every Nth element for some even N. See the helper function for
9073   // details.
9074   //
9075   // We special case these as they can be particularly efficiently handled with
9076   // the PACKUSB instruction on x86 and they show up in common patterns of
9077   // rearranging bytes to truncate wide elements.
9078   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9079     // NumEvenDrops is the power of two stride of the elements. Another way of
9080     // thinking about it is that we need to drop the even elements this many
9081     // times to get the original input.
9082     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9083
9084     // First we need to zero all the dropped bytes.
9085     assert(NumEvenDrops <= 3 &&
9086            "No support for dropping even elements more than 3 times.");
9087     // We use the mask type to pick which bytes are preserved based on how many
9088     // elements are dropped.
9089     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9090     SDValue ByteClearMask = DAG.getBitcast(
9091         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9092     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9093     if (!IsSingleInput)
9094       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9095
9096     // Now pack things back together.
9097     V1 = DAG.getBitcast(MVT::v8i16, V1);
9098     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9099     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9100     for (int i = 1; i < NumEvenDrops; ++i) {
9101       Result = DAG.getBitcast(MVT::v8i16, Result);
9102       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9103     }
9104
9105     return Result;
9106   }
9107
9108   // Handle multi-input cases by blending single-input shuffles.
9109   if (NumV2Elements > 0)
9110     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9111                                                       Mask, DAG);
9112
9113   // The fallback path for single-input shuffles widens this into two v8i16
9114   // vectors with unpacks, shuffles those, and then pulls them back together
9115   // with a pack.
9116   SDValue V = V1;
9117
9118   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9119   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9120   for (int i = 0; i < 16; ++i)
9121     if (Mask[i] >= 0)
9122       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9123
9124   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9125
9126   SDValue VLoHalf, VHiHalf;
9127   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9128   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9129   // i16s.
9130   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9131                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9132       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9133                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9134     // Use a mask to drop the high bytes.
9135     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9136     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9137                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9138
9139     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9140     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9141
9142     // Squash the masks to point directly into VLoHalf.
9143     for (int &M : LoBlendMask)
9144       if (M >= 0)
9145         M /= 2;
9146     for (int &M : HiBlendMask)
9147       if (M >= 0)
9148         M /= 2;
9149   } else {
9150     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9151     // VHiHalf so that we can blend them as i16s.
9152     VLoHalf = DAG.getBitcast(
9153         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9154     VHiHalf = DAG.getBitcast(
9155         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9156   }
9157
9158   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9159   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9160
9161   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9162 }
9163
9164 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9165 ///
9166 /// This routine breaks down the specific type of 128-bit shuffle and
9167 /// dispatches to the lowering routines accordingly.
9168 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9169                                         MVT VT, const X86Subtarget *Subtarget,
9170                                         SelectionDAG &DAG) {
9171   switch (VT.SimpleTy) {
9172   case MVT::v2i64:
9173     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9174   case MVT::v2f64:
9175     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9176   case MVT::v4i32:
9177     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9178   case MVT::v4f32:
9179     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9180   case MVT::v8i16:
9181     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9182   case MVT::v16i8:
9183     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9184
9185   default:
9186     llvm_unreachable("Unimplemented!");
9187   }
9188 }
9189
9190 /// \brief Helper function to test whether a shuffle mask could be
9191 /// simplified by widening the elements being shuffled.
9192 ///
9193 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9194 /// leaves it in an unspecified state.
9195 ///
9196 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9197 /// shuffle masks. The latter have the special property of a '-2' representing
9198 /// a zero-ed lane of a vector.
9199 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9200                                     SmallVectorImpl<int> &WidenedMask) {
9201   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9202     // If both elements are undef, its trivial.
9203     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9204       WidenedMask.push_back(SM_SentinelUndef);
9205       continue;
9206     }
9207
9208     // Check for an undef mask and a mask value properly aligned to fit with
9209     // a pair of values. If we find such a case, use the non-undef mask's value.
9210     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9211       WidenedMask.push_back(Mask[i + 1] / 2);
9212       continue;
9213     }
9214     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9215       WidenedMask.push_back(Mask[i] / 2);
9216       continue;
9217     }
9218
9219     // When zeroing, we need to spread the zeroing across both lanes to widen.
9220     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9221       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9222           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9223         WidenedMask.push_back(SM_SentinelZero);
9224         continue;
9225       }
9226       return false;
9227     }
9228
9229     // Finally check if the two mask values are adjacent and aligned with
9230     // a pair.
9231     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9232       WidenedMask.push_back(Mask[i] / 2);
9233       continue;
9234     }
9235
9236     // Otherwise we can't safely widen the elements used in this shuffle.
9237     return false;
9238   }
9239   assert(WidenedMask.size() == Mask.size() / 2 &&
9240          "Incorrect size of mask after widening the elements!");
9241
9242   return true;
9243 }
9244
9245 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9246 ///
9247 /// This routine just extracts two subvectors, shuffles them independently, and
9248 /// then concatenates them back together. This should work effectively with all
9249 /// AVX vector shuffle types.
9250 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9251                                           SDValue V2, ArrayRef<int> Mask,
9252                                           SelectionDAG &DAG) {
9253   assert(VT.getSizeInBits() >= 256 &&
9254          "Only for 256-bit or wider vector shuffles!");
9255   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9256   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9257
9258   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9259   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9260
9261   int NumElements = VT.getVectorNumElements();
9262   int SplitNumElements = NumElements / 2;
9263   MVT ScalarVT = VT.getScalarType();
9264   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9265
9266   // Rather than splitting build-vectors, just build two narrower build
9267   // vectors. This helps shuffling with splats and zeros.
9268   auto SplitVector = [&](SDValue V) {
9269     while (V.getOpcode() == ISD::BITCAST)
9270       V = V->getOperand(0);
9271
9272     MVT OrigVT = V.getSimpleValueType();
9273     int OrigNumElements = OrigVT.getVectorNumElements();
9274     int OrigSplitNumElements = OrigNumElements / 2;
9275     MVT OrigScalarVT = OrigVT.getScalarType();
9276     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9277
9278     SDValue LoV, HiV;
9279
9280     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9281     if (!BV) {
9282       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9283                         DAG.getIntPtrConstant(0, DL));
9284       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9285                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9286     } else {
9287
9288       SmallVector<SDValue, 16> LoOps, HiOps;
9289       for (int i = 0; i < OrigSplitNumElements; ++i) {
9290         LoOps.push_back(BV->getOperand(i));
9291         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9292       }
9293       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9294       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9295     }
9296     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9297                           DAG.getBitcast(SplitVT, HiV));
9298   };
9299
9300   SDValue LoV1, HiV1, LoV2, HiV2;
9301   std::tie(LoV1, HiV1) = SplitVector(V1);
9302   std::tie(LoV2, HiV2) = SplitVector(V2);
9303
9304   // Now create two 4-way blends of these half-width vectors.
9305   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9306     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9307     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9308     for (int i = 0; i < SplitNumElements; ++i) {
9309       int M = HalfMask[i];
9310       if (M >= NumElements) {
9311         if (M >= NumElements + SplitNumElements)
9312           UseHiV2 = true;
9313         else
9314           UseLoV2 = true;
9315         V2BlendMask.push_back(M - NumElements);
9316         V1BlendMask.push_back(-1);
9317         BlendMask.push_back(SplitNumElements + i);
9318       } else if (M >= 0) {
9319         if (M >= SplitNumElements)
9320           UseHiV1 = true;
9321         else
9322           UseLoV1 = true;
9323         V2BlendMask.push_back(-1);
9324         V1BlendMask.push_back(M);
9325         BlendMask.push_back(i);
9326       } else {
9327         V2BlendMask.push_back(-1);
9328         V1BlendMask.push_back(-1);
9329         BlendMask.push_back(-1);
9330       }
9331     }
9332
9333     // Because the lowering happens after all combining takes place, we need to
9334     // manually combine these blend masks as much as possible so that we create
9335     // a minimal number of high-level vector shuffle nodes.
9336
9337     // First try just blending the halves of V1 or V2.
9338     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9339       return DAG.getUNDEF(SplitVT);
9340     if (!UseLoV2 && !UseHiV2)
9341       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9342     if (!UseLoV1 && !UseHiV1)
9343       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9344
9345     SDValue V1Blend, V2Blend;
9346     if (UseLoV1 && UseHiV1) {
9347       V1Blend =
9348         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9349     } else {
9350       // We only use half of V1 so map the usage down into the final blend mask.
9351       V1Blend = UseLoV1 ? LoV1 : HiV1;
9352       for (int i = 0; i < SplitNumElements; ++i)
9353         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9354           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9355     }
9356     if (UseLoV2 && UseHiV2) {
9357       V2Blend =
9358         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9359     } else {
9360       // We only use half of V2 so map the usage down into the final blend mask.
9361       V2Blend = UseLoV2 ? LoV2 : HiV2;
9362       for (int i = 0; i < SplitNumElements; ++i)
9363         if (BlendMask[i] >= SplitNumElements)
9364           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9365     }
9366     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9367   };
9368   SDValue Lo = HalfBlend(LoMask);
9369   SDValue Hi = HalfBlend(HiMask);
9370   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9371 }
9372
9373 /// \brief Either split a vector in halves or decompose the shuffles and the
9374 /// blend.
9375 ///
9376 /// This is provided as a good fallback for many lowerings of non-single-input
9377 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9378 /// between splitting the shuffle into 128-bit components and stitching those
9379 /// back together vs. extracting the single-input shuffles and blending those
9380 /// results.
9381 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9382                                                 SDValue V2, ArrayRef<int> Mask,
9383                                                 SelectionDAG &DAG) {
9384   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9385                                             "lower single-input shuffles as it "
9386                                             "could then recurse on itself.");
9387   int Size = Mask.size();
9388
9389   // If this can be modeled as a broadcast of two elements followed by a blend,
9390   // prefer that lowering. This is especially important because broadcasts can
9391   // often fold with memory operands.
9392   auto DoBothBroadcast = [&] {
9393     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9394     for (int M : Mask)
9395       if (M >= Size) {
9396         if (V2BroadcastIdx == -1)
9397           V2BroadcastIdx = M - Size;
9398         else if (M - Size != V2BroadcastIdx)
9399           return false;
9400       } else if (M >= 0) {
9401         if (V1BroadcastIdx == -1)
9402           V1BroadcastIdx = M;
9403         else if (M != V1BroadcastIdx)
9404           return false;
9405       }
9406     return true;
9407   };
9408   if (DoBothBroadcast())
9409     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9410                                                       DAG);
9411
9412   // If the inputs all stem from a single 128-bit lane of each input, then we
9413   // split them rather than blending because the split will decompose to
9414   // unusually few instructions.
9415   int LaneCount = VT.getSizeInBits() / 128;
9416   int LaneSize = Size / LaneCount;
9417   SmallBitVector LaneInputs[2];
9418   LaneInputs[0].resize(LaneCount, false);
9419   LaneInputs[1].resize(LaneCount, false);
9420   for (int i = 0; i < Size; ++i)
9421     if (Mask[i] >= 0)
9422       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9423   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9424     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9425
9426   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9427   // that the decomposed single-input shuffles don't end up here.
9428   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9429 }
9430
9431 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9432 /// a permutation and blend of those lanes.
9433 ///
9434 /// This essentially blends the out-of-lane inputs to each lane into the lane
9435 /// from a permuted copy of the vector. This lowering strategy results in four
9436 /// instructions in the worst case for a single-input cross lane shuffle which
9437 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9438 /// of. Special cases for each particular shuffle pattern should be handled
9439 /// prior to trying this lowering.
9440 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9441                                                        SDValue V1, SDValue V2,
9442                                                        ArrayRef<int> Mask,
9443                                                        SelectionDAG &DAG) {
9444   // FIXME: This should probably be generalized for 512-bit vectors as well.
9445   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9446   int LaneSize = Mask.size() / 2;
9447
9448   // If there are only inputs from one 128-bit lane, splitting will in fact be
9449   // less expensive. The flags track whether the given lane contains an element
9450   // that crosses to another lane.
9451   bool LaneCrossing[2] = {false, false};
9452   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9453     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9454       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9455   if (!LaneCrossing[0] || !LaneCrossing[1])
9456     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9457
9458   if (isSingleInputShuffleMask(Mask)) {
9459     SmallVector<int, 32> FlippedBlendMask;
9460     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9461       FlippedBlendMask.push_back(
9462           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9463                                   ? Mask[i]
9464                                   : Mask[i] % LaneSize +
9465                                         (i / LaneSize) * LaneSize + Size));
9466
9467     // Flip the vector, and blend the results which should now be in-lane. The
9468     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9469     // 5 for the high source. The value 3 selects the high half of source 2 and
9470     // the value 2 selects the low half of source 2. We only use source 2 to
9471     // allow folding it into a memory operand.
9472     unsigned PERMMask = 3 | 2 << 4;
9473     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9474                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9475     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9476   }
9477
9478   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9479   // will be handled by the above logic and a blend of the results, much like
9480   // other patterns in AVX.
9481   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9482 }
9483
9484 /// \brief Handle lowering 2-lane 128-bit shuffles.
9485 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9486                                         SDValue V2, ArrayRef<int> Mask,
9487                                         const X86Subtarget *Subtarget,
9488                                         SelectionDAG &DAG) {
9489   // TODO: If minimizing size and one of the inputs is a zero vector and the
9490   // the zero vector has only one use, we could use a VPERM2X128 to save the
9491   // instruction bytes needed to explicitly generate the zero vector.
9492
9493   // Blends are faster and handle all the non-lane-crossing cases.
9494   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9495                                                 Subtarget, DAG))
9496     return Blend;
9497
9498   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9499   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9500
9501   // If either input operand is a zero vector, use VPERM2X128 because its mask
9502   // allows us to replace the zero input with an implicit zero.
9503   if (!IsV1Zero && !IsV2Zero) {
9504     // Check for patterns which can be matched with a single insert of a 128-bit
9505     // subvector.
9506     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9507     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9508       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9509                                    VT.getVectorNumElements() / 2);
9510       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9511                                 DAG.getIntPtrConstant(0, DL));
9512       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9513                                 OnlyUsesV1 ? V1 : V2,
9514                                 DAG.getIntPtrConstant(0, DL));
9515       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9516     }
9517   }
9518
9519   // Otherwise form a 128-bit permutation. After accounting for undefs,
9520   // convert the 64-bit shuffle mask selection values into 128-bit
9521   // selection bits by dividing the indexes by 2 and shifting into positions
9522   // defined by a vperm2*128 instruction's immediate control byte.
9523
9524   // The immediate permute control byte looks like this:
9525   //    [1:0] - select 128 bits from sources for low half of destination
9526   //    [2]   - ignore
9527   //    [3]   - zero low half of destination
9528   //    [5:4] - select 128 bits from sources for high half of destination
9529   //    [6]   - ignore
9530   //    [7]   - zero high half of destination
9531
9532   int MaskLO = Mask[0];
9533   if (MaskLO == SM_SentinelUndef)
9534     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9535
9536   int MaskHI = Mask[2];
9537   if (MaskHI == SM_SentinelUndef)
9538     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9539
9540   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9541
9542   // If either input is a zero vector, replace it with an undef input.
9543   // Shuffle mask values <  4 are selecting elements of V1.
9544   // Shuffle mask values >= 4 are selecting elements of V2.
9545   // Adjust each half of the permute mask by clearing the half that was
9546   // selecting the zero vector and setting the zero mask bit.
9547   if (IsV1Zero) {
9548     V1 = DAG.getUNDEF(VT);
9549     if (MaskLO < 4)
9550       PermMask = (PermMask & 0xf0) | 0x08;
9551     if (MaskHI < 4)
9552       PermMask = (PermMask & 0x0f) | 0x80;
9553   }
9554   if (IsV2Zero) {
9555     V2 = DAG.getUNDEF(VT);
9556     if (MaskLO >= 4)
9557       PermMask = (PermMask & 0xf0) | 0x08;
9558     if (MaskHI >= 4)
9559       PermMask = (PermMask & 0x0f) | 0x80;
9560   }
9561
9562   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9563                      DAG.getConstant(PermMask, DL, MVT::i8));
9564 }
9565
9566 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9567 /// shuffling each lane.
9568 ///
9569 /// This will only succeed when the result of fixing the 128-bit lanes results
9570 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9571 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9572 /// the lane crosses early and then use simpler shuffles within each lane.
9573 ///
9574 /// FIXME: It might be worthwhile at some point to support this without
9575 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9576 /// in x86 only floating point has interesting non-repeating shuffles, and even
9577 /// those are still *marginally* more expensive.
9578 static SDValue lowerVectorShuffleByMerging128BitLanes(
9579     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9580     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9581   assert(!isSingleInputShuffleMask(Mask) &&
9582          "This is only useful with multiple inputs.");
9583
9584   int Size = Mask.size();
9585   int LaneSize = 128 / VT.getScalarSizeInBits();
9586   int NumLanes = Size / LaneSize;
9587   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9588
9589   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9590   // check whether the in-128-bit lane shuffles share a repeating pattern.
9591   SmallVector<int, 4> Lanes;
9592   Lanes.resize(NumLanes, -1);
9593   SmallVector<int, 4> InLaneMask;
9594   InLaneMask.resize(LaneSize, -1);
9595   for (int i = 0; i < Size; ++i) {
9596     if (Mask[i] < 0)
9597       continue;
9598
9599     int j = i / LaneSize;
9600
9601     if (Lanes[j] < 0) {
9602       // First entry we've seen for this lane.
9603       Lanes[j] = Mask[i] / LaneSize;
9604     } else if (Lanes[j] != Mask[i] / LaneSize) {
9605       // This doesn't match the lane selected previously!
9606       return SDValue();
9607     }
9608
9609     // Check that within each lane we have a consistent shuffle mask.
9610     int k = i % LaneSize;
9611     if (InLaneMask[k] < 0) {
9612       InLaneMask[k] = Mask[i] % LaneSize;
9613     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9614       // This doesn't fit a repeating in-lane mask.
9615       return SDValue();
9616     }
9617   }
9618
9619   // First shuffle the lanes into place.
9620   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9621                                 VT.getSizeInBits() / 64);
9622   SmallVector<int, 8> LaneMask;
9623   LaneMask.resize(NumLanes * 2, -1);
9624   for (int i = 0; i < NumLanes; ++i)
9625     if (Lanes[i] >= 0) {
9626       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9627       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9628     }
9629
9630   V1 = DAG.getBitcast(LaneVT, V1);
9631   V2 = DAG.getBitcast(LaneVT, V2);
9632   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9633
9634   // Cast it back to the type we actually want.
9635   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9636
9637   // Now do a simple shuffle that isn't lane crossing.
9638   SmallVector<int, 8> NewMask;
9639   NewMask.resize(Size, -1);
9640   for (int i = 0; i < Size; ++i)
9641     if (Mask[i] >= 0)
9642       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9643   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9644          "Must not introduce lane crosses at this point!");
9645
9646   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9647 }
9648
9649 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9650 /// given mask.
9651 ///
9652 /// This returns true if the elements from a particular input are already in the
9653 /// slot required by the given mask and require no permutation.
9654 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9655   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9656   int Size = Mask.size();
9657   for (int i = 0; i < Size; ++i)
9658     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9659       return false;
9660
9661   return true;
9662 }
9663
9664 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9665                                             ArrayRef<int> Mask, SDValue V1,
9666                                             SDValue V2, SelectionDAG &DAG) {
9667
9668   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9669   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9670   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9671   int NumElts = VT.getVectorNumElements();
9672   bool ShufpdMask = true;
9673   bool CommutableMask = true;
9674   unsigned Immediate = 0;
9675   for (int i = 0; i < NumElts; ++i) {
9676     if (Mask[i] < 0)
9677       continue;
9678     int Val = (i & 6) + NumElts * (i & 1);
9679     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9680     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9681       ShufpdMask = false;
9682     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9683       CommutableMask = false;
9684     Immediate |= (Mask[i] % 2) << i;
9685   }
9686   if (ShufpdMask)
9687     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9688                        DAG.getConstant(Immediate, DL, MVT::i8));
9689   if (CommutableMask)
9690     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9691                        DAG.getConstant(Immediate, DL, MVT::i8));
9692   return SDValue();
9693 }
9694
9695 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9696 ///
9697 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9698 /// isn't available.
9699 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9700                                        const X86Subtarget *Subtarget,
9701                                        SelectionDAG &DAG) {
9702   SDLoc DL(Op);
9703   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9704   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9705   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9706   ArrayRef<int> Mask = SVOp->getMask();
9707   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9708
9709   SmallVector<int, 4> WidenedMask;
9710   if (canWidenShuffleElements(Mask, WidenedMask))
9711     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9712                                     DAG);
9713
9714   if (isSingleInputShuffleMask(Mask)) {
9715     // Check for being able to broadcast a single element.
9716     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9717                                                           Mask, Subtarget, DAG))
9718       return Broadcast;
9719
9720     // Use low duplicate instructions for masks that match their pattern.
9721     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9722       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9723
9724     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9725       // Non-half-crossing single input shuffles can be lowerid with an
9726       // interleaved permutation.
9727       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9728                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9729       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9730                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9731     }
9732
9733     // With AVX2 we have direct support for this permutation.
9734     if (Subtarget->hasAVX2())
9735       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9736                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9737
9738     // Otherwise, fall back.
9739     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9740                                                    DAG);
9741   }
9742
9743   // X86 has dedicated unpack instructions that can handle specific blend
9744   // operations: UNPCKH and UNPCKL.
9745   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9746     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9747   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9748     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9749   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9750     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9751   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9752     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9753
9754   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9755                                                 Subtarget, DAG))
9756     return Blend;
9757
9758   // Check if the blend happens to exactly fit that of SHUFPD.
9759   if (SDValue Op =
9760       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9761     return Op;
9762
9763   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9764   // shuffle. However, if we have AVX2 and either inputs are already in place,
9765   // we will be able to shuffle even across lanes the other input in a single
9766   // instruction so skip this pattern.
9767   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9768                                  isShuffleMaskInputInPlace(1, Mask))))
9769     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9770             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9771       return Result;
9772
9773   // If we have AVX2 then we always want to lower with a blend because an v4 we
9774   // can fully permute the elements.
9775   if (Subtarget->hasAVX2())
9776     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9777                                                       Mask, DAG);
9778
9779   // Otherwise fall back on generic lowering.
9780   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9781 }
9782
9783 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9784 ///
9785 /// This routine is only called when we have AVX2 and thus a reasonable
9786 /// instruction set for v4i64 shuffling..
9787 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9788                                        const X86Subtarget *Subtarget,
9789                                        SelectionDAG &DAG) {
9790   SDLoc DL(Op);
9791   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9792   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9793   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9794   ArrayRef<int> Mask = SVOp->getMask();
9795   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9796   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9797
9798   SmallVector<int, 4> WidenedMask;
9799   if (canWidenShuffleElements(Mask, WidenedMask))
9800     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9801                                     DAG);
9802
9803   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9804                                                 Subtarget, DAG))
9805     return Blend;
9806
9807   // Check for being able to broadcast a single element.
9808   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9809                                                         Mask, Subtarget, DAG))
9810     return Broadcast;
9811
9812   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9813   // use lower latency instructions that will operate on both 128-bit lanes.
9814   SmallVector<int, 2> RepeatedMask;
9815   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9816     if (isSingleInputShuffleMask(Mask)) {
9817       int PSHUFDMask[] = {-1, -1, -1, -1};
9818       for (int i = 0; i < 2; ++i)
9819         if (RepeatedMask[i] >= 0) {
9820           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9821           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9822         }
9823       return DAG.getBitcast(
9824           MVT::v4i64,
9825           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9826                       DAG.getBitcast(MVT::v8i32, V1),
9827                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9828     }
9829   }
9830
9831   // AVX2 provides a direct instruction for permuting a single input across
9832   // lanes.
9833   if (isSingleInputShuffleMask(Mask))
9834     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9835                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9836
9837   // Try to use shift instructions.
9838   if (SDValue Shift =
9839           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9840     return Shift;
9841
9842   // Use dedicated unpack instructions for masks that match their pattern.
9843   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9844     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9845   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9846     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9847   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9848     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9849   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9850     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9851
9852   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9853   // shuffle. However, if we have AVX2 and either inputs are already in place,
9854   // we will be able to shuffle even across lanes the other input in a single
9855   // instruction so skip this pattern.
9856   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9857                                  isShuffleMaskInputInPlace(1, Mask))))
9858     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9859             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9860       return Result;
9861
9862   // Otherwise fall back on generic blend lowering.
9863   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9864                                                     Mask, DAG);
9865 }
9866
9867 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9868 ///
9869 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9870 /// isn't available.
9871 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9872                                        const X86Subtarget *Subtarget,
9873                                        SelectionDAG &DAG) {
9874   SDLoc DL(Op);
9875   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9876   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9877   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9878   ArrayRef<int> Mask = SVOp->getMask();
9879   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9880
9881   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9882                                                 Subtarget, DAG))
9883     return Blend;
9884
9885   // Check for being able to broadcast a single element.
9886   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9887                                                         Mask, Subtarget, DAG))
9888     return Broadcast;
9889
9890   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9891   // options to efficiently lower the shuffle.
9892   SmallVector<int, 4> RepeatedMask;
9893   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9894     assert(RepeatedMask.size() == 4 &&
9895            "Repeated masks must be half the mask width!");
9896
9897     // Use even/odd duplicate instructions for masks that match their pattern.
9898     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9899       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9900     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9901       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9902
9903     if (isSingleInputShuffleMask(Mask))
9904       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9905                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9906
9907     // Use dedicated unpack instructions for masks that match their pattern.
9908     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9909       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9910     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9911       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9912     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9913       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9914     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9915       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9916
9917     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9918     // have already handled any direct blends. We also need to squash the
9919     // repeated mask into a simulated v4f32 mask.
9920     for (int i = 0; i < 4; ++i)
9921       if (RepeatedMask[i] >= 8)
9922         RepeatedMask[i] -= 4;
9923     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9924   }
9925
9926   // If we have a single input shuffle with different shuffle patterns in the
9927   // two 128-bit lanes use the variable mask to VPERMILPS.
9928   if (isSingleInputShuffleMask(Mask)) {
9929     SDValue VPermMask[8];
9930     for (int i = 0; i < 8; ++i)
9931       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9932                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9933     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9934       return DAG.getNode(
9935           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9936           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9937
9938     if (Subtarget->hasAVX2())
9939       return DAG.getNode(
9940           X86ISD::VPERMV, DL, MVT::v8f32,
9941           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9942                                                  MVT::v8i32, VPermMask)),
9943           V1);
9944
9945     // Otherwise, fall back.
9946     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9947                                                    DAG);
9948   }
9949
9950   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9951   // shuffle.
9952   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9953           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9954     return Result;
9955
9956   // If we have AVX2 then we always want to lower with a blend because at v8 we
9957   // can fully permute the elements.
9958   if (Subtarget->hasAVX2())
9959     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9960                                                       Mask, DAG);
9961
9962   // Otherwise fall back on generic lowering.
9963   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9964 }
9965
9966 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9967 ///
9968 /// This routine is only called when we have AVX2 and thus a reasonable
9969 /// instruction set for v8i32 shuffling..
9970 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9971                                        const X86Subtarget *Subtarget,
9972                                        SelectionDAG &DAG) {
9973   SDLoc DL(Op);
9974   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9975   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9976   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9977   ArrayRef<int> Mask = SVOp->getMask();
9978   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9979   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9980
9981   // Whenever we can lower this as a zext, that instruction is strictly faster
9982   // than any alternative. It also allows us to fold memory operands into the
9983   // shuffle in many cases.
9984   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9985                                                          Mask, Subtarget, DAG))
9986     return ZExt;
9987
9988   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9989                                                 Subtarget, DAG))
9990     return Blend;
9991
9992   // Check for being able to broadcast a single element.
9993   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9994                                                         Mask, Subtarget, DAG))
9995     return Broadcast;
9996
9997   // If the shuffle mask is repeated in each 128-bit lane we can use more
9998   // efficient instructions that mirror the shuffles across the two 128-bit
9999   // lanes.
10000   SmallVector<int, 4> RepeatedMask;
10001   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10002     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10003     if (isSingleInputShuffleMask(Mask))
10004       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10005                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10006
10007     // Use dedicated unpack instructions for masks that match their pattern.
10008     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10009       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10010     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10011       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10012     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10013       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10014     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10015       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10016   }
10017
10018   // Try to use shift instructions.
10019   if (SDValue Shift =
10020           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10021     return Shift;
10022
10023   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10024           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10025     return Rotate;
10026
10027   // If the shuffle patterns aren't repeated but it is a single input, directly
10028   // generate a cross-lane VPERMD instruction.
10029   if (isSingleInputShuffleMask(Mask)) {
10030     SDValue VPermMask[8];
10031     for (int i = 0; i < 8; ++i)
10032       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10033                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10034     return DAG.getNode(
10035         X86ISD::VPERMV, DL, MVT::v8i32,
10036         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10037   }
10038
10039   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10040   // shuffle.
10041   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10042           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10043     return Result;
10044
10045   // Otherwise fall back on generic blend lowering.
10046   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10047                                                     Mask, DAG);
10048 }
10049
10050 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10051 ///
10052 /// This routine is only called when we have AVX2 and thus a reasonable
10053 /// instruction set for v16i16 shuffling..
10054 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10055                                         const X86Subtarget *Subtarget,
10056                                         SelectionDAG &DAG) {
10057   SDLoc DL(Op);
10058   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10059   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10060   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10061   ArrayRef<int> Mask = SVOp->getMask();
10062   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10063   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10064
10065   // Whenever we can lower this as a zext, that instruction is strictly faster
10066   // than any alternative. It also allows us to fold memory operands into the
10067   // shuffle in many cases.
10068   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10069                                                          Mask, Subtarget, DAG))
10070     return ZExt;
10071
10072   // Check for being able to broadcast a single element.
10073   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10074                                                         Mask, Subtarget, DAG))
10075     return Broadcast;
10076
10077   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10078                                                 Subtarget, DAG))
10079     return Blend;
10080
10081   // Use dedicated unpack instructions for masks that match their pattern.
10082   if (isShuffleEquivalent(V1, V2, Mask,
10083                           {// First 128-bit lane:
10084                            0, 16, 1, 17, 2, 18, 3, 19,
10085                            // Second 128-bit lane:
10086                            8, 24, 9, 25, 10, 26, 11, 27}))
10087     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10088   if (isShuffleEquivalent(V1, V2, Mask,
10089                           {// First 128-bit lane:
10090                            4, 20, 5, 21, 6, 22, 7, 23,
10091                            // Second 128-bit lane:
10092                            12, 28, 13, 29, 14, 30, 15, 31}))
10093     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10094
10095   // Try to use shift instructions.
10096   if (SDValue Shift =
10097           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10098     return Shift;
10099
10100   // Try to use byte rotation instructions.
10101   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10102           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10103     return Rotate;
10104
10105   if (isSingleInputShuffleMask(Mask)) {
10106     // There are no generalized cross-lane shuffle operations available on i16
10107     // element types.
10108     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10109       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10110                                                      Mask, DAG);
10111
10112     SmallVector<int, 8> RepeatedMask;
10113     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10114       // As this is a single-input shuffle, the repeated mask should be
10115       // a strictly valid v8i16 mask that we can pass through to the v8i16
10116       // lowering to handle even the v16 case.
10117       return lowerV8I16GeneralSingleInputVectorShuffle(
10118           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10119     }
10120
10121     SDValue PSHUFBMask[32];
10122     for (int i = 0; i < 16; ++i) {
10123       if (Mask[i] == -1) {
10124         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10125         continue;
10126       }
10127
10128       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10129       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10130       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10131       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10132     }
10133     return DAG.getBitcast(MVT::v16i16,
10134                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10135                                       DAG.getBitcast(MVT::v32i8, V1),
10136                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10137                                                   MVT::v32i8, PSHUFBMask)));
10138   }
10139
10140   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10141   // shuffle.
10142   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10143           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10144     return Result;
10145
10146   // Otherwise fall back on generic lowering.
10147   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10148 }
10149
10150 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10151 ///
10152 /// This routine is only called when we have AVX2 and thus a reasonable
10153 /// instruction set for v32i8 shuffling..
10154 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10155                                        const X86Subtarget *Subtarget,
10156                                        SelectionDAG &DAG) {
10157   SDLoc DL(Op);
10158   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10159   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10160   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10161   ArrayRef<int> Mask = SVOp->getMask();
10162   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10163   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10164
10165   // Whenever we can lower this as a zext, that instruction is strictly faster
10166   // than any alternative. It also allows us to fold memory operands into the
10167   // shuffle in many cases.
10168   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10169                                                          Mask, Subtarget, DAG))
10170     return ZExt;
10171
10172   // Check for being able to broadcast a single element.
10173   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10174                                                         Mask, Subtarget, DAG))
10175     return Broadcast;
10176
10177   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10178                                                 Subtarget, DAG))
10179     return Blend;
10180
10181   // Use dedicated unpack instructions for masks that match their pattern.
10182   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10183   // 256-bit lanes.
10184   if (isShuffleEquivalent(
10185           V1, V2, Mask,
10186           {// First 128-bit lane:
10187            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10188            // Second 128-bit lane:
10189            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10190     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10191   if (isShuffleEquivalent(
10192           V1, V2, Mask,
10193           {// First 128-bit lane:
10194            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10195            // Second 128-bit lane:
10196            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10197     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10198
10199   // Try to use shift instructions.
10200   if (SDValue Shift =
10201           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10202     return Shift;
10203
10204   // Try to use byte rotation instructions.
10205   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10206           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10207     return Rotate;
10208
10209   if (isSingleInputShuffleMask(Mask)) {
10210     // There are no generalized cross-lane shuffle operations available on i8
10211     // element types.
10212     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10213       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10214                                                      Mask, DAG);
10215
10216     SDValue PSHUFBMask[32];
10217     for (int i = 0; i < 32; ++i)
10218       PSHUFBMask[i] =
10219           Mask[i] < 0
10220               ? DAG.getUNDEF(MVT::i8)
10221               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10222                                 MVT::i8);
10223
10224     return DAG.getNode(
10225         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10226         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10227   }
10228
10229   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10230   // shuffle.
10231   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10232           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10233     return Result;
10234
10235   // Otherwise fall back on generic lowering.
10236   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10237 }
10238
10239 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10240 ///
10241 /// This routine either breaks down the specific type of a 256-bit x86 vector
10242 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10243 /// together based on the available instructions.
10244 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10245                                         MVT VT, const X86Subtarget *Subtarget,
10246                                         SelectionDAG &DAG) {
10247   SDLoc DL(Op);
10248   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10249   ArrayRef<int> Mask = SVOp->getMask();
10250
10251   // If we have a single input to the zero element, insert that into V1 if we
10252   // can do so cheaply.
10253   int NumElts = VT.getVectorNumElements();
10254   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10255     return M >= NumElts;
10256   });
10257
10258   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10259     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10260                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10261       return Insertion;
10262
10263   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10264   // check for those subtargets here and avoid much of the subtarget querying in
10265   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10266   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10267   // floating point types there eventually, just immediately cast everything to
10268   // a float and operate entirely in that domain.
10269   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10270     int ElementBits = VT.getScalarSizeInBits();
10271     if (ElementBits < 32)
10272       // No floating point type available, decompose into 128-bit vectors.
10273       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10274
10275     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10276                                 VT.getVectorNumElements());
10277     V1 = DAG.getBitcast(FpVT, V1);
10278     V2 = DAG.getBitcast(FpVT, V2);
10279     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10280   }
10281
10282   switch (VT.SimpleTy) {
10283   case MVT::v4f64:
10284     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10285   case MVT::v4i64:
10286     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10287   case MVT::v8f32:
10288     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10289   case MVT::v8i32:
10290     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10291   case MVT::v16i16:
10292     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10293   case MVT::v32i8:
10294     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10295
10296   default:
10297     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10298   }
10299 }
10300
10301 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10302 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10303                                        const X86Subtarget *Subtarget,
10304                                        SelectionDAG &DAG) {
10305   SDLoc DL(Op);
10306   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10307   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10308   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10309   ArrayRef<int> Mask = SVOp->getMask();
10310   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10311
10312   // X86 has dedicated unpack instructions that can handle specific blend
10313   // operations: UNPCKH and UNPCKL.
10314   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10315     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10316   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10317     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10318
10319   // FIXME: Implement direct support for this type!
10320   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10321 }
10322
10323 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10324 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10325                                        const X86Subtarget *Subtarget,
10326                                        SelectionDAG &DAG) {
10327   SDLoc DL(Op);
10328   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10329   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10330   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10331   ArrayRef<int> Mask = SVOp->getMask();
10332   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10333
10334   // Use dedicated unpack instructions for masks that match their pattern.
10335   if (isShuffleEquivalent(V1, V2, Mask,
10336                           {// First 128-bit lane.
10337                            0, 16, 1, 17, 4, 20, 5, 21,
10338                            // Second 128-bit lane.
10339                            8, 24, 9, 25, 12, 28, 13, 29}))
10340     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10341   if (isShuffleEquivalent(V1, V2, Mask,
10342                           {// First 128-bit lane.
10343                            2, 18, 3, 19, 6, 22, 7, 23,
10344                            // Second 128-bit lane.
10345                            10, 26, 11, 27, 14, 30, 15, 31}))
10346     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10347
10348   // FIXME: Implement direct support for this type!
10349   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10350 }
10351
10352 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10353 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10354                                        const X86Subtarget *Subtarget,
10355                                        SelectionDAG &DAG) {
10356   SDLoc DL(Op);
10357   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10358   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10359   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10360   ArrayRef<int> Mask = SVOp->getMask();
10361   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10362
10363   // X86 has dedicated unpack instructions that can handle specific blend
10364   // operations: UNPCKH and UNPCKL.
10365   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10366     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10367   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10368     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10369
10370   // FIXME: Implement direct support for this type!
10371   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10372 }
10373
10374 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10375 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10376                                        const X86Subtarget *Subtarget,
10377                                        SelectionDAG &DAG) {
10378   SDLoc DL(Op);
10379   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10380   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10381   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10382   ArrayRef<int> Mask = SVOp->getMask();
10383   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10384
10385   // Use dedicated unpack instructions for masks that match their pattern.
10386   if (isShuffleEquivalent(V1, V2, Mask,
10387                           {// First 128-bit lane.
10388                            0, 16, 1, 17, 4, 20, 5, 21,
10389                            // Second 128-bit lane.
10390                            8, 24, 9, 25, 12, 28, 13, 29}))
10391     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10392   if (isShuffleEquivalent(V1, V2, Mask,
10393                           {// First 128-bit lane.
10394                            2, 18, 3, 19, 6, 22, 7, 23,
10395                            // Second 128-bit lane.
10396                            10, 26, 11, 27, 14, 30, 15, 31}))
10397     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10398
10399   // FIXME: Implement direct support for this type!
10400   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10401 }
10402
10403 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10404 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10405                                         const X86Subtarget *Subtarget,
10406                                         SelectionDAG &DAG) {
10407   SDLoc DL(Op);
10408   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10409   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10410   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10411   ArrayRef<int> Mask = SVOp->getMask();
10412   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10413   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10414
10415   // FIXME: Implement direct support for this type!
10416   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10417 }
10418
10419 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10420 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10421                                        const X86Subtarget *Subtarget,
10422                                        SelectionDAG &DAG) {
10423   SDLoc DL(Op);
10424   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10425   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10426   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10427   ArrayRef<int> Mask = SVOp->getMask();
10428   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10429   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10430
10431   // FIXME: Implement direct support for this type!
10432   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10433 }
10434
10435 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10436 ///
10437 /// This routine either breaks down the specific type of a 512-bit x86 vector
10438 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10439 /// together based on the available instructions.
10440 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10441                                         MVT VT, const X86Subtarget *Subtarget,
10442                                         SelectionDAG &DAG) {
10443   SDLoc DL(Op);
10444   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10445   ArrayRef<int> Mask = SVOp->getMask();
10446   assert(Subtarget->hasAVX512() &&
10447          "Cannot lower 512-bit vectors w/ basic ISA!");
10448
10449   // Check for being able to broadcast a single element.
10450   if (SDValue Broadcast =
10451           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10452     return Broadcast;
10453
10454   // Dispatch to each element type for lowering. If we don't have supprot for
10455   // specific element type shuffles at 512 bits, immediately split them and
10456   // lower them. Each lowering routine of a given type is allowed to assume that
10457   // the requisite ISA extensions for that element type are available.
10458   switch (VT.SimpleTy) {
10459   case MVT::v8f64:
10460     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10461   case MVT::v16f32:
10462     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10463   case MVT::v8i64:
10464     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10465   case MVT::v16i32:
10466     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10467   case MVT::v32i16:
10468     if (Subtarget->hasBWI())
10469       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10470     break;
10471   case MVT::v64i8:
10472     if (Subtarget->hasBWI())
10473       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10474     break;
10475
10476   default:
10477     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10478   }
10479
10480   // Otherwise fall back on splitting.
10481   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10482 }
10483
10484 /// \brief Top-level lowering for x86 vector shuffles.
10485 ///
10486 /// This handles decomposition, canonicalization, and lowering of all x86
10487 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10488 /// above in helper routines. The canonicalization attempts to widen shuffles
10489 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10490 /// s.t. only one of the two inputs needs to be tested, etc.
10491 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10492                                   SelectionDAG &DAG) {
10493   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10494   ArrayRef<int> Mask = SVOp->getMask();
10495   SDValue V1 = Op.getOperand(0);
10496   SDValue V2 = Op.getOperand(1);
10497   MVT VT = Op.getSimpleValueType();
10498   int NumElements = VT.getVectorNumElements();
10499   SDLoc dl(Op);
10500
10501   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10502
10503   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10504   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10505   if (V1IsUndef && V2IsUndef)
10506     return DAG.getUNDEF(VT);
10507
10508   // When we create a shuffle node we put the UNDEF node to second operand,
10509   // but in some cases the first operand may be transformed to UNDEF.
10510   // In this case we should just commute the node.
10511   if (V1IsUndef)
10512     return DAG.getCommutedVectorShuffle(*SVOp);
10513
10514   // Check for non-undef masks pointing at an undef vector and make the masks
10515   // undef as well. This makes it easier to match the shuffle based solely on
10516   // the mask.
10517   if (V2IsUndef)
10518     for (int M : Mask)
10519       if (M >= NumElements) {
10520         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10521         for (int &M : NewMask)
10522           if (M >= NumElements)
10523             M = -1;
10524         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10525       }
10526
10527   // We actually see shuffles that are entirely re-arrangements of a set of
10528   // zero inputs. This mostly happens while decomposing complex shuffles into
10529   // simple ones. Directly lower these as a buildvector of zeros.
10530   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10531   if (Zeroable.all())
10532     return getZeroVector(VT, Subtarget, DAG, dl);
10533
10534   // Try to collapse shuffles into using a vector type with fewer elements but
10535   // wider element types. We cap this to not form integers or floating point
10536   // elements wider than 64 bits, but it might be interesting to form i128
10537   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10538   SmallVector<int, 16> WidenedMask;
10539   if (VT.getScalarSizeInBits() < 64 &&
10540       canWidenShuffleElements(Mask, WidenedMask)) {
10541     MVT NewEltVT = VT.isFloatingPoint()
10542                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10543                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10544     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10545     // Make sure that the new vector type is legal. For example, v2f64 isn't
10546     // legal on SSE1.
10547     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10548       V1 = DAG.getBitcast(NewVT, V1);
10549       V2 = DAG.getBitcast(NewVT, V2);
10550       return DAG.getBitcast(
10551           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10552     }
10553   }
10554
10555   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10556   for (int M : SVOp->getMask())
10557     if (M < 0)
10558       ++NumUndefElements;
10559     else if (M < NumElements)
10560       ++NumV1Elements;
10561     else
10562       ++NumV2Elements;
10563
10564   // Commute the shuffle as needed such that more elements come from V1 than
10565   // V2. This allows us to match the shuffle pattern strictly on how many
10566   // elements come from V1 without handling the symmetric cases.
10567   if (NumV2Elements > NumV1Elements)
10568     return DAG.getCommutedVectorShuffle(*SVOp);
10569
10570   // When the number of V1 and V2 elements are the same, try to minimize the
10571   // number of uses of V2 in the low half of the vector. When that is tied,
10572   // ensure that the sum of indices for V1 is equal to or lower than the sum
10573   // indices for V2. When those are equal, try to ensure that the number of odd
10574   // indices for V1 is lower than the number of odd indices for V2.
10575   if (NumV1Elements == NumV2Elements) {
10576     int LowV1Elements = 0, LowV2Elements = 0;
10577     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10578       if (M >= NumElements)
10579         ++LowV2Elements;
10580       else if (M >= 0)
10581         ++LowV1Elements;
10582     if (LowV2Elements > LowV1Elements) {
10583       return DAG.getCommutedVectorShuffle(*SVOp);
10584     } else if (LowV2Elements == LowV1Elements) {
10585       int SumV1Indices = 0, SumV2Indices = 0;
10586       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10587         if (SVOp->getMask()[i] >= NumElements)
10588           SumV2Indices += i;
10589         else if (SVOp->getMask()[i] >= 0)
10590           SumV1Indices += i;
10591       if (SumV2Indices < SumV1Indices) {
10592         return DAG.getCommutedVectorShuffle(*SVOp);
10593       } else if (SumV2Indices == SumV1Indices) {
10594         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10595         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10596           if (SVOp->getMask()[i] >= NumElements)
10597             NumV2OddIndices += i % 2;
10598           else if (SVOp->getMask()[i] >= 0)
10599             NumV1OddIndices += i % 2;
10600         if (NumV2OddIndices < NumV1OddIndices)
10601           return DAG.getCommutedVectorShuffle(*SVOp);
10602       }
10603     }
10604   }
10605
10606   // For each vector width, delegate to a specialized lowering routine.
10607   if (VT.getSizeInBits() == 128)
10608     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10609
10610   if (VT.getSizeInBits() == 256)
10611     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10612
10613   // Force AVX-512 vectors to be scalarized for now.
10614   // FIXME: Implement AVX-512 support!
10615   if (VT.getSizeInBits() == 512)
10616     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10617
10618   llvm_unreachable("Unimplemented!");
10619 }
10620
10621 // This function assumes its argument is a BUILD_VECTOR of constants or
10622 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10623 // true.
10624 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10625                                     unsigned &MaskValue) {
10626   MaskValue = 0;
10627   unsigned NumElems = BuildVector->getNumOperands();
10628   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10629   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10630   unsigned NumElemsInLane = NumElems / NumLanes;
10631
10632   // Blend for v16i16 should be symetric for the both lanes.
10633   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10634     SDValue EltCond = BuildVector->getOperand(i);
10635     SDValue SndLaneEltCond =
10636         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10637
10638     int Lane1Cond = -1, Lane2Cond = -1;
10639     if (isa<ConstantSDNode>(EltCond))
10640       Lane1Cond = !isZero(EltCond);
10641     if (isa<ConstantSDNode>(SndLaneEltCond))
10642       Lane2Cond = !isZero(SndLaneEltCond);
10643
10644     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10645       // Lane1Cond != 0, means we want the first argument.
10646       // Lane1Cond == 0, means we want the second argument.
10647       // The encoding of this argument is 0 for the first argument, 1
10648       // for the second. Therefore, invert the condition.
10649       MaskValue |= !Lane1Cond << i;
10650     else if (Lane1Cond < 0)
10651       MaskValue |= !Lane2Cond << i;
10652     else
10653       return false;
10654   }
10655   return true;
10656 }
10657
10658 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10659 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10660                                            const X86Subtarget *Subtarget,
10661                                            SelectionDAG &DAG) {
10662   SDValue Cond = Op.getOperand(0);
10663   SDValue LHS = Op.getOperand(1);
10664   SDValue RHS = Op.getOperand(2);
10665   SDLoc dl(Op);
10666   MVT VT = Op.getSimpleValueType();
10667
10668   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10669     return SDValue();
10670   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10671
10672   // Only non-legal VSELECTs reach this lowering, convert those into generic
10673   // shuffles and re-use the shuffle lowering path for blends.
10674   SmallVector<int, 32> Mask;
10675   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10676     SDValue CondElt = CondBV->getOperand(i);
10677     Mask.push_back(
10678         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10679   }
10680   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10681 }
10682
10683 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10684   // A vselect where all conditions and data are constants can be optimized into
10685   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10686   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10687       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10688       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10689     return SDValue();
10690
10691   // Try to lower this to a blend-style vector shuffle. This can handle all
10692   // constant condition cases.
10693   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10694     return BlendOp;
10695
10696   // Variable blends are only legal from SSE4.1 onward.
10697   if (!Subtarget->hasSSE41())
10698     return SDValue();
10699
10700   // Only some types will be legal on some subtargets. If we can emit a legal
10701   // VSELECT-matching blend, return Op, and but if we need to expand, return
10702   // a null value.
10703   switch (Op.getSimpleValueType().SimpleTy) {
10704   default:
10705     // Most of the vector types have blends past SSE4.1.
10706     return Op;
10707
10708   case MVT::v32i8:
10709     // The byte blends for AVX vectors were introduced only in AVX2.
10710     if (Subtarget->hasAVX2())
10711       return Op;
10712
10713     return SDValue();
10714
10715   case MVT::v8i16:
10716   case MVT::v16i16:
10717     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10718     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10719       return Op;
10720
10721     // FIXME: We should custom lower this by fixing the condition and using i8
10722     // blends.
10723     return SDValue();
10724   }
10725 }
10726
10727 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10728   MVT VT = Op.getSimpleValueType();
10729   SDLoc dl(Op);
10730
10731   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10732     return SDValue();
10733
10734   if (VT.getSizeInBits() == 8) {
10735     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10736                                   Op.getOperand(0), Op.getOperand(1));
10737     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10738                                   DAG.getValueType(VT));
10739     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10740   }
10741
10742   if (VT.getSizeInBits() == 16) {
10743     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10744     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10745     if (Idx == 0)
10746       return DAG.getNode(
10747           ISD::TRUNCATE, dl, MVT::i16,
10748           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10749                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10750                       Op.getOperand(1)));
10751     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10752                                   Op.getOperand(0), Op.getOperand(1));
10753     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10754                                   DAG.getValueType(VT));
10755     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10756   }
10757
10758   if (VT == MVT::f32) {
10759     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10760     // the result back to FR32 register. It's only worth matching if the
10761     // result has a single use which is a store or a bitcast to i32.  And in
10762     // the case of a store, it's not worth it if the index is a constant 0,
10763     // because a MOVSSmr can be used instead, which is smaller and faster.
10764     if (!Op.hasOneUse())
10765       return SDValue();
10766     SDNode *User = *Op.getNode()->use_begin();
10767     if ((User->getOpcode() != ISD::STORE ||
10768          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10769           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10770         (User->getOpcode() != ISD::BITCAST ||
10771          User->getValueType(0) != MVT::i32))
10772       return SDValue();
10773     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10774                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10775                                   Op.getOperand(1));
10776     return DAG.getBitcast(MVT::f32, Extract);
10777   }
10778
10779   if (VT == MVT::i32 || VT == MVT::i64) {
10780     // ExtractPS/pextrq works with constant index.
10781     if (isa<ConstantSDNode>(Op.getOperand(1)))
10782       return Op;
10783   }
10784   return SDValue();
10785 }
10786
10787 /// Extract one bit from mask vector, like v16i1 or v8i1.
10788 /// AVX-512 feature.
10789 SDValue
10790 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10791   SDValue Vec = Op.getOperand(0);
10792   SDLoc dl(Vec);
10793   MVT VecVT = Vec.getSimpleValueType();
10794   SDValue Idx = Op.getOperand(1);
10795   MVT EltVT = Op.getSimpleValueType();
10796
10797   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10798   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10799          "Unexpected vector type in ExtractBitFromMaskVector");
10800
10801   // variable index can't be handled in mask registers,
10802   // extend vector to VR512
10803   if (!isa<ConstantSDNode>(Idx)) {
10804     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10805     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10806     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10807                               ExtVT.getVectorElementType(), Ext, Idx);
10808     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10809   }
10810
10811   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10812   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10813   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10814     rc = getRegClassFor(MVT::v16i1);
10815   unsigned MaxSift = rc->getSize()*8 - 1;
10816   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10817                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10818   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10819                     DAG.getConstant(MaxSift, dl, MVT::i8));
10820   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10821                        DAG.getIntPtrConstant(0, dl));
10822 }
10823
10824 SDValue
10825 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10826                                            SelectionDAG &DAG) const {
10827   SDLoc dl(Op);
10828   SDValue Vec = Op.getOperand(0);
10829   MVT VecVT = Vec.getSimpleValueType();
10830   SDValue Idx = Op.getOperand(1);
10831
10832   if (Op.getSimpleValueType() == MVT::i1)
10833     return ExtractBitFromMaskVector(Op, DAG);
10834
10835   if (!isa<ConstantSDNode>(Idx)) {
10836     if (VecVT.is512BitVector() ||
10837         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10838          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10839
10840       MVT MaskEltVT =
10841         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10842       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10843                                     MaskEltVT.getSizeInBits());
10844
10845       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10846       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10847                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10848                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10849       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10850       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10851                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10852     }
10853     return SDValue();
10854   }
10855
10856   // If this is a 256-bit vector result, first extract the 128-bit vector and
10857   // then extract the element from the 128-bit vector.
10858   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10859
10860     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10861     // Get the 128-bit vector.
10862     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10863     MVT EltVT = VecVT.getVectorElementType();
10864
10865     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10866
10867     //if (IdxVal >= NumElems/2)
10868     //  IdxVal -= NumElems/2;
10869     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10870     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10871                        DAG.getConstant(IdxVal, dl, MVT::i32));
10872   }
10873
10874   assert(VecVT.is128BitVector() && "Unexpected vector length");
10875
10876   if (Subtarget->hasSSE41())
10877     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10878       return Res;
10879
10880   MVT VT = Op.getSimpleValueType();
10881   // TODO: handle v16i8.
10882   if (VT.getSizeInBits() == 16) {
10883     SDValue Vec = Op.getOperand(0);
10884     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10885     if (Idx == 0)
10886       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10887                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10888                                      DAG.getBitcast(MVT::v4i32, Vec),
10889                                      Op.getOperand(1)));
10890     // Transform it so it match pextrw which produces a 32-bit result.
10891     MVT EltVT = MVT::i32;
10892     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10893                                   Op.getOperand(0), Op.getOperand(1));
10894     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10895                                   DAG.getValueType(VT));
10896     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10897   }
10898
10899   if (VT.getSizeInBits() == 32) {
10900     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10901     if (Idx == 0)
10902       return Op;
10903
10904     // SHUFPS the element to the lowest double word, then movss.
10905     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10906     MVT VVT = Op.getOperand(0).getSimpleValueType();
10907     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10908                                        DAG.getUNDEF(VVT), Mask);
10909     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10910                        DAG.getIntPtrConstant(0, dl));
10911   }
10912
10913   if (VT.getSizeInBits() == 64) {
10914     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10915     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10916     //        to match extract_elt for f64.
10917     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10918     if (Idx == 0)
10919       return Op;
10920
10921     // UNPCKHPD the element to the lowest double word, then movsd.
10922     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10923     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10924     int Mask[2] = { 1, -1 };
10925     MVT VVT = Op.getOperand(0).getSimpleValueType();
10926     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10927                                        DAG.getUNDEF(VVT), Mask);
10928     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10929                        DAG.getIntPtrConstant(0, dl));
10930   }
10931
10932   return SDValue();
10933 }
10934
10935 /// Insert one bit to mask vector, like v16i1 or v8i1.
10936 /// AVX-512 feature.
10937 SDValue
10938 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10939   SDLoc dl(Op);
10940   SDValue Vec = Op.getOperand(0);
10941   SDValue Elt = Op.getOperand(1);
10942   SDValue Idx = Op.getOperand(2);
10943   MVT VecVT = Vec.getSimpleValueType();
10944
10945   if (!isa<ConstantSDNode>(Idx)) {
10946     // Non constant index. Extend source and destination,
10947     // insert element and then truncate the result.
10948     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10949     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10950     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10951       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10952       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10953     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10954   }
10955
10956   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10957   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10958   if (IdxVal)
10959     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10960                            DAG.getConstant(IdxVal, dl, MVT::i8));
10961   if (Vec.getOpcode() == ISD::UNDEF)
10962     return EltInVec;
10963   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10964 }
10965
10966 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10967                                                   SelectionDAG &DAG) const {
10968   MVT VT = Op.getSimpleValueType();
10969   MVT EltVT = VT.getVectorElementType();
10970
10971   if (EltVT == MVT::i1)
10972     return InsertBitToMaskVector(Op, DAG);
10973
10974   SDLoc dl(Op);
10975   SDValue N0 = Op.getOperand(0);
10976   SDValue N1 = Op.getOperand(1);
10977   SDValue N2 = Op.getOperand(2);
10978   if (!isa<ConstantSDNode>(N2))
10979     return SDValue();
10980   auto *N2C = cast<ConstantSDNode>(N2);
10981   unsigned IdxVal = N2C->getZExtValue();
10982
10983   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10984   // into that, and then insert the subvector back into the result.
10985   if (VT.is256BitVector() || VT.is512BitVector()) {
10986     // With a 256-bit vector, we can insert into the zero element efficiently
10987     // using a blend if we have AVX or AVX2 and the right data type.
10988     if (VT.is256BitVector() && IdxVal == 0) {
10989       // TODO: It is worthwhile to cast integer to floating point and back
10990       // and incur a domain crossing penalty if that's what we'll end up
10991       // doing anyway after extracting to a 128-bit vector.
10992       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10993           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10994         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10995         N2 = DAG.getIntPtrConstant(1, dl);
10996         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10997       }
10998     }
10999
11000     // Get the desired 128-bit vector chunk.
11001     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11002
11003     // Insert the element into the desired chunk.
11004     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11005     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11006
11007     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11008                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11009
11010     // Insert the changed part back into the bigger vector
11011     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11012   }
11013   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11014
11015   if (Subtarget->hasSSE41()) {
11016     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11017       unsigned Opc;
11018       if (VT == MVT::v8i16) {
11019         Opc = X86ISD::PINSRW;
11020       } else {
11021         assert(VT == MVT::v16i8);
11022         Opc = X86ISD::PINSRB;
11023       }
11024
11025       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11026       // argument.
11027       if (N1.getValueType() != MVT::i32)
11028         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11029       if (N2.getValueType() != MVT::i32)
11030         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11031       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11032     }
11033
11034     if (EltVT == MVT::f32) {
11035       // Bits [7:6] of the constant are the source select. This will always be
11036       //   zero here. The DAG Combiner may combine an extract_elt index into
11037       //   these bits. For example (insert (extract, 3), 2) could be matched by
11038       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11039       // Bits [5:4] of the constant are the destination select. This is the
11040       //   value of the incoming immediate.
11041       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11042       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11043
11044       const Function *F = DAG.getMachineFunction().getFunction();
11045       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11046       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11047         // If this is an insertion of 32-bits into the low 32-bits of
11048         // a vector, we prefer to generate a blend with immediate rather
11049         // than an insertps. Blends are simpler operations in hardware and so
11050         // will always have equal or better performance than insertps.
11051         // But if optimizing for size and there's a load folding opportunity,
11052         // generate insertps because blendps does not have a 32-bit memory
11053         // operand form.
11054         N2 = DAG.getIntPtrConstant(1, dl);
11055         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11056         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11057       }
11058       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11059       // Create this as a scalar to vector..
11060       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11061       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11062     }
11063
11064     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11065       // PINSR* works with constant index.
11066       return Op;
11067     }
11068   }
11069
11070   if (EltVT == MVT::i8)
11071     return SDValue();
11072
11073   if (EltVT.getSizeInBits() == 16) {
11074     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11075     // as its second argument.
11076     if (N1.getValueType() != MVT::i32)
11077       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11078     if (N2.getValueType() != MVT::i32)
11079       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11080     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11081   }
11082   return SDValue();
11083 }
11084
11085 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11086   SDLoc dl(Op);
11087   MVT OpVT = Op.getSimpleValueType();
11088
11089   // If this is a 256-bit vector result, first insert into a 128-bit
11090   // vector and then insert into the 256-bit vector.
11091   if (!OpVT.is128BitVector()) {
11092     // Insert into a 128-bit vector.
11093     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11094     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11095                                  OpVT.getVectorNumElements() / SizeFactor);
11096
11097     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11098
11099     // Insert the 128-bit vector.
11100     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11101   }
11102
11103   if (OpVT == MVT::v1i64 &&
11104       Op.getOperand(0).getValueType() == MVT::i64)
11105     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11106
11107   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11108   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11109   return DAG.getBitcast(
11110       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11111 }
11112
11113 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11114 // a simple subregister reference or explicit instructions to grab
11115 // upper bits of a vector.
11116 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11117                                       SelectionDAG &DAG) {
11118   SDLoc dl(Op);
11119   SDValue In =  Op.getOperand(0);
11120   SDValue Idx = Op.getOperand(1);
11121   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11122   MVT ResVT   = Op.getSimpleValueType();
11123   MVT InVT    = In.getSimpleValueType();
11124
11125   if (Subtarget->hasFp256()) {
11126     if (ResVT.is128BitVector() &&
11127         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11128         isa<ConstantSDNode>(Idx)) {
11129       return Extract128BitVector(In, IdxVal, DAG, dl);
11130     }
11131     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11132         isa<ConstantSDNode>(Idx)) {
11133       return Extract256BitVector(In, IdxVal, DAG, dl);
11134     }
11135   }
11136   return SDValue();
11137 }
11138
11139 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11140 // simple superregister reference or explicit instructions to insert
11141 // the upper bits of a vector.
11142 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11143                                      SelectionDAG &DAG) {
11144   if (!Subtarget->hasAVX())
11145     return SDValue();
11146
11147   SDLoc dl(Op);
11148   SDValue Vec = Op.getOperand(0);
11149   SDValue SubVec = Op.getOperand(1);
11150   SDValue Idx = Op.getOperand(2);
11151
11152   if (!isa<ConstantSDNode>(Idx))
11153     return SDValue();
11154
11155   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11156   MVT OpVT = Op.getSimpleValueType();
11157   MVT SubVecVT = SubVec.getSimpleValueType();
11158
11159   // Fold two 16-byte subvector loads into one 32-byte load:
11160   // (insert_subvector (insert_subvector undef, (load addr), 0),
11161   //                   (load addr + 16), Elts/2)
11162   // --> load32 addr
11163   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11164       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11165       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11166       !Subtarget->isUnalignedMem32Slow()) {
11167     SDValue SubVec2 = Vec.getOperand(1);
11168     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11169       if (Idx2->getZExtValue() == 0) {
11170         SDValue Ops[] = { SubVec2, SubVec };
11171         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11172           return Ld;
11173       }
11174     }
11175   }
11176
11177   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11178       SubVecVT.is128BitVector())
11179     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11180
11181   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11182     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11183
11184   if (OpVT.getVectorElementType() == MVT::i1) {
11185     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11186       return Op;
11187     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11188     SDValue Undef = DAG.getUNDEF(OpVT);
11189     unsigned NumElems = OpVT.getVectorNumElements();
11190     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11191
11192     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11193       // Zero upper bits of the Vec
11194       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11195       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11196
11197       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11198                                  SubVec, ZeroIdx);
11199       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11200       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11201     }
11202     if (IdxVal == 0) {
11203       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11204                                  SubVec, ZeroIdx);
11205       // Zero upper bits of the Vec2
11206       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11207       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11208       // Zero lower bits of the Vec
11209       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11210       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11211       // Merge them together
11212       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11213     }
11214   }
11215   return SDValue();
11216 }
11217
11218 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11219 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11220 // one of the above mentioned nodes. It has to be wrapped because otherwise
11221 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11222 // be used to form addressing mode. These wrapped nodes will be selected
11223 // into MOV32ri.
11224 SDValue
11225 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11226   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11227
11228   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11229   // global base reg.
11230   unsigned char OpFlag = 0;
11231   unsigned WrapperKind = X86ISD::Wrapper;
11232   CodeModel::Model M = DAG.getTarget().getCodeModel();
11233
11234   if (Subtarget->isPICStyleRIPRel() &&
11235       (M == CodeModel::Small || M == CodeModel::Kernel))
11236     WrapperKind = X86ISD::WrapperRIP;
11237   else if (Subtarget->isPICStyleGOT())
11238     OpFlag = X86II::MO_GOTOFF;
11239   else if (Subtarget->isPICStyleStubPIC())
11240     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11241
11242   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11243                                              CP->getAlignment(),
11244                                              CP->getOffset(), OpFlag);
11245   SDLoc DL(CP);
11246   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11247   // With PIC, the address is actually $g + Offset.
11248   if (OpFlag) {
11249     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11250                          DAG.getNode(X86ISD::GlobalBaseReg,
11251                                      SDLoc(), getPointerTy()),
11252                          Result);
11253   }
11254
11255   return Result;
11256 }
11257
11258 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11259   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11260
11261   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11262   // global base reg.
11263   unsigned char OpFlag = 0;
11264   unsigned WrapperKind = X86ISD::Wrapper;
11265   CodeModel::Model M = DAG.getTarget().getCodeModel();
11266
11267   if (Subtarget->isPICStyleRIPRel() &&
11268       (M == CodeModel::Small || M == CodeModel::Kernel))
11269     WrapperKind = X86ISD::WrapperRIP;
11270   else if (Subtarget->isPICStyleGOT())
11271     OpFlag = X86II::MO_GOTOFF;
11272   else if (Subtarget->isPICStyleStubPIC())
11273     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11274
11275   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11276                                           OpFlag);
11277   SDLoc DL(JT);
11278   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11279
11280   // With PIC, the address is actually $g + Offset.
11281   if (OpFlag)
11282     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11283                          DAG.getNode(X86ISD::GlobalBaseReg,
11284                                      SDLoc(), getPointerTy()),
11285                          Result);
11286
11287   return Result;
11288 }
11289
11290 SDValue
11291 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11292   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11293
11294   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11295   // global base reg.
11296   unsigned char OpFlag = 0;
11297   unsigned WrapperKind = X86ISD::Wrapper;
11298   CodeModel::Model M = DAG.getTarget().getCodeModel();
11299
11300   if (Subtarget->isPICStyleRIPRel() &&
11301       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11302     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11303       OpFlag = X86II::MO_GOTPCREL;
11304     WrapperKind = X86ISD::WrapperRIP;
11305   } else if (Subtarget->isPICStyleGOT()) {
11306     OpFlag = X86II::MO_GOT;
11307   } else if (Subtarget->isPICStyleStubPIC()) {
11308     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11309   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11310     OpFlag = X86II::MO_DARWIN_NONLAZY;
11311   }
11312
11313   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11314
11315   SDLoc DL(Op);
11316   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11317
11318   // With PIC, the address is actually $g + Offset.
11319   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11320       !Subtarget->is64Bit()) {
11321     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11322                          DAG.getNode(X86ISD::GlobalBaseReg,
11323                                      SDLoc(), getPointerTy()),
11324                          Result);
11325   }
11326
11327   // For symbols that require a load from a stub to get the address, emit the
11328   // load.
11329   if (isGlobalStubReference(OpFlag))
11330     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11331                          MachinePointerInfo::getGOT(), false, false, false, 0);
11332
11333   return Result;
11334 }
11335
11336 SDValue
11337 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11338   // Create the TargetBlockAddressAddress node.
11339   unsigned char OpFlags =
11340     Subtarget->ClassifyBlockAddressReference();
11341   CodeModel::Model M = DAG.getTarget().getCodeModel();
11342   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11343   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11344   SDLoc dl(Op);
11345   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11346                                              OpFlags);
11347
11348   if (Subtarget->isPICStyleRIPRel() &&
11349       (M == CodeModel::Small || M == CodeModel::Kernel))
11350     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11351   else
11352     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11353
11354   // With PIC, the address is actually $g + Offset.
11355   if (isGlobalRelativeToPICBase(OpFlags)) {
11356     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11357                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11358                          Result);
11359   }
11360
11361   return Result;
11362 }
11363
11364 SDValue
11365 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11366                                       int64_t Offset, SelectionDAG &DAG) const {
11367   // Create the TargetGlobalAddress node, folding in the constant
11368   // offset if it is legal.
11369   unsigned char OpFlags =
11370       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11371   CodeModel::Model M = DAG.getTarget().getCodeModel();
11372   SDValue Result;
11373   if (OpFlags == X86II::MO_NO_FLAG &&
11374       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11375     // A direct static reference to a global.
11376     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11377     Offset = 0;
11378   } else {
11379     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11380   }
11381
11382   if (Subtarget->isPICStyleRIPRel() &&
11383       (M == CodeModel::Small || M == CodeModel::Kernel))
11384     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11385   else
11386     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11387
11388   // With PIC, the address is actually $g + Offset.
11389   if (isGlobalRelativeToPICBase(OpFlags)) {
11390     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11391                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11392                          Result);
11393   }
11394
11395   // For globals that require a load from a stub to get the address, emit the
11396   // load.
11397   if (isGlobalStubReference(OpFlags))
11398     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11399                          MachinePointerInfo::getGOT(), false, false, false, 0);
11400
11401   // If there was a non-zero offset that we didn't fold, create an explicit
11402   // addition for it.
11403   if (Offset != 0)
11404     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11405                          DAG.getConstant(Offset, dl, getPointerTy()));
11406
11407   return Result;
11408 }
11409
11410 SDValue
11411 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11412   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11413   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11414   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11415 }
11416
11417 static SDValue
11418 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11419            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11420            unsigned char OperandFlags, bool LocalDynamic = false) {
11421   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11422   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11423   SDLoc dl(GA);
11424   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11425                                            GA->getValueType(0),
11426                                            GA->getOffset(),
11427                                            OperandFlags);
11428
11429   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11430                                            : X86ISD::TLSADDR;
11431
11432   if (InFlag) {
11433     SDValue Ops[] = { Chain,  TGA, *InFlag };
11434     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11435   } else {
11436     SDValue Ops[]  = { Chain, TGA };
11437     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11438   }
11439
11440   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11441   MFI->setAdjustsStack(true);
11442   MFI->setHasCalls(true);
11443
11444   SDValue Flag = Chain.getValue(1);
11445   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11446 }
11447
11448 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11449 static SDValue
11450 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11451                                 const EVT PtrVT) {
11452   SDValue InFlag;
11453   SDLoc dl(GA);  // ? function entry point might be better
11454   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11455                                    DAG.getNode(X86ISD::GlobalBaseReg,
11456                                                SDLoc(), PtrVT), InFlag);
11457   InFlag = Chain.getValue(1);
11458
11459   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11460 }
11461
11462 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11463 static SDValue
11464 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11465                                 const EVT PtrVT) {
11466   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11467                     X86::RAX, X86II::MO_TLSGD);
11468 }
11469
11470 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11471                                            SelectionDAG &DAG,
11472                                            const EVT PtrVT,
11473                                            bool is64Bit) {
11474   SDLoc dl(GA);
11475
11476   // Get the start address of the TLS block for this module.
11477   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11478       .getInfo<X86MachineFunctionInfo>();
11479   MFI->incNumLocalDynamicTLSAccesses();
11480
11481   SDValue Base;
11482   if (is64Bit) {
11483     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11484                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11485   } else {
11486     SDValue InFlag;
11487     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11488         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11489     InFlag = Chain.getValue(1);
11490     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11491                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11492   }
11493
11494   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11495   // of Base.
11496
11497   // Build x@dtpoff.
11498   unsigned char OperandFlags = X86II::MO_DTPOFF;
11499   unsigned WrapperKind = X86ISD::Wrapper;
11500   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11501                                            GA->getValueType(0),
11502                                            GA->getOffset(), OperandFlags);
11503   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11504
11505   // Add x@dtpoff with the base.
11506   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11507 }
11508
11509 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11510 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11511                                    const EVT PtrVT, TLSModel::Model model,
11512                                    bool is64Bit, bool isPIC) {
11513   SDLoc dl(GA);
11514
11515   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11516   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11517                                                          is64Bit ? 257 : 256));
11518
11519   SDValue ThreadPointer =
11520       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11521                   MachinePointerInfo(Ptr), false, false, false, 0);
11522
11523   unsigned char OperandFlags = 0;
11524   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11525   // initialexec.
11526   unsigned WrapperKind = X86ISD::Wrapper;
11527   if (model == TLSModel::LocalExec) {
11528     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11529   } else if (model == TLSModel::InitialExec) {
11530     if (is64Bit) {
11531       OperandFlags = X86II::MO_GOTTPOFF;
11532       WrapperKind = X86ISD::WrapperRIP;
11533     } else {
11534       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11535     }
11536   } else {
11537     llvm_unreachable("Unexpected model");
11538   }
11539
11540   // emit "addl x@ntpoff,%eax" (local exec)
11541   // or "addl x@indntpoff,%eax" (initial exec)
11542   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11543   SDValue TGA =
11544       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11545                                  GA->getOffset(), OperandFlags);
11546   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11547
11548   if (model == TLSModel::InitialExec) {
11549     if (isPIC && !is64Bit) {
11550       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11551                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11552                            Offset);
11553     }
11554
11555     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11556                          MachinePointerInfo::getGOT(), false, false, false, 0);
11557   }
11558
11559   // The address of the thread local variable is the add of the thread
11560   // pointer with the offset of the variable.
11561   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11562 }
11563
11564 SDValue
11565 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11566
11567   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11568   const GlobalValue *GV = GA->getGlobal();
11569
11570   if (Subtarget->isTargetELF()) {
11571     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11572     switch (model) {
11573       case TLSModel::GeneralDynamic:
11574         if (Subtarget->is64Bit())
11575           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11576         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11577       case TLSModel::LocalDynamic:
11578         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11579                                            Subtarget->is64Bit());
11580       case TLSModel::InitialExec:
11581       case TLSModel::LocalExec:
11582         return LowerToTLSExecModel(
11583             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11584             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11585     }
11586     llvm_unreachable("Unknown TLS model.");
11587   }
11588
11589   if (Subtarget->isTargetDarwin()) {
11590     // Darwin only has one model of TLS.  Lower to that.
11591     unsigned char OpFlag = 0;
11592     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11593                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11594
11595     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11596     // global base reg.
11597     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11598                  !Subtarget->is64Bit();
11599     if (PIC32)
11600       OpFlag = X86II::MO_TLVP_PIC_BASE;
11601     else
11602       OpFlag = X86II::MO_TLVP;
11603     SDLoc DL(Op);
11604     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11605                                                 GA->getValueType(0),
11606                                                 GA->getOffset(), OpFlag);
11607     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11608
11609     // With PIC32, the address is actually $g + Offset.
11610     if (PIC32)
11611       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11612                            DAG.getNode(X86ISD::GlobalBaseReg,
11613                                        SDLoc(), getPointerTy()),
11614                            Offset);
11615
11616     // Lowering the machine isd will make sure everything is in the right
11617     // location.
11618     SDValue Chain = DAG.getEntryNode();
11619     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11620     SDValue Args[] = { Chain, Offset };
11621     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11622
11623     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11624     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11625     MFI->setAdjustsStack(true);
11626
11627     // And our return value (tls address) is in the standard call return value
11628     // location.
11629     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11630     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11631                               Chain.getValue(1));
11632   }
11633
11634   if (Subtarget->isTargetKnownWindowsMSVC() ||
11635       Subtarget->isTargetWindowsGNU()) {
11636     // Just use the implicit TLS architecture
11637     // Need to generate someting similar to:
11638     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11639     //                                  ; from TEB
11640     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11641     //   mov     rcx, qword [rdx+rcx*8]
11642     //   mov     eax, .tls$:tlsvar
11643     //   [rax+rcx] contains the address
11644     // Windows 64bit: gs:0x58
11645     // Windows 32bit: fs:__tls_array
11646
11647     SDLoc dl(GA);
11648     SDValue Chain = DAG.getEntryNode();
11649
11650     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11651     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11652     // use its literal value of 0x2C.
11653     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11654                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11655                                                              256)
11656                                         : Type::getInt32PtrTy(*DAG.getContext(),
11657                                                               257));
11658
11659     SDValue TlsArray =
11660         Subtarget->is64Bit()
11661             ? DAG.getIntPtrConstant(0x58, dl)
11662             : (Subtarget->isTargetWindowsGNU()
11663                    ? DAG.getIntPtrConstant(0x2C, dl)
11664                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11665
11666     SDValue ThreadPointer =
11667         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11668                     MachinePointerInfo(Ptr), false, false, false, 0);
11669
11670     SDValue res;
11671     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11672       res = ThreadPointer;
11673     } else {
11674       // Load the _tls_index variable
11675       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11676       if (Subtarget->is64Bit())
11677         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11678                              MachinePointerInfo(), MVT::i32, false, false,
11679                              false, 0);
11680       else
11681         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11682                           false, false, false, 0);
11683
11684       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11685                                       getPointerTy());
11686       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11687
11688       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11689     }
11690
11691     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11692                       false, false, false, 0);
11693
11694     // Get the offset of start of .tls section
11695     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11696                                              GA->getValueType(0),
11697                                              GA->getOffset(), X86II::MO_SECREL);
11698     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11699
11700     // The address of the thread local variable is the add of the thread
11701     // pointer with the offset of the variable.
11702     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11703   }
11704
11705   llvm_unreachable("TLS not implemented for this target.");
11706 }
11707
11708 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11709 /// and take a 2 x i32 value to shift plus a shift amount.
11710 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11711   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11712   MVT VT = Op.getSimpleValueType();
11713   unsigned VTBits = VT.getSizeInBits();
11714   SDLoc dl(Op);
11715   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11716   SDValue ShOpLo = Op.getOperand(0);
11717   SDValue ShOpHi = Op.getOperand(1);
11718   SDValue ShAmt  = Op.getOperand(2);
11719   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11720   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11721   // during isel.
11722   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11723                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11724   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11725                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11726                        : DAG.getConstant(0, dl, VT);
11727
11728   SDValue Tmp2, Tmp3;
11729   if (Op.getOpcode() == ISD::SHL_PARTS) {
11730     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11731     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11732   } else {
11733     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11734     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11735   }
11736
11737   // If the shift amount is larger or equal than the width of a part we can't
11738   // rely on the results of shld/shrd. Insert a test and select the appropriate
11739   // values for large shift amounts.
11740   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11741                                 DAG.getConstant(VTBits, dl, MVT::i8));
11742   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11743                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11744
11745   SDValue Hi, Lo;
11746   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11747   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11748   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11749
11750   if (Op.getOpcode() == ISD::SHL_PARTS) {
11751     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11752     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11753   } else {
11754     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11755     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11756   }
11757
11758   SDValue Ops[2] = { Lo, Hi };
11759   return DAG.getMergeValues(Ops, dl);
11760 }
11761
11762 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11763                                            SelectionDAG &DAG) const {
11764   SDValue Src = Op.getOperand(0);
11765   MVT SrcVT = Src.getSimpleValueType();
11766   MVT VT = Op.getSimpleValueType();
11767   SDLoc dl(Op);
11768
11769   if (SrcVT.isVector()) {
11770     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11771       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11772                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11773                          DAG.getUNDEF(SrcVT)));
11774     }
11775     if (SrcVT.getVectorElementType() == MVT::i1) {
11776       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11777       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11778                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11779     }
11780     return SDValue();
11781   }
11782
11783   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11784          "Unknown SINT_TO_FP to lower!");
11785
11786   // These are really Legal; return the operand so the caller accepts it as
11787   // Legal.
11788   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11789     return Op;
11790   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11791       Subtarget->is64Bit()) {
11792     return Op;
11793   }
11794
11795   unsigned Size = SrcVT.getSizeInBits()/8;
11796   MachineFunction &MF = DAG.getMachineFunction();
11797   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11798   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11799   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11800                                StackSlot,
11801                                MachinePointerInfo::getFixedStack(SSFI),
11802                                false, false, 0);
11803   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11804 }
11805
11806 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11807                                      SDValue StackSlot,
11808                                      SelectionDAG &DAG) const {
11809   // Build the FILD
11810   SDLoc DL(Op);
11811   SDVTList Tys;
11812   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11813   if (useSSE)
11814     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11815   else
11816     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11817
11818   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11819
11820   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11821   MachineMemOperand *MMO;
11822   if (FI) {
11823     int SSFI = FI->getIndex();
11824     MMO =
11825       DAG.getMachineFunction()
11826       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11827                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11828   } else {
11829     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11830     StackSlot = StackSlot.getOperand(1);
11831   }
11832   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11833   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11834                                            X86ISD::FILD, DL,
11835                                            Tys, Ops, SrcVT, MMO);
11836
11837   if (useSSE) {
11838     Chain = Result.getValue(1);
11839     SDValue InFlag = Result.getValue(2);
11840
11841     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11842     // shouldn't be necessary except that RFP cannot be live across
11843     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11844     MachineFunction &MF = DAG.getMachineFunction();
11845     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11846     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11847     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11848     Tys = DAG.getVTList(MVT::Other);
11849     SDValue Ops[] = {
11850       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11851     };
11852     MachineMemOperand *MMO =
11853       DAG.getMachineFunction()
11854       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11855                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11856
11857     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11858                                     Ops, Op.getValueType(), MMO);
11859     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11860                          MachinePointerInfo::getFixedStack(SSFI),
11861                          false, false, false, 0);
11862   }
11863
11864   return Result;
11865 }
11866
11867 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11868 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11869                                                SelectionDAG &DAG) const {
11870   // This algorithm is not obvious. Here it is what we're trying to output:
11871   /*
11872      movq       %rax,  %xmm0
11873      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11874      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11875      #ifdef __SSE3__
11876        haddpd   %xmm0, %xmm0
11877      #else
11878        pshufd   $0x4e, %xmm0, %xmm1
11879        addpd    %xmm1, %xmm0
11880      #endif
11881   */
11882
11883   SDLoc dl(Op);
11884   LLVMContext *Context = DAG.getContext();
11885
11886   // Build some magic constants.
11887   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11888   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11889   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11890
11891   SmallVector<Constant*,2> CV1;
11892   CV1.push_back(
11893     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11894                                       APInt(64, 0x4330000000000000ULL))));
11895   CV1.push_back(
11896     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11897                                       APInt(64, 0x4530000000000000ULL))));
11898   Constant *C1 = ConstantVector::get(CV1);
11899   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11900
11901   // Load the 64-bit value into an XMM register.
11902   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11903                             Op.getOperand(0));
11904   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11905                               MachinePointerInfo::getConstantPool(),
11906                               false, false, false, 16);
11907   SDValue Unpck1 =
11908       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11909
11910   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11911                               MachinePointerInfo::getConstantPool(),
11912                               false, false, false, 16);
11913   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11914   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11915   SDValue Result;
11916
11917   if (Subtarget->hasSSE3()) {
11918     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11919     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11920   } else {
11921     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11922     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11923                                            S2F, 0x4E, DAG);
11924     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11925                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11926   }
11927
11928   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11929                      DAG.getIntPtrConstant(0, dl));
11930 }
11931
11932 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11933 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11934                                                SelectionDAG &DAG) const {
11935   SDLoc dl(Op);
11936   // FP constant to bias correct the final result.
11937   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11938                                    MVT::f64);
11939
11940   // Load the 32-bit value into an XMM register.
11941   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11942                              Op.getOperand(0));
11943
11944   // Zero out the upper parts of the register.
11945   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11946
11947   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11948                      DAG.getBitcast(MVT::v2f64, Load),
11949                      DAG.getIntPtrConstant(0, dl));
11950
11951   // Or the load with the bias.
11952   SDValue Or = DAG.getNode(
11953       ISD::OR, dl, MVT::v2i64,
11954       DAG.getBitcast(MVT::v2i64,
11955                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11956       DAG.getBitcast(MVT::v2i64,
11957                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11958   Or =
11959       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11960                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11961
11962   // Subtract the bias.
11963   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11964
11965   // Handle final rounding.
11966   EVT DestVT = Op.getValueType();
11967
11968   if (DestVT.bitsLT(MVT::f64))
11969     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11970                        DAG.getIntPtrConstant(0, dl));
11971   if (DestVT.bitsGT(MVT::f64))
11972     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11973
11974   // Handle final rounding.
11975   return Sub;
11976 }
11977
11978 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11979                                      const X86Subtarget &Subtarget) {
11980   // The algorithm is the following:
11981   // #ifdef __SSE4_1__
11982   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11983   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11984   //                                 (uint4) 0x53000000, 0xaa);
11985   // #else
11986   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11987   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11988   // #endif
11989   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11990   //     return (float4) lo + fhi;
11991
11992   SDLoc DL(Op);
11993   SDValue V = Op->getOperand(0);
11994   EVT VecIntVT = V.getValueType();
11995   bool Is128 = VecIntVT == MVT::v4i32;
11996   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11997   // If we convert to something else than the supported type, e.g., to v4f64,
11998   // abort early.
11999   if (VecFloatVT != Op->getValueType(0))
12000     return SDValue();
12001
12002   unsigned NumElts = VecIntVT.getVectorNumElements();
12003   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12004          "Unsupported custom type");
12005   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12006
12007   // In the #idef/#else code, we have in common:
12008   // - The vector of constants:
12009   // -- 0x4b000000
12010   // -- 0x53000000
12011   // - A shift:
12012   // -- v >> 16
12013
12014   // Create the splat vector for 0x4b000000.
12015   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12016   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12017                            CstLow, CstLow, CstLow, CstLow};
12018   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12019                                   makeArrayRef(&CstLowArray[0], NumElts));
12020   // Create the splat vector for 0x53000000.
12021   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12022   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12023                             CstHigh, CstHigh, CstHigh, CstHigh};
12024   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12025                                    makeArrayRef(&CstHighArray[0], NumElts));
12026
12027   // Create the right shift.
12028   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12029   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12030                              CstShift, CstShift, CstShift, CstShift};
12031   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12032                                     makeArrayRef(&CstShiftArray[0], NumElts));
12033   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12034
12035   SDValue Low, High;
12036   if (Subtarget.hasSSE41()) {
12037     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12038     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12039     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12040     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12041     // Low will be bitcasted right away, so do not bother bitcasting back to its
12042     // original type.
12043     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12044                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12045     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12046     //                                 (uint4) 0x53000000, 0xaa);
12047     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12048     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12049     // High will be bitcasted right away, so do not bother bitcasting back to
12050     // its original type.
12051     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12052                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12053   } else {
12054     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12055     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12056                                      CstMask, CstMask, CstMask);
12057     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12058     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12059     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12060
12061     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12062     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12063   }
12064
12065   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12066   SDValue CstFAdd = DAG.getConstantFP(
12067       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12068   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12069                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12070   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12071                                    makeArrayRef(&CstFAddArray[0], NumElts));
12072
12073   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12074   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12075   SDValue FHigh =
12076       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12077   //     return (float4) lo + fhi;
12078   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12079   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12080 }
12081
12082 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12083                                                SelectionDAG &DAG) const {
12084   SDValue N0 = Op.getOperand(0);
12085   MVT SVT = N0.getSimpleValueType();
12086   SDLoc dl(Op);
12087
12088   switch (SVT.SimpleTy) {
12089   default:
12090     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12091   case MVT::v4i8:
12092   case MVT::v4i16:
12093   case MVT::v8i8:
12094   case MVT::v8i16: {
12095     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12096     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12097                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12098   }
12099   case MVT::v4i32:
12100   case MVT::v8i32:
12101     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12102   case MVT::v16i8:
12103   case MVT::v16i16:
12104     if (Subtarget->hasAVX512())
12105       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12106                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12107   }
12108   llvm_unreachable(nullptr);
12109 }
12110
12111 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12112                                            SelectionDAG &DAG) const {
12113   SDValue N0 = Op.getOperand(0);
12114   SDLoc dl(Op);
12115
12116   if (Op.getValueType().isVector())
12117     return lowerUINT_TO_FP_vec(Op, DAG);
12118
12119   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12120   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12121   // the optimization here.
12122   if (DAG.SignBitIsZero(N0))
12123     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12124
12125   MVT SrcVT = N0.getSimpleValueType();
12126   MVT DstVT = Op.getSimpleValueType();
12127   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12128     return LowerUINT_TO_FP_i64(Op, DAG);
12129   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12130     return LowerUINT_TO_FP_i32(Op, DAG);
12131   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12132     return SDValue();
12133
12134   // Make a 64-bit buffer, and use it to build an FILD.
12135   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12136   if (SrcVT == MVT::i32) {
12137     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
12138     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
12139                                      getPointerTy(), StackSlot, WordOff);
12140     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12141                                   StackSlot, MachinePointerInfo(),
12142                                   false, false, 0);
12143     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12144                                   OffsetSlot, MachinePointerInfo(),
12145                                   false, false, 0);
12146     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12147     return Fild;
12148   }
12149
12150   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12151   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12152                                StackSlot, MachinePointerInfo(),
12153                                false, false, 0);
12154   // For i64 source, we need to add the appropriate power of 2 if the input
12155   // was negative.  This is the same as the optimization in
12156   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12157   // we must be careful to do the computation in x87 extended precision, not
12158   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12159   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12160   MachineMemOperand *MMO =
12161     DAG.getMachineFunction()
12162     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12163                           MachineMemOperand::MOLoad, 8, 8);
12164
12165   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12166   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12167   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12168                                          MVT::i64, MMO);
12169
12170   APInt FF(32, 0x5F800000ULL);
12171
12172   // Check whether the sign bit is set.
12173   SDValue SignSet = DAG.getSetCC(dl,
12174                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
12175                                  Op.getOperand(0),
12176                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12177
12178   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12179   SDValue FudgePtr = DAG.getConstantPool(
12180                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12181                                          getPointerTy());
12182
12183   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12184   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12185   SDValue Four = DAG.getIntPtrConstant(4, dl);
12186   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12187                                Zero, Four);
12188   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12189
12190   // Load the value out, extending it from f32 to f80.
12191   // FIXME: Avoid the extend by constructing the right constant pool?
12192   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12193                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12194                                  MVT::f32, false, false, false, 4);
12195   // Extend everything to 80 bits to force it to be done on x87.
12196   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12197   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12198                      DAG.getIntPtrConstant(0, dl));
12199 }
12200
12201 std::pair<SDValue,SDValue>
12202 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12203                                     bool IsSigned, bool IsReplace) const {
12204   SDLoc DL(Op);
12205
12206   EVT DstTy = Op.getValueType();
12207
12208   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12209     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12210     DstTy = MVT::i64;
12211   }
12212
12213   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12214          DstTy.getSimpleVT() >= MVT::i16 &&
12215          "Unknown FP_TO_INT to lower!");
12216
12217   // These are really Legal.
12218   if (DstTy == MVT::i32 &&
12219       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12220     return std::make_pair(SDValue(), SDValue());
12221   if (Subtarget->is64Bit() &&
12222       DstTy == MVT::i64 &&
12223       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12224     return std::make_pair(SDValue(), SDValue());
12225
12226   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12227   // stack slot, or into the FTOL runtime function.
12228   MachineFunction &MF = DAG.getMachineFunction();
12229   unsigned MemSize = DstTy.getSizeInBits()/8;
12230   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12231   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12232
12233   unsigned Opc;
12234   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12235     Opc = X86ISD::WIN_FTOL;
12236   else
12237     switch (DstTy.getSimpleVT().SimpleTy) {
12238     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12239     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12240     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12241     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12242     }
12243
12244   SDValue Chain = DAG.getEntryNode();
12245   SDValue Value = Op.getOperand(0);
12246   EVT TheVT = Op.getOperand(0).getValueType();
12247   // FIXME This causes a redundant load/store if the SSE-class value is already
12248   // in memory, such as if it is on the callstack.
12249   if (isScalarFPTypeInSSEReg(TheVT)) {
12250     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12251     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12252                          MachinePointerInfo::getFixedStack(SSFI),
12253                          false, false, 0);
12254     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12255     SDValue Ops[] = {
12256       Chain, StackSlot, DAG.getValueType(TheVT)
12257     };
12258
12259     MachineMemOperand *MMO =
12260       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12261                               MachineMemOperand::MOLoad, MemSize, MemSize);
12262     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12263     Chain = Value.getValue(1);
12264     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12265     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12266   }
12267
12268   MachineMemOperand *MMO =
12269     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12270                             MachineMemOperand::MOStore, MemSize, MemSize);
12271
12272   if (Opc != X86ISD::WIN_FTOL) {
12273     // Build the FP_TO_INT*_IN_MEM
12274     SDValue Ops[] = { Chain, Value, StackSlot };
12275     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12276                                            Ops, DstTy, MMO);
12277     return std::make_pair(FIST, StackSlot);
12278   } else {
12279     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12280       DAG.getVTList(MVT::Other, MVT::Glue),
12281       Chain, Value);
12282     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12283       MVT::i32, ftol.getValue(1));
12284     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12285       MVT::i32, eax.getValue(2));
12286     SDValue Ops[] = { eax, edx };
12287     SDValue pair = IsReplace
12288       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12289       : DAG.getMergeValues(Ops, DL);
12290     return std::make_pair(pair, SDValue());
12291   }
12292 }
12293
12294 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12295                               const X86Subtarget *Subtarget) {
12296   MVT VT = Op->getSimpleValueType(0);
12297   SDValue In = Op->getOperand(0);
12298   MVT InVT = In.getSimpleValueType();
12299   SDLoc dl(Op);
12300
12301   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12302     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12303
12304   // Optimize vectors in AVX mode:
12305   //
12306   //   v8i16 -> v8i32
12307   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12308   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12309   //   Concat upper and lower parts.
12310   //
12311   //   v4i32 -> v4i64
12312   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12313   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12314   //   Concat upper and lower parts.
12315   //
12316
12317   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12318       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12319       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12320     return SDValue();
12321
12322   if (Subtarget->hasInt256())
12323     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12324
12325   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12326   SDValue Undef = DAG.getUNDEF(InVT);
12327   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12328   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12329   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12330
12331   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12332                              VT.getVectorNumElements()/2);
12333
12334   OpLo = DAG.getBitcast(HVT, OpLo);
12335   OpHi = DAG.getBitcast(HVT, OpHi);
12336
12337   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12338 }
12339
12340 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12341                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12342   MVT VT = Op->getSimpleValueType(0);
12343   SDValue In = Op->getOperand(0);
12344   MVT InVT = In.getSimpleValueType();
12345   SDLoc DL(Op);
12346   unsigned int NumElts = VT.getVectorNumElements();
12347   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12348     return SDValue();
12349
12350   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12351     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12352
12353   assert(InVT.getVectorElementType() == MVT::i1);
12354   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12355   SDValue One =
12356    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12357   SDValue Zero =
12358    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12359
12360   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12361   if (VT.is512BitVector())
12362     return V;
12363   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12364 }
12365
12366 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12367                                SelectionDAG &DAG) {
12368   if (Subtarget->hasFp256())
12369     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12370       return Res;
12371
12372   return SDValue();
12373 }
12374
12375 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12376                                 SelectionDAG &DAG) {
12377   SDLoc DL(Op);
12378   MVT VT = Op.getSimpleValueType();
12379   SDValue In = Op.getOperand(0);
12380   MVT SVT = In.getSimpleValueType();
12381
12382   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12383     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12384
12385   if (Subtarget->hasFp256())
12386     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12387       return Res;
12388
12389   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12390          VT.getVectorNumElements() != SVT.getVectorNumElements());
12391   return SDValue();
12392 }
12393
12394 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12395   SDLoc DL(Op);
12396   MVT VT = Op.getSimpleValueType();
12397   SDValue In = Op.getOperand(0);
12398   MVT InVT = In.getSimpleValueType();
12399
12400   if (VT == MVT::i1) {
12401     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12402            "Invalid scalar TRUNCATE operation");
12403     if (InVT.getSizeInBits() >= 32)
12404       return SDValue();
12405     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12406     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12407   }
12408   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12409          "Invalid TRUNCATE operation");
12410
12411   // move vector to mask - truncate solution for SKX
12412   if (VT.getVectorElementType() == MVT::i1) {
12413     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12414         Subtarget->hasBWI())
12415       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12416     if ((InVT.is256BitVector() || InVT.is128BitVector())
12417         && InVT.getScalarSizeInBits() <= 16 &&
12418         Subtarget->hasBWI() && Subtarget->hasVLX())
12419       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12420     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12421         Subtarget->hasDQI())
12422       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12423     if ((InVT.is256BitVector() || InVT.is128BitVector())
12424         && InVT.getScalarSizeInBits() >= 32 &&
12425         Subtarget->hasDQI() && Subtarget->hasVLX())
12426       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12427   }
12428   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12429     if (VT.getVectorElementType().getSizeInBits() >=8)
12430       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12431
12432     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12433     unsigned NumElts = InVT.getVectorNumElements();
12434     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12435     if (InVT.getSizeInBits() < 512) {
12436       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12437       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12438       InVT = ExtVT;
12439     }
12440
12441     SDValue OneV =
12442      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12443     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12444     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12445   }
12446
12447   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12448     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12449     if (Subtarget->hasInt256()) {
12450       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12451       In = DAG.getBitcast(MVT::v8i32, In);
12452       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12453                                 ShufMask);
12454       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12455                          DAG.getIntPtrConstant(0, DL));
12456     }
12457
12458     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12459                                DAG.getIntPtrConstant(0, DL));
12460     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12461                                DAG.getIntPtrConstant(2, DL));
12462     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12463     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12464     static const int ShufMask[] = {0, 2, 4, 6};
12465     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12466   }
12467
12468   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12469     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12470     if (Subtarget->hasInt256()) {
12471       In = DAG.getBitcast(MVT::v32i8, In);
12472
12473       SmallVector<SDValue,32> pshufbMask;
12474       for (unsigned i = 0; i < 2; ++i) {
12475         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12476         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12477         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12478         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12479         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12480         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12481         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12482         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12483         for (unsigned j = 0; j < 8; ++j)
12484           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12485       }
12486       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12487       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12488       In = DAG.getBitcast(MVT::v4i64, In);
12489
12490       static const int ShufMask[] = {0,  2,  -1,  -1};
12491       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12492                                 &ShufMask[0]);
12493       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12494                        DAG.getIntPtrConstant(0, DL));
12495       return DAG.getBitcast(VT, In);
12496     }
12497
12498     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12499                                DAG.getIntPtrConstant(0, DL));
12500
12501     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12502                                DAG.getIntPtrConstant(4, DL));
12503
12504     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12505     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12506
12507     // The PSHUFB mask:
12508     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12509                                    -1, -1, -1, -1, -1, -1, -1, -1};
12510
12511     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12512     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12513     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12514
12515     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12516     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12517
12518     // The MOVLHPS Mask:
12519     static const int ShufMask2[] = {0, 1, 4, 5};
12520     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12521     return DAG.getBitcast(MVT::v8i16, res);
12522   }
12523
12524   // Handle truncation of V256 to V128 using shuffles.
12525   if (!VT.is128BitVector() || !InVT.is256BitVector())
12526     return SDValue();
12527
12528   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12529
12530   unsigned NumElems = VT.getVectorNumElements();
12531   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12532
12533   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12534   // Prepare truncation shuffle mask
12535   for (unsigned i = 0; i != NumElems; ++i)
12536     MaskVec[i] = i * 2;
12537   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12538                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12539   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12540                      DAG.getIntPtrConstant(0, DL));
12541 }
12542
12543 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12544                                            SelectionDAG &DAG) const {
12545   assert(!Op.getSimpleValueType().isVector());
12546
12547   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12548     /*IsSigned=*/ true, /*IsReplace=*/ false);
12549   SDValue FIST = Vals.first, StackSlot = Vals.second;
12550   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12551   if (!FIST.getNode()) return Op;
12552
12553   if (StackSlot.getNode())
12554     // Load the result.
12555     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12556                        FIST, StackSlot, MachinePointerInfo(),
12557                        false, false, false, 0);
12558
12559   // The node is the result.
12560   return FIST;
12561 }
12562
12563 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12564                                            SelectionDAG &DAG) const {
12565   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12566     /*IsSigned=*/ false, /*IsReplace=*/ false);
12567   SDValue FIST = Vals.first, StackSlot = Vals.second;
12568   assert(FIST.getNode() && "Unexpected failure");
12569
12570   if (StackSlot.getNode())
12571     // Load the result.
12572     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12573                        FIST, StackSlot, MachinePointerInfo(),
12574                        false, false, false, 0);
12575
12576   // The node is the result.
12577   return FIST;
12578 }
12579
12580 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12581   SDLoc DL(Op);
12582   MVT VT = Op.getSimpleValueType();
12583   SDValue In = Op.getOperand(0);
12584   MVT SVT = In.getSimpleValueType();
12585
12586   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12587
12588   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12589                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12590                                  In, DAG.getUNDEF(SVT)));
12591 }
12592
12593 /// The only differences between FABS and FNEG are the mask and the logic op.
12594 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12595 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12596   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12597          "Wrong opcode for lowering FABS or FNEG.");
12598
12599   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12600
12601   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12602   // into an FNABS. We'll lower the FABS after that if it is still in use.
12603   if (IsFABS)
12604     for (SDNode *User : Op->uses())
12605       if (User->getOpcode() == ISD::FNEG)
12606         return Op;
12607
12608   SDValue Op0 = Op.getOperand(0);
12609   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12610
12611   SDLoc dl(Op);
12612   MVT VT = Op.getSimpleValueType();
12613   // Assume scalar op for initialization; update for vector if needed.
12614   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12615   // generate a 16-byte vector constant and logic op even for the scalar case.
12616   // Using a 16-byte mask allows folding the load of the mask with
12617   // the logic op, so it can save (~4 bytes) on code size.
12618   MVT EltVT = VT;
12619   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12620   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12621   // decide if we should generate a 16-byte constant mask when we only need 4 or
12622   // 8 bytes for the scalar case.
12623   if (VT.isVector()) {
12624     EltVT = VT.getVectorElementType();
12625     NumElts = VT.getVectorNumElements();
12626   }
12627
12628   unsigned EltBits = EltVT.getSizeInBits();
12629   LLVMContext *Context = DAG.getContext();
12630   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12631   APInt MaskElt =
12632     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12633   Constant *C = ConstantInt::get(*Context, MaskElt);
12634   C = ConstantVector::getSplat(NumElts, C);
12635   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12636   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12637   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12638   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12639                              MachinePointerInfo::getConstantPool(),
12640                              false, false, false, Alignment);
12641
12642   if (VT.isVector()) {
12643     // For a vector, cast operands to a vector type, perform the logic op,
12644     // and cast the result back to the original value type.
12645     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12646     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12647     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12648                               : DAG.getBitcast(VecVT, Op0);
12649     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12650     return DAG.getBitcast(VT,
12651                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12652   }
12653
12654   // If not vector, then scalar.
12655   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12656   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12657   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12658 }
12659
12660 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12661   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12662   LLVMContext *Context = DAG.getContext();
12663   SDValue Op0 = Op.getOperand(0);
12664   SDValue Op1 = Op.getOperand(1);
12665   SDLoc dl(Op);
12666   MVT VT = Op.getSimpleValueType();
12667   MVT SrcVT = Op1.getSimpleValueType();
12668
12669   // If second operand is smaller, extend it first.
12670   if (SrcVT.bitsLT(VT)) {
12671     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12672     SrcVT = VT;
12673   }
12674   // And if it is bigger, shrink it first.
12675   if (SrcVT.bitsGT(VT)) {
12676     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12677     SrcVT = VT;
12678   }
12679
12680   // At this point the operands and the result should have the same
12681   // type, and that won't be f80 since that is not custom lowered.
12682
12683   const fltSemantics &Sem =
12684       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12685   const unsigned SizeInBits = VT.getSizeInBits();
12686
12687   SmallVector<Constant *, 4> CV(
12688       VT == MVT::f64 ? 2 : 4,
12689       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12690
12691   // First, clear all bits but the sign bit from the second operand (sign).
12692   CV[0] = ConstantFP::get(*Context,
12693                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12694   Constant *C = ConstantVector::get(CV);
12695   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12696   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12697                               MachinePointerInfo::getConstantPool(),
12698                               false, false, false, 16);
12699   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12700
12701   // Next, clear the sign bit from the first operand (magnitude).
12702   // If it's a constant, we can clear it here.
12703   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12704     APFloat APF = Op0CN->getValueAPF();
12705     // If the magnitude is a positive zero, the sign bit alone is enough.
12706     if (APF.isPosZero())
12707       return SignBit;
12708     APF.clearSign();
12709     CV[0] = ConstantFP::get(*Context, APF);
12710   } else {
12711     CV[0] = ConstantFP::get(
12712         *Context,
12713         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12714   }
12715   C = ConstantVector::get(CV);
12716   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12717   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12718                             MachinePointerInfo::getConstantPool(),
12719                             false, false, false, 16);
12720   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12721   if (!isa<ConstantFPSDNode>(Op0))
12722     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12723
12724   // OR the magnitude value with the sign bit.
12725   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12726 }
12727
12728 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12729   SDValue N0 = Op.getOperand(0);
12730   SDLoc dl(Op);
12731   MVT VT = Op.getSimpleValueType();
12732
12733   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12734   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12735                                   DAG.getConstant(1, dl, VT));
12736   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12737 }
12738
12739 // Check whether an OR'd tree is PTEST-able.
12740 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12741                                       SelectionDAG &DAG) {
12742   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12743
12744   if (!Subtarget->hasSSE41())
12745     return SDValue();
12746
12747   if (!Op->hasOneUse())
12748     return SDValue();
12749
12750   SDNode *N = Op.getNode();
12751   SDLoc DL(N);
12752
12753   SmallVector<SDValue, 8> Opnds;
12754   DenseMap<SDValue, unsigned> VecInMap;
12755   SmallVector<SDValue, 8> VecIns;
12756   EVT VT = MVT::Other;
12757
12758   // Recognize a special case where a vector is casted into wide integer to
12759   // test all 0s.
12760   Opnds.push_back(N->getOperand(0));
12761   Opnds.push_back(N->getOperand(1));
12762
12763   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12764     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12765     // BFS traverse all OR'd operands.
12766     if (I->getOpcode() == ISD::OR) {
12767       Opnds.push_back(I->getOperand(0));
12768       Opnds.push_back(I->getOperand(1));
12769       // Re-evaluate the number of nodes to be traversed.
12770       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12771       continue;
12772     }
12773
12774     // Quit if a non-EXTRACT_VECTOR_ELT
12775     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12776       return SDValue();
12777
12778     // Quit if without a constant index.
12779     SDValue Idx = I->getOperand(1);
12780     if (!isa<ConstantSDNode>(Idx))
12781       return SDValue();
12782
12783     SDValue ExtractedFromVec = I->getOperand(0);
12784     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12785     if (M == VecInMap.end()) {
12786       VT = ExtractedFromVec.getValueType();
12787       // Quit if not 128/256-bit vector.
12788       if (!VT.is128BitVector() && !VT.is256BitVector())
12789         return SDValue();
12790       // Quit if not the same type.
12791       if (VecInMap.begin() != VecInMap.end() &&
12792           VT != VecInMap.begin()->first.getValueType())
12793         return SDValue();
12794       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12795       VecIns.push_back(ExtractedFromVec);
12796     }
12797     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12798   }
12799
12800   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12801          "Not extracted from 128-/256-bit vector.");
12802
12803   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12804
12805   for (DenseMap<SDValue, unsigned>::const_iterator
12806         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12807     // Quit if not all elements are used.
12808     if (I->second != FullMask)
12809       return SDValue();
12810   }
12811
12812   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12813
12814   // Cast all vectors into TestVT for PTEST.
12815   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12816     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12817
12818   // If more than one full vectors are evaluated, OR them first before PTEST.
12819   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12820     // Each iteration will OR 2 nodes and append the result until there is only
12821     // 1 node left, i.e. the final OR'd value of all vectors.
12822     SDValue LHS = VecIns[Slot];
12823     SDValue RHS = VecIns[Slot + 1];
12824     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12825   }
12826
12827   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12828                      VecIns.back(), VecIns.back());
12829 }
12830
12831 /// \brief return true if \c Op has a use that doesn't just read flags.
12832 static bool hasNonFlagsUse(SDValue Op) {
12833   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12834        ++UI) {
12835     SDNode *User = *UI;
12836     unsigned UOpNo = UI.getOperandNo();
12837     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12838       // Look pass truncate.
12839       UOpNo = User->use_begin().getOperandNo();
12840       User = *User->use_begin();
12841     }
12842
12843     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12844         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12845       return true;
12846   }
12847   return false;
12848 }
12849
12850 /// Emit nodes that will be selected as "test Op0,Op0", or something
12851 /// equivalent.
12852 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12853                                     SelectionDAG &DAG) const {
12854   if (Op.getValueType() == MVT::i1) {
12855     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12856     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12857                        DAG.getConstant(0, dl, MVT::i8));
12858   }
12859   // CF and OF aren't always set the way we want. Determine which
12860   // of these we need.
12861   bool NeedCF = false;
12862   bool NeedOF = false;
12863   switch (X86CC) {
12864   default: break;
12865   case X86::COND_A: case X86::COND_AE:
12866   case X86::COND_B: case X86::COND_BE:
12867     NeedCF = true;
12868     break;
12869   case X86::COND_G: case X86::COND_GE:
12870   case X86::COND_L: case X86::COND_LE:
12871   case X86::COND_O: case X86::COND_NO: {
12872     // Check if we really need to set the
12873     // Overflow flag. If NoSignedWrap is present
12874     // that is not actually needed.
12875     switch (Op->getOpcode()) {
12876     case ISD::ADD:
12877     case ISD::SUB:
12878     case ISD::MUL:
12879     case ISD::SHL: {
12880       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12881       if (BinNode->Flags.hasNoSignedWrap())
12882         break;
12883     }
12884     default:
12885       NeedOF = true;
12886       break;
12887     }
12888     break;
12889   }
12890   }
12891   // See if we can use the EFLAGS value from the operand instead of
12892   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12893   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12894   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12895     // Emit a CMP with 0, which is the TEST pattern.
12896     //if (Op.getValueType() == MVT::i1)
12897     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12898     //                     DAG.getConstant(0, MVT::i1));
12899     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12900                        DAG.getConstant(0, dl, Op.getValueType()));
12901   }
12902   unsigned Opcode = 0;
12903   unsigned NumOperands = 0;
12904
12905   // Truncate operations may prevent the merge of the SETCC instruction
12906   // and the arithmetic instruction before it. Attempt to truncate the operands
12907   // of the arithmetic instruction and use a reduced bit-width instruction.
12908   bool NeedTruncation = false;
12909   SDValue ArithOp = Op;
12910   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12911     SDValue Arith = Op->getOperand(0);
12912     // Both the trunc and the arithmetic op need to have one user each.
12913     if (Arith->hasOneUse())
12914       switch (Arith.getOpcode()) {
12915         default: break;
12916         case ISD::ADD:
12917         case ISD::SUB:
12918         case ISD::AND:
12919         case ISD::OR:
12920         case ISD::XOR: {
12921           NeedTruncation = true;
12922           ArithOp = Arith;
12923         }
12924       }
12925   }
12926
12927   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12928   // which may be the result of a CAST.  We use the variable 'Op', which is the
12929   // non-casted variable when we check for possible users.
12930   switch (ArithOp.getOpcode()) {
12931   case ISD::ADD:
12932     // Due to an isel shortcoming, be conservative if this add is likely to be
12933     // selected as part of a load-modify-store instruction. When the root node
12934     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12935     // uses of other nodes in the match, such as the ADD in this case. This
12936     // leads to the ADD being left around and reselected, with the result being
12937     // two adds in the output.  Alas, even if none our users are stores, that
12938     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12939     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12940     // climbing the DAG back to the root, and it doesn't seem to be worth the
12941     // effort.
12942     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12943          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12944       if (UI->getOpcode() != ISD::CopyToReg &&
12945           UI->getOpcode() != ISD::SETCC &&
12946           UI->getOpcode() != ISD::STORE)
12947         goto default_case;
12948
12949     if (ConstantSDNode *C =
12950         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12951       // An add of one will be selected as an INC.
12952       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12953         Opcode = X86ISD::INC;
12954         NumOperands = 1;
12955         break;
12956       }
12957
12958       // An add of negative one (subtract of one) will be selected as a DEC.
12959       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12960         Opcode = X86ISD::DEC;
12961         NumOperands = 1;
12962         break;
12963       }
12964     }
12965
12966     // Otherwise use a regular EFLAGS-setting add.
12967     Opcode = X86ISD::ADD;
12968     NumOperands = 2;
12969     break;
12970   case ISD::SHL:
12971   case ISD::SRL:
12972     // If we have a constant logical shift that's only used in a comparison
12973     // against zero turn it into an equivalent AND. This allows turning it into
12974     // a TEST instruction later.
12975     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12976         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12977       EVT VT = Op.getValueType();
12978       unsigned BitWidth = VT.getSizeInBits();
12979       unsigned ShAmt = Op->getConstantOperandVal(1);
12980       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12981         break;
12982       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12983                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12984                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12985       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12986         break;
12987       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12988                                 DAG.getConstant(Mask, dl, VT));
12989       DAG.ReplaceAllUsesWith(Op, New);
12990       Op = New;
12991     }
12992     break;
12993
12994   case ISD::AND:
12995     // If the primary and result isn't used, don't bother using X86ISD::AND,
12996     // because a TEST instruction will be better.
12997     if (!hasNonFlagsUse(Op))
12998       break;
12999     // FALL THROUGH
13000   case ISD::SUB:
13001   case ISD::OR:
13002   case ISD::XOR:
13003     // Due to the ISEL shortcoming noted above, be conservative if this op is
13004     // likely to be selected as part of a load-modify-store instruction.
13005     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13006            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13007       if (UI->getOpcode() == ISD::STORE)
13008         goto default_case;
13009
13010     // Otherwise use a regular EFLAGS-setting instruction.
13011     switch (ArithOp.getOpcode()) {
13012     default: llvm_unreachable("unexpected operator!");
13013     case ISD::SUB: Opcode = X86ISD::SUB; break;
13014     case ISD::XOR: Opcode = X86ISD::XOR; break;
13015     case ISD::AND: Opcode = X86ISD::AND; break;
13016     case ISD::OR: {
13017       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13018         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13019         if (EFLAGS.getNode())
13020           return EFLAGS;
13021       }
13022       Opcode = X86ISD::OR;
13023       break;
13024     }
13025     }
13026
13027     NumOperands = 2;
13028     break;
13029   case X86ISD::ADD:
13030   case X86ISD::SUB:
13031   case X86ISD::INC:
13032   case X86ISD::DEC:
13033   case X86ISD::OR:
13034   case X86ISD::XOR:
13035   case X86ISD::AND:
13036     return SDValue(Op.getNode(), 1);
13037   default:
13038   default_case:
13039     break;
13040   }
13041
13042   // If we found that truncation is beneficial, perform the truncation and
13043   // update 'Op'.
13044   if (NeedTruncation) {
13045     EVT VT = Op.getValueType();
13046     SDValue WideVal = Op->getOperand(0);
13047     EVT WideVT = WideVal.getValueType();
13048     unsigned ConvertedOp = 0;
13049     // Use a target machine opcode to prevent further DAGCombine
13050     // optimizations that may separate the arithmetic operations
13051     // from the setcc node.
13052     switch (WideVal.getOpcode()) {
13053       default: break;
13054       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13055       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13056       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13057       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13058       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13059     }
13060
13061     if (ConvertedOp) {
13062       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13063       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13064         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13065         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13066         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13067       }
13068     }
13069   }
13070
13071   if (Opcode == 0)
13072     // Emit a CMP with 0, which is the TEST pattern.
13073     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13074                        DAG.getConstant(0, dl, Op.getValueType()));
13075
13076   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13077   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13078
13079   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13080   DAG.ReplaceAllUsesWith(Op, New);
13081   return SDValue(New.getNode(), 1);
13082 }
13083
13084 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13085 /// equivalent.
13086 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13087                                    SDLoc dl, SelectionDAG &DAG) const {
13088   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13089     if (C->getAPIntValue() == 0)
13090       return EmitTest(Op0, X86CC, dl, DAG);
13091
13092      if (Op0.getValueType() == MVT::i1)
13093        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13094   }
13095
13096   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13097        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13098     // Do the comparison at i32 if it's smaller, besides the Atom case.
13099     // This avoids subregister aliasing issues. Keep the smaller reference
13100     // if we're optimizing for size, however, as that'll allow better folding
13101     // of memory operations.
13102     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13103         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13104             Attribute::MinSize) &&
13105         !Subtarget->isAtom()) {
13106       unsigned ExtendOp =
13107           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13108       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13109       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13110     }
13111     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13112     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13113     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13114                               Op0, Op1);
13115     return SDValue(Sub.getNode(), 1);
13116   }
13117   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13118 }
13119
13120 /// Convert a comparison if required by the subtarget.
13121 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13122                                                  SelectionDAG &DAG) const {
13123   // If the subtarget does not support the FUCOMI instruction, floating-point
13124   // comparisons have to be converted.
13125   if (Subtarget->hasCMov() ||
13126       Cmp.getOpcode() != X86ISD::CMP ||
13127       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13128       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13129     return Cmp;
13130
13131   // The instruction selector will select an FUCOM instruction instead of
13132   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13133   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13134   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13135   SDLoc dl(Cmp);
13136   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13137   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13138   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13139                             DAG.getConstant(8, dl, MVT::i8));
13140   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13141   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13142 }
13143
13144 /// The minimum architected relative accuracy is 2^-12. We need one
13145 /// Newton-Raphson step to have a good float result (24 bits of precision).
13146 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13147                                             DAGCombinerInfo &DCI,
13148                                             unsigned &RefinementSteps,
13149                                             bool &UseOneConstNR) const {
13150   EVT VT = Op.getValueType();
13151   const char *RecipOp;
13152
13153   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13154   // TODO: Add support for AVX512 (v16f32).
13155   // It is likely not profitable to do this for f64 because a double-precision
13156   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13157   // instructions: convert to single, rsqrtss, convert back to double, refine
13158   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13159   // along with FMA, this could be a throughput win.
13160   if (VT == MVT::f32 && Subtarget->hasSSE1())
13161     RecipOp = "sqrtf";
13162   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13163            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13164     RecipOp = "vec-sqrtf";
13165   else
13166     return SDValue();
13167
13168   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13169   if (!Recips.isEnabled(RecipOp))
13170     return SDValue();
13171
13172   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13173   UseOneConstNR = false;
13174   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13175 }
13176
13177 /// The minimum architected relative accuracy is 2^-12. We need one
13178 /// Newton-Raphson step to have a good float result (24 bits of precision).
13179 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13180                                             DAGCombinerInfo &DCI,
13181                                             unsigned &RefinementSteps) const {
13182   EVT VT = Op.getValueType();
13183   const char *RecipOp;
13184
13185   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13186   // TODO: Add support for AVX512 (v16f32).
13187   // It is likely not profitable to do this for f64 because a double-precision
13188   // reciprocal estimate with refinement on x86 prior to FMA requires
13189   // 15 instructions: convert to single, rcpss, convert back to double, refine
13190   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13191   // along with FMA, this could be a throughput win.
13192   if (VT == MVT::f32 && Subtarget->hasSSE1())
13193     RecipOp = "divf";
13194   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13195            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13196     RecipOp = "vec-divf";
13197   else
13198     return SDValue();
13199
13200   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13201   if (!Recips.isEnabled(RecipOp))
13202     return SDValue();
13203
13204   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13205   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13206 }
13207
13208 /// If we have at least two divisions that use the same divisor, convert to
13209 /// multplication by a reciprocal. This may need to be adjusted for a given
13210 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13211 /// This is because we still need one division to calculate the reciprocal and
13212 /// then we need two multiplies by that reciprocal as replacements for the
13213 /// original divisions.
13214 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13215   return NumUsers > 1;
13216 }
13217
13218 static bool isAllOnes(SDValue V) {
13219   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13220   return C && C->isAllOnesValue();
13221 }
13222
13223 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13224 /// if it's possible.
13225 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13226                                      SDLoc dl, SelectionDAG &DAG) const {
13227   SDValue Op0 = And.getOperand(0);
13228   SDValue Op1 = And.getOperand(1);
13229   if (Op0.getOpcode() == ISD::TRUNCATE)
13230     Op0 = Op0.getOperand(0);
13231   if (Op1.getOpcode() == ISD::TRUNCATE)
13232     Op1 = Op1.getOperand(0);
13233
13234   SDValue LHS, RHS;
13235   if (Op1.getOpcode() == ISD::SHL)
13236     std::swap(Op0, Op1);
13237   if (Op0.getOpcode() == ISD::SHL) {
13238     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13239       if (And00C->getZExtValue() == 1) {
13240         // If we looked past a truncate, check that it's only truncating away
13241         // known zeros.
13242         unsigned BitWidth = Op0.getValueSizeInBits();
13243         unsigned AndBitWidth = And.getValueSizeInBits();
13244         if (BitWidth > AndBitWidth) {
13245           APInt Zeros, Ones;
13246           DAG.computeKnownBits(Op0, Zeros, Ones);
13247           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13248             return SDValue();
13249         }
13250         LHS = Op1;
13251         RHS = Op0.getOperand(1);
13252       }
13253   } else if (Op1.getOpcode() == ISD::Constant) {
13254     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13255     uint64_t AndRHSVal = AndRHS->getZExtValue();
13256     SDValue AndLHS = Op0;
13257
13258     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13259       LHS = AndLHS.getOperand(0);
13260       RHS = AndLHS.getOperand(1);
13261     }
13262
13263     // Use BT if the immediate can't be encoded in a TEST instruction.
13264     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13265       LHS = AndLHS;
13266       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13267     }
13268   }
13269
13270   if (LHS.getNode()) {
13271     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13272     // instruction.  Since the shift amount is in-range-or-undefined, we know
13273     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13274     // the encoding for the i16 version is larger than the i32 version.
13275     // Also promote i16 to i32 for performance / code size reason.
13276     if (LHS.getValueType() == MVT::i8 ||
13277         LHS.getValueType() == MVT::i16)
13278       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13279
13280     // If the operand types disagree, extend the shift amount to match.  Since
13281     // BT ignores high bits (like shifts) we can use anyextend.
13282     if (LHS.getValueType() != RHS.getValueType())
13283       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13284
13285     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13286     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13287     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13288                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13289   }
13290
13291   return SDValue();
13292 }
13293
13294 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13295 /// mask CMPs.
13296 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13297                               SDValue &Op1) {
13298   unsigned SSECC;
13299   bool Swap = false;
13300
13301   // SSE Condition code mapping:
13302   //  0 - EQ
13303   //  1 - LT
13304   //  2 - LE
13305   //  3 - UNORD
13306   //  4 - NEQ
13307   //  5 - NLT
13308   //  6 - NLE
13309   //  7 - ORD
13310   switch (SetCCOpcode) {
13311   default: llvm_unreachable("Unexpected SETCC condition");
13312   case ISD::SETOEQ:
13313   case ISD::SETEQ:  SSECC = 0; break;
13314   case ISD::SETOGT:
13315   case ISD::SETGT:  Swap = true; // Fallthrough
13316   case ISD::SETLT:
13317   case ISD::SETOLT: SSECC = 1; break;
13318   case ISD::SETOGE:
13319   case ISD::SETGE:  Swap = true; // Fallthrough
13320   case ISD::SETLE:
13321   case ISD::SETOLE: SSECC = 2; break;
13322   case ISD::SETUO:  SSECC = 3; break;
13323   case ISD::SETUNE:
13324   case ISD::SETNE:  SSECC = 4; break;
13325   case ISD::SETULE: Swap = true; // Fallthrough
13326   case ISD::SETUGE: SSECC = 5; break;
13327   case ISD::SETULT: Swap = true; // Fallthrough
13328   case ISD::SETUGT: SSECC = 6; break;
13329   case ISD::SETO:   SSECC = 7; break;
13330   case ISD::SETUEQ:
13331   case ISD::SETONE: SSECC = 8; break;
13332   }
13333   if (Swap)
13334     std::swap(Op0, Op1);
13335
13336   return SSECC;
13337 }
13338
13339 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13340 // ones, and then concatenate the result back.
13341 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13342   MVT VT = Op.getSimpleValueType();
13343
13344   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13345          "Unsupported value type for operation");
13346
13347   unsigned NumElems = VT.getVectorNumElements();
13348   SDLoc dl(Op);
13349   SDValue CC = Op.getOperand(2);
13350
13351   // Extract the LHS vectors
13352   SDValue LHS = Op.getOperand(0);
13353   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13354   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13355
13356   // Extract the RHS vectors
13357   SDValue RHS = Op.getOperand(1);
13358   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13359   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13360
13361   // Issue the operation on the smaller types and concatenate the result back
13362   MVT EltVT = VT.getVectorElementType();
13363   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13364   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13365                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13366                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13367 }
13368
13369 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13370   SDValue Op0 = Op.getOperand(0);
13371   SDValue Op1 = Op.getOperand(1);
13372   SDValue CC = Op.getOperand(2);
13373   MVT VT = Op.getSimpleValueType();
13374   SDLoc dl(Op);
13375
13376   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13377          "Unexpected type for boolean compare operation");
13378   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13379   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13380                                DAG.getConstant(-1, dl, VT));
13381   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13382                                DAG.getConstant(-1, dl, VT));
13383   switch (SetCCOpcode) {
13384   default: llvm_unreachable("Unexpected SETCC condition");
13385   case ISD::SETEQ:
13386     // (x == y) -> ~(x ^ y)
13387     return DAG.getNode(ISD::XOR, dl, VT,
13388                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13389                        DAG.getConstant(-1, dl, VT));
13390   case ISD::SETNE:
13391     // (x != y) -> (x ^ y)
13392     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13393   case ISD::SETUGT:
13394   case ISD::SETGT:
13395     // (x > y) -> (x & ~y)
13396     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13397   case ISD::SETULT:
13398   case ISD::SETLT:
13399     // (x < y) -> (~x & y)
13400     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13401   case ISD::SETULE:
13402   case ISD::SETLE:
13403     // (x <= y) -> (~x | y)
13404     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13405   case ISD::SETUGE:
13406   case ISD::SETGE:
13407     // (x >=y) -> (x | ~y)
13408     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13409   }
13410 }
13411
13412 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13413                                      const X86Subtarget *Subtarget) {
13414   SDValue Op0 = Op.getOperand(0);
13415   SDValue Op1 = Op.getOperand(1);
13416   SDValue CC = Op.getOperand(2);
13417   MVT VT = Op.getSimpleValueType();
13418   SDLoc dl(Op);
13419
13420   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13421          Op.getValueType().getScalarType() == MVT::i1 &&
13422          "Cannot set masked compare for this operation");
13423
13424   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13425   unsigned  Opc = 0;
13426   bool Unsigned = false;
13427   bool Swap = false;
13428   unsigned SSECC;
13429   switch (SetCCOpcode) {
13430   default: llvm_unreachable("Unexpected SETCC condition");
13431   case ISD::SETNE:  SSECC = 4; break;
13432   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13433   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13434   case ISD::SETLT:  Swap = true; //fall-through
13435   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13436   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13437   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13438   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13439   case ISD::SETULE: Unsigned = true; //fall-through
13440   case ISD::SETLE:  SSECC = 2; break;
13441   }
13442
13443   if (Swap)
13444     std::swap(Op0, Op1);
13445   if (Opc)
13446     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13447   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13448   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13449                      DAG.getConstant(SSECC, dl, MVT::i8));
13450 }
13451
13452 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13453 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13454 /// return an empty value.
13455 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13456 {
13457   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13458   if (!BV)
13459     return SDValue();
13460
13461   MVT VT = Op1.getSimpleValueType();
13462   MVT EVT = VT.getVectorElementType();
13463   unsigned n = VT.getVectorNumElements();
13464   SmallVector<SDValue, 8> ULTOp1;
13465
13466   for (unsigned i = 0; i < n; ++i) {
13467     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13468     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13469       return SDValue();
13470
13471     // Avoid underflow.
13472     APInt Val = Elt->getAPIntValue();
13473     if (Val == 0)
13474       return SDValue();
13475
13476     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13477   }
13478
13479   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13480 }
13481
13482 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13483                            SelectionDAG &DAG) {
13484   SDValue Op0 = Op.getOperand(0);
13485   SDValue Op1 = Op.getOperand(1);
13486   SDValue CC = Op.getOperand(2);
13487   MVT VT = Op.getSimpleValueType();
13488   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13489   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13490   SDLoc dl(Op);
13491
13492   if (isFP) {
13493 #ifndef NDEBUG
13494     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13495     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13496 #endif
13497
13498     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13499     unsigned Opc = X86ISD::CMPP;
13500     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13501       assert(VT.getVectorNumElements() <= 16);
13502       Opc = X86ISD::CMPM;
13503     }
13504     // In the two special cases we can't handle, emit two comparisons.
13505     if (SSECC == 8) {
13506       unsigned CC0, CC1;
13507       unsigned CombineOpc;
13508       if (SetCCOpcode == ISD::SETUEQ) {
13509         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13510       } else {
13511         assert(SetCCOpcode == ISD::SETONE);
13512         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13513       }
13514
13515       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13516                                  DAG.getConstant(CC0, dl, MVT::i8));
13517       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13518                                  DAG.getConstant(CC1, dl, MVT::i8));
13519       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13520     }
13521     // Handle all other FP comparisons here.
13522     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13523                        DAG.getConstant(SSECC, dl, MVT::i8));
13524   }
13525
13526   // Break 256-bit integer vector compare into smaller ones.
13527   if (VT.is256BitVector() && !Subtarget->hasInt256())
13528     return Lower256IntVSETCC(Op, DAG);
13529
13530   EVT OpVT = Op1.getValueType();
13531   if (OpVT.getVectorElementType() == MVT::i1)
13532     return LowerBoolVSETCC_AVX512(Op, DAG);
13533
13534   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13535   if (Subtarget->hasAVX512()) {
13536     if (Op1.getValueType().is512BitVector() ||
13537         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13538         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13539       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13540
13541     // In AVX-512 architecture setcc returns mask with i1 elements,
13542     // But there is no compare instruction for i8 and i16 elements in KNL.
13543     // We are not talking about 512-bit operands in this case, these
13544     // types are illegal.
13545     if (MaskResult &&
13546         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13547          OpVT.getVectorElementType().getSizeInBits() >= 8))
13548       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13549                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13550   }
13551
13552   // We are handling one of the integer comparisons here.  Since SSE only has
13553   // GT and EQ comparisons for integer, swapping operands and multiple
13554   // operations may be required for some comparisons.
13555   unsigned Opc;
13556   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13557   bool Subus = false;
13558
13559   switch (SetCCOpcode) {
13560   default: llvm_unreachable("Unexpected SETCC condition");
13561   case ISD::SETNE:  Invert = true;
13562   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13563   case ISD::SETLT:  Swap = true;
13564   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13565   case ISD::SETGE:  Swap = true;
13566   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13567                     Invert = true; break;
13568   case ISD::SETULT: Swap = true;
13569   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13570                     FlipSigns = true; break;
13571   case ISD::SETUGE: Swap = true;
13572   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13573                     FlipSigns = true; Invert = true; break;
13574   }
13575
13576   // Special case: Use min/max operations for SETULE/SETUGE
13577   MVT VET = VT.getVectorElementType();
13578   bool hasMinMax =
13579        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13580     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13581
13582   if (hasMinMax) {
13583     switch (SetCCOpcode) {
13584     default: break;
13585     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13586     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13587     }
13588
13589     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13590   }
13591
13592   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13593   if (!MinMax && hasSubus) {
13594     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13595     // Op0 u<= Op1:
13596     //   t = psubus Op0, Op1
13597     //   pcmpeq t, <0..0>
13598     switch (SetCCOpcode) {
13599     default: break;
13600     case ISD::SETULT: {
13601       // If the comparison is against a constant we can turn this into a
13602       // setule.  With psubus, setule does not require a swap.  This is
13603       // beneficial because the constant in the register is no longer
13604       // destructed as the destination so it can be hoisted out of a loop.
13605       // Only do this pre-AVX since vpcmp* is no longer destructive.
13606       if (Subtarget->hasAVX())
13607         break;
13608       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13609       if (ULEOp1.getNode()) {
13610         Op1 = ULEOp1;
13611         Subus = true; Invert = false; Swap = false;
13612       }
13613       break;
13614     }
13615     // Psubus is better than flip-sign because it requires no inversion.
13616     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13617     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13618     }
13619
13620     if (Subus) {
13621       Opc = X86ISD::SUBUS;
13622       FlipSigns = false;
13623     }
13624   }
13625
13626   if (Swap)
13627     std::swap(Op0, Op1);
13628
13629   // Check that the operation in question is available (most are plain SSE2,
13630   // but PCMPGTQ and PCMPEQQ have different requirements).
13631   if (VT == MVT::v2i64) {
13632     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13633       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13634
13635       // First cast everything to the right type.
13636       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13637       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13638
13639       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13640       // bits of the inputs before performing those operations. The lower
13641       // compare is always unsigned.
13642       SDValue SB;
13643       if (FlipSigns) {
13644         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13645       } else {
13646         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13647         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13648         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13649                          Sign, Zero, Sign, Zero);
13650       }
13651       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13652       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13653
13654       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13655       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13656       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13657
13658       // Create masks for only the low parts/high parts of the 64 bit integers.
13659       static const int MaskHi[] = { 1, 1, 3, 3 };
13660       static const int MaskLo[] = { 0, 0, 2, 2 };
13661       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13662       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13663       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13664
13665       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13666       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13667
13668       if (Invert)
13669         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13670
13671       return DAG.getBitcast(VT, Result);
13672     }
13673
13674     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13675       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13676       // pcmpeqd + pshufd + pand.
13677       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13678
13679       // First cast everything to the right type.
13680       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13681       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13682
13683       // Do the compare.
13684       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13685
13686       // Make sure the lower and upper halves are both all-ones.
13687       static const int Mask[] = { 1, 0, 3, 2 };
13688       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13689       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13690
13691       if (Invert)
13692         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13693
13694       return DAG.getBitcast(VT, Result);
13695     }
13696   }
13697
13698   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13699   // bits of the inputs before performing those operations.
13700   if (FlipSigns) {
13701     EVT EltVT = VT.getVectorElementType();
13702     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13703                                  VT);
13704     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13705     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13706   }
13707
13708   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13709
13710   // If the logical-not of the result is required, perform that now.
13711   if (Invert)
13712     Result = DAG.getNOT(dl, Result, VT);
13713
13714   if (MinMax)
13715     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13716
13717   if (Subus)
13718     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13719                          getZeroVector(VT, Subtarget, DAG, dl));
13720
13721   return Result;
13722 }
13723
13724 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13725
13726   MVT VT = Op.getSimpleValueType();
13727
13728   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13729
13730   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13731          && "SetCC type must be 8-bit or 1-bit integer");
13732   SDValue Op0 = Op.getOperand(0);
13733   SDValue Op1 = Op.getOperand(1);
13734   SDLoc dl(Op);
13735   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13736
13737   // Optimize to BT if possible.
13738   // Lower (X & (1 << N)) == 0 to BT(X, N).
13739   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13740   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13741   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13742       Op1.getOpcode() == ISD::Constant &&
13743       cast<ConstantSDNode>(Op1)->isNullValue() &&
13744       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13745     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13746     if (NewSetCC.getNode()) {
13747       if (VT == MVT::i1)
13748         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13749       return NewSetCC;
13750     }
13751   }
13752
13753   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13754   // these.
13755   if (Op1.getOpcode() == ISD::Constant &&
13756       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13757        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13758       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13759
13760     // If the input is a setcc, then reuse the input setcc or use a new one with
13761     // the inverted condition.
13762     if (Op0.getOpcode() == X86ISD::SETCC) {
13763       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13764       bool Invert = (CC == ISD::SETNE) ^
13765         cast<ConstantSDNode>(Op1)->isNullValue();
13766       if (!Invert)
13767         return Op0;
13768
13769       CCode = X86::GetOppositeBranchCondition(CCode);
13770       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13771                                   DAG.getConstant(CCode, dl, MVT::i8),
13772                                   Op0.getOperand(1));
13773       if (VT == MVT::i1)
13774         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13775       return SetCC;
13776     }
13777   }
13778   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13779       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13780       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13781
13782     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13783     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13784   }
13785
13786   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13787   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13788   if (X86CC == X86::COND_INVALID)
13789     return SDValue();
13790
13791   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13792   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13793   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13794                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13795   if (VT == MVT::i1)
13796     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13797   return SetCC;
13798 }
13799
13800 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13801 static bool isX86LogicalCmp(SDValue Op) {
13802   unsigned Opc = Op.getNode()->getOpcode();
13803   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13804       Opc == X86ISD::SAHF)
13805     return true;
13806   if (Op.getResNo() == 1 &&
13807       (Opc == X86ISD::ADD ||
13808        Opc == X86ISD::SUB ||
13809        Opc == X86ISD::ADC ||
13810        Opc == X86ISD::SBB ||
13811        Opc == X86ISD::SMUL ||
13812        Opc == X86ISD::UMUL ||
13813        Opc == X86ISD::INC ||
13814        Opc == X86ISD::DEC ||
13815        Opc == X86ISD::OR ||
13816        Opc == X86ISD::XOR ||
13817        Opc == X86ISD::AND))
13818     return true;
13819
13820   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13821     return true;
13822
13823   return false;
13824 }
13825
13826 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13827   if (V.getOpcode() != ISD::TRUNCATE)
13828     return false;
13829
13830   SDValue VOp0 = V.getOperand(0);
13831   unsigned InBits = VOp0.getValueSizeInBits();
13832   unsigned Bits = V.getValueSizeInBits();
13833   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13834 }
13835
13836 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13837   bool addTest = true;
13838   SDValue Cond  = Op.getOperand(0);
13839   SDValue Op1 = Op.getOperand(1);
13840   SDValue Op2 = Op.getOperand(2);
13841   SDLoc DL(Op);
13842   EVT VT = Op1.getValueType();
13843   SDValue CC;
13844
13845   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13846   // are available or VBLENDV if AVX is available.
13847   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13848   if (Cond.getOpcode() == ISD::SETCC &&
13849       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13850        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13851       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13852     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13853     int SSECC = translateX86FSETCC(
13854         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13855
13856     if (SSECC != 8) {
13857       if (Subtarget->hasAVX512()) {
13858         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13859                                   DAG.getConstant(SSECC, DL, MVT::i8));
13860         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13861       }
13862
13863       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13864                                 DAG.getConstant(SSECC, DL, MVT::i8));
13865
13866       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13867       // of 3 logic instructions for size savings and potentially speed.
13868       // Unfortunately, there is no scalar form of VBLENDV.
13869
13870       // If either operand is a constant, don't try this. We can expect to
13871       // optimize away at least one of the logic instructions later in that
13872       // case, so that sequence would be faster than a variable blend.
13873
13874       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13875       // uses XMM0 as the selection register. That may need just as many
13876       // instructions as the AND/ANDN/OR sequence due to register moves, so
13877       // don't bother.
13878
13879       if (Subtarget->hasAVX() &&
13880           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13881
13882         // Convert to vectors, do a VSELECT, and convert back to scalar.
13883         // All of the conversions should be optimized away.
13884
13885         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13886         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13887         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13888         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13889
13890         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13891         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13892
13893         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13894
13895         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13896                            VSel, DAG.getIntPtrConstant(0, DL));
13897       }
13898       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13899       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13900       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13901     }
13902   }
13903
13904     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13905       SDValue Op1Scalar;
13906       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13907         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13908       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13909         Op1Scalar = Op1.getOperand(0);
13910       SDValue Op2Scalar;
13911       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13912         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13913       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13914         Op2Scalar = Op2.getOperand(0);
13915       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13916         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13917                                         Op1Scalar.getValueType(),
13918                                         Cond, Op1Scalar, Op2Scalar);
13919         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13920           return DAG.getBitcast(VT, newSelect);
13921         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13922         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13923                            DAG.getIntPtrConstant(0, DL));
13924     }
13925   }
13926
13927   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13928     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13929     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13930                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13931     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13932                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13933     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13934                                     Cond, Op1, Op2);
13935     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13936   }
13937
13938   if (Cond.getOpcode() == ISD::SETCC) {
13939     SDValue NewCond = LowerSETCC(Cond, DAG);
13940     if (NewCond.getNode())
13941       Cond = NewCond;
13942   }
13943
13944   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13945   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13946   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13947   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13948   if (Cond.getOpcode() == X86ISD::SETCC &&
13949       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13950       isZero(Cond.getOperand(1).getOperand(1))) {
13951     SDValue Cmp = Cond.getOperand(1);
13952
13953     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13954
13955     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13956         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13957       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13958
13959       SDValue CmpOp0 = Cmp.getOperand(0);
13960       // Apply further optimizations for special cases
13961       // (select (x != 0), -1, 0) -> neg & sbb
13962       // (select (x == 0), 0, -1) -> neg & sbb
13963       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13964         if (YC->isNullValue() &&
13965             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13966           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13967           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13968                                     DAG.getConstant(0, DL,
13969                                                     CmpOp0.getValueType()),
13970                                     CmpOp0);
13971           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13972                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13973                                     SDValue(Neg.getNode(), 1));
13974           return Res;
13975         }
13976
13977       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13978                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13979       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13980
13981       SDValue Res =   // Res = 0 or -1.
13982         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13983                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13984
13985       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13986         Res = DAG.getNOT(DL, Res, Res.getValueType());
13987
13988       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13989       if (!N2C || !N2C->isNullValue())
13990         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13991       return Res;
13992     }
13993   }
13994
13995   // Look past (and (setcc_carry (cmp ...)), 1).
13996   if (Cond.getOpcode() == ISD::AND &&
13997       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13998     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13999     if (C && C->getAPIntValue() == 1)
14000       Cond = Cond.getOperand(0);
14001   }
14002
14003   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14004   // setting operand in place of the X86ISD::SETCC.
14005   unsigned CondOpcode = Cond.getOpcode();
14006   if (CondOpcode == X86ISD::SETCC ||
14007       CondOpcode == X86ISD::SETCC_CARRY) {
14008     CC = Cond.getOperand(0);
14009
14010     SDValue Cmp = Cond.getOperand(1);
14011     unsigned Opc = Cmp.getOpcode();
14012     MVT VT = Op.getSimpleValueType();
14013
14014     bool IllegalFPCMov = false;
14015     if (VT.isFloatingPoint() && !VT.isVector() &&
14016         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14017       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14018
14019     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14020         Opc == X86ISD::BT) { // FIXME
14021       Cond = Cmp;
14022       addTest = false;
14023     }
14024   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14025              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14026              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14027               Cond.getOperand(0).getValueType() != MVT::i8)) {
14028     SDValue LHS = Cond.getOperand(0);
14029     SDValue RHS = Cond.getOperand(1);
14030     unsigned X86Opcode;
14031     unsigned X86Cond;
14032     SDVTList VTs;
14033     switch (CondOpcode) {
14034     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14035     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14036     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14037     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14038     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14039     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14040     default: llvm_unreachable("unexpected overflowing operator");
14041     }
14042     if (CondOpcode == ISD::UMULO)
14043       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14044                           MVT::i32);
14045     else
14046       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14047
14048     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14049
14050     if (CondOpcode == ISD::UMULO)
14051       Cond = X86Op.getValue(2);
14052     else
14053       Cond = X86Op.getValue(1);
14054
14055     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14056     addTest = false;
14057   }
14058
14059   if (addTest) {
14060     // Look pass the truncate if the high bits are known zero.
14061     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14062         Cond = Cond.getOperand(0);
14063
14064     // We know the result of AND is compared against zero. Try to match
14065     // it to BT.
14066     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14067       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14068       if (NewSetCC.getNode()) {
14069         CC = NewSetCC.getOperand(0);
14070         Cond = NewSetCC.getOperand(1);
14071         addTest = false;
14072       }
14073     }
14074   }
14075
14076   if (addTest) {
14077     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14078     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14079   }
14080
14081   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14082   // a <  b ?  0 : -1 -> RES = setcc_carry
14083   // a >= b ? -1 :  0 -> RES = setcc_carry
14084   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14085   if (Cond.getOpcode() == X86ISD::SUB) {
14086     Cond = ConvertCmpIfNecessary(Cond, DAG);
14087     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14088
14089     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14090         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14091       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14092                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14093                                 Cond);
14094       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14095         return DAG.getNOT(DL, Res, Res.getValueType());
14096       return Res;
14097     }
14098   }
14099
14100   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14101   // widen the cmov and push the truncate through. This avoids introducing a new
14102   // branch during isel and doesn't add any extensions.
14103   if (Op.getValueType() == MVT::i8 &&
14104       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14105     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14106     if (T1.getValueType() == T2.getValueType() &&
14107         // Blacklist CopyFromReg to avoid partial register stalls.
14108         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14109       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14110       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14111       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14112     }
14113   }
14114
14115   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14116   // condition is true.
14117   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14118   SDValue Ops[] = { Op2, Op1, CC, Cond };
14119   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14120 }
14121
14122 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14123                                        const X86Subtarget *Subtarget,
14124                                        SelectionDAG &DAG) {
14125   MVT VT = Op->getSimpleValueType(0);
14126   SDValue In = Op->getOperand(0);
14127   MVT InVT = In.getSimpleValueType();
14128   MVT VTElt = VT.getVectorElementType();
14129   MVT InVTElt = InVT.getVectorElementType();
14130   SDLoc dl(Op);
14131
14132   // SKX processor
14133   if ((InVTElt == MVT::i1) &&
14134       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14135         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14136
14137        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14138         VTElt.getSizeInBits() <= 16)) ||
14139
14140        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14141         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14142
14143        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14144         VTElt.getSizeInBits() >= 32))))
14145     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14146
14147   unsigned int NumElts = VT.getVectorNumElements();
14148
14149   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14150     return SDValue();
14151
14152   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14153     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14154       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14155     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14156   }
14157
14158   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14159   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14160   SDValue NegOne =
14161    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14162                    ExtVT);
14163   SDValue Zero =
14164    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14165
14166   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14167   if (VT.is512BitVector())
14168     return V;
14169   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14170 }
14171
14172 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14173                                              const X86Subtarget *Subtarget,
14174                                              SelectionDAG &DAG) {
14175   SDValue In = Op->getOperand(0);
14176   MVT VT = Op->getSimpleValueType(0);
14177   MVT InVT = In.getSimpleValueType();
14178   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14179
14180   MVT InSVT = InVT.getScalarType();
14181   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14182
14183   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14184     return SDValue();
14185   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14186     return SDValue();
14187
14188   SDLoc dl(Op);
14189
14190   // SSE41 targets can use the pmovsx* instructions directly.
14191   if (Subtarget->hasSSE41())
14192     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14193
14194   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14195   SDValue Curr = In;
14196   MVT CurrVT = InVT;
14197
14198   // As SRAI is only available on i16/i32 types, we expand only up to i32
14199   // and handle i64 separately.
14200   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14201     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14202     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14203     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14204     Curr = DAG.getBitcast(CurrVT, Curr);
14205   }
14206
14207   SDValue SignExt = Curr;
14208   if (CurrVT != InVT) {
14209     unsigned SignExtShift =
14210         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14211     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14212                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14213   }
14214
14215   if (CurrVT == VT)
14216     return SignExt;
14217
14218   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14219     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14220                                DAG.getConstant(31, dl, MVT::i8));
14221     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14222     return DAG.getBitcast(VT, Ext);
14223   }
14224
14225   return SDValue();
14226 }
14227
14228 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14229                                 SelectionDAG &DAG) {
14230   MVT VT = Op->getSimpleValueType(0);
14231   SDValue In = Op->getOperand(0);
14232   MVT InVT = In.getSimpleValueType();
14233   SDLoc dl(Op);
14234
14235   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14236     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14237
14238   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14239       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14240       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14241     return SDValue();
14242
14243   if (Subtarget->hasInt256())
14244     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14245
14246   // Optimize vectors in AVX mode
14247   // Sign extend  v8i16 to v8i32 and
14248   //              v4i32 to v4i64
14249   //
14250   // Divide input vector into two parts
14251   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14252   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14253   // concat the vectors to original VT
14254
14255   unsigned NumElems = InVT.getVectorNumElements();
14256   SDValue Undef = DAG.getUNDEF(InVT);
14257
14258   SmallVector<int,8> ShufMask1(NumElems, -1);
14259   for (unsigned i = 0; i != NumElems/2; ++i)
14260     ShufMask1[i] = i;
14261
14262   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14263
14264   SmallVector<int,8> ShufMask2(NumElems, -1);
14265   for (unsigned i = 0; i != NumElems/2; ++i)
14266     ShufMask2[i] = i + NumElems/2;
14267
14268   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14269
14270   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14271                                 VT.getVectorNumElements()/2);
14272
14273   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14274   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14275
14276   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14277 }
14278
14279 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14280 // may emit an illegal shuffle but the expansion is still better than scalar
14281 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14282 // we'll emit a shuffle and a arithmetic shift.
14283 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14284 // TODO: It is possible to support ZExt by zeroing the undef values during
14285 // the shuffle phase or after the shuffle.
14286 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14287                                  SelectionDAG &DAG) {
14288   MVT RegVT = Op.getSimpleValueType();
14289   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14290   assert(RegVT.isInteger() &&
14291          "We only custom lower integer vector sext loads.");
14292
14293   // Nothing useful we can do without SSE2 shuffles.
14294   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14295
14296   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14297   SDLoc dl(Ld);
14298   EVT MemVT = Ld->getMemoryVT();
14299   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14300   unsigned RegSz = RegVT.getSizeInBits();
14301
14302   ISD::LoadExtType Ext = Ld->getExtensionType();
14303
14304   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14305          && "Only anyext and sext are currently implemented.");
14306   assert(MemVT != RegVT && "Cannot extend to the same type");
14307   assert(MemVT.isVector() && "Must load a vector from memory");
14308
14309   unsigned NumElems = RegVT.getVectorNumElements();
14310   unsigned MemSz = MemVT.getSizeInBits();
14311   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14312
14313   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14314     // The only way in which we have a legal 256-bit vector result but not the
14315     // integer 256-bit operations needed to directly lower a sextload is if we
14316     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14317     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14318     // correctly legalized. We do this late to allow the canonical form of
14319     // sextload to persist throughout the rest of the DAG combiner -- it wants
14320     // to fold together any extensions it can, and so will fuse a sign_extend
14321     // of an sextload into a sextload targeting a wider value.
14322     SDValue Load;
14323     if (MemSz == 128) {
14324       // Just switch this to a normal load.
14325       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14326                                        "it must be a legal 128-bit vector "
14327                                        "type!");
14328       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14329                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14330                   Ld->isInvariant(), Ld->getAlignment());
14331     } else {
14332       assert(MemSz < 128 &&
14333              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14334       // Do an sext load to a 128-bit vector type. We want to use the same
14335       // number of elements, but elements half as wide. This will end up being
14336       // recursively lowered by this routine, but will succeed as we definitely
14337       // have all the necessary features if we're using AVX1.
14338       EVT HalfEltVT =
14339           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14340       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14341       Load =
14342           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14343                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14344                          Ld->isNonTemporal(), Ld->isInvariant(),
14345                          Ld->getAlignment());
14346     }
14347
14348     // Replace chain users with the new chain.
14349     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14350     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14351
14352     // Finally, do a normal sign-extend to the desired register.
14353     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14354   }
14355
14356   // All sizes must be a power of two.
14357   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14358          "Non-power-of-two elements are not custom lowered!");
14359
14360   // Attempt to load the original value using scalar loads.
14361   // Find the largest scalar type that divides the total loaded size.
14362   MVT SclrLoadTy = MVT::i8;
14363   for (MVT Tp : MVT::integer_valuetypes()) {
14364     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14365       SclrLoadTy = Tp;
14366     }
14367   }
14368
14369   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14370   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14371       (64 <= MemSz))
14372     SclrLoadTy = MVT::f64;
14373
14374   // Calculate the number of scalar loads that we need to perform
14375   // in order to load our vector from memory.
14376   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14377
14378   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14379          "Can only lower sext loads with a single scalar load!");
14380
14381   unsigned loadRegZize = RegSz;
14382   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14383     loadRegZize = 128;
14384
14385   // Represent our vector as a sequence of elements which are the
14386   // largest scalar that we can load.
14387   EVT LoadUnitVecVT = EVT::getVectorVT(
14388       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14389
14390   // Represent the data using the same element type that is stored in
14391   // memory. In practice, we ''widen'' MemVT.
14392   EVT WideVecVT =
14393       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14394                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14395
14396   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14397          "Invalid vector type");
14398
14399   // We can't shuffle using an illegal type.
14400   assert(TLI.isTypeLegal(WideVecVT) &&
14401          "We only lower types that form legal widened vector types");
14402
14403   SmallVector<SDValue, 8> Chains;
14404   SDValue Ptr = Ld->getBasePtr();
14405   SDValue Increment =
14406       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14407   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14408
14409   for (unsigned i = 0; i < NumLoads; ++i) {
14410     // Perform a single load.
14411     SDValue ScalarLoad =
14412         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14413                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14414                     Ld->getAlignment());
14415     Chains.push_back(ScalarLoad.getValue(1));
14416     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14417     // another round of DAGCombining.
14418     if (i == 0)
14419       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14420     else
14421       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14422                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14423
14424     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14425   }
14426
14427   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14428
14429   // Bitcast the loaded value to a vector of the original element type, in
14430   // the size of the target vector type.
14431   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14432   unsigned SizeRatio = RegSz / MemSz;
14433
14434   if (Ext == ISD::SEXTLOAD) {
14435     // If we have SSE4.1, we can directly emit a VSEXT node.
14436     if (Subtarget->hasSSE41()) {
14437       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14438       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14439       return Sext;
14440     }
14441
14442     // Otherwise we'll shuffle the small elements in the high bits of the
14443     // larger type and perform an arithmetic shift. If the shift is not legal
14444     // it's better to scalarize.
14445     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14446            "We can't implement a sext load without an arithmetic right shift!");
14447
14448     // Redistribute the loaded elements into the different locations.
14449     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14450     for (unsigned i = 0; i != NumElems; ++i)
14451       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14452
14453     SDValue Shuff = DAG.getVectorShuffle(
14454         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14455
14456     Shuff = DAG.getBitcast(RegVT, Shuff);
14457
14458     // Build the arithmetic shift.
14459     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14460                    MemVT.getVectorElementType().getSizeInBits();
14461     Shuff =
14462         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14463                     DAG.getConstant(Amt, dl, RegVT));
14464
14465     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14466     return Shuff;
14467   }
14468
14469   // Redistribute the loaded elements into the different locations.
14470   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14471   for (unsigned i = 0; i != NumElems; ++i)
14472     ShuffleVec[i * SizeRatio] = i;
14473
14474   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14475                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14476
14477   // Bitcast to the requested type.
14478   Shuff = DAG.getBitcast(RegVT, Shuff);
14479   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14480   return Shuff;
14481 }
14482
14483 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14484 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14485 // from the AND / OR.
14486 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14487   Opc = Op.getOpcode();
14488   if (Opc != ISD::OR && Opc != ISD::AND)
14489     return false;
14490   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14491           Op.getOperand(0).hasOneUse() &&
14492           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14493           Op.getOperand(1).hasOneUse());
14494 }
14495
14496 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14497 // 1 and that the SETCC node has a single use.
14498 static bool isXor1OfSetCC(SDValue Op) {
14499   if (Op.getOpcode() != ISD::XOR)
14500     return false;
14501   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14502   if (N1C && N1C->getAPIntValue() == 1) {
14503     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14504       Op.getOperand(0).hasOneUse();
14505   }
14506   return false;
14507 }
14508
14509 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14510   bool addTest = true;
14511   SDValue Chain = Op.getOperand(0);
14512   SDValue Cond  = Op.getOperand(1);
14513   SDValue Dest  = Op.getOperand(2);
14514   SDLoc dl(Op);
14515   SDValue CC;
14516   bool Inverted = false;
14517
14518   if (Cond.getOpcode() == ISD::SETCC) {
14519     // Check for setcc([su]{add,sub,mul}o == 0).
14520     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14521         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14522         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14523         Cond.getOperand(0).getResNo() == 1 &&
14524         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14525          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14526          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14527          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14528          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14529          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14530       Inverted = true;
14531       Cond = Cond.getOperand(0);
14532     } else {
14533       SDValue NewCond = LowerSETCC(Cond, DAG);
14534       if (NewCond.getNode())
14535         Cond = NewCond;
14536     }
14537   }
14538 #if 0
14539   // FIXME: LowerXALUO doesn't handle these!!
14540   else if (Cond.getOpcode() == X86ISD::ADD  ||
14541            Cond.getOpcode() == X86ISD::SUB  ||
14542            Cond.getOpcode() == X86ISD::SMUL ||
14543            Cond.getOpcode() == X86ISD::UMUL)
14544     Cond = LowerXALUO(Cond, DAG);
14545 #endif
14546
14547   // Look pass (and (setcc_carry (cmp ...)), 1).
14548   if (Cond.getOpcode() == ISD::AND &&
14549       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14550     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14551     if (C && C->getAPIntValue() == 1)
14552       Cond = Cond.getOperand(0);
14553   }
14554
14555   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14556   // setting operand in place of the X86ISD::SETCC.
14557   unsigned CondOpcode = Cond.getOpcode();
14558   if (CondOpcode == X86ISD::SETCC ||
14559       CondOpcode == X86ISD::SETCC_CARRY) {
14560     CC = Cond.getOperand(0);
14561
14562     SDValue Cmp = Cond.getOperand(1);
14563     unsigned Opc = Cmp.getOpcode();
14564     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14565     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14566       Cond = Cmp;
14567       addTest = false;
14568     } else {
14569       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14570       default: break;
14571       case X86::COND_O:
14572       case X86::COND_B:
14573         // These can only come from an arithmetic instruction with overflow,
14574         // e.g. SADDO, UADDO.
14575         Cond = Cond.getNode()->getOperand(1);
14576         addTest = false;
14577         break;
14578       }
14579     }
14580   }
14581   CondOpcode = Cond.getOpcode();
14582   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14583       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14584       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14585        Cond.getOperand(0).getValueType() != MVT::i8)) {
14586     SDValue LHS = Cond.getOperand(0);
14587     SDValue RHS = Cond.getOperand(1);
14588     unsigned X86Opcode;
14589     unsigned X86Cond;
14590     SDVTList VTs;
14591     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14592     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14593     // X86ISD::INC).
14594     switch (CondOpcode) {
14595     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14596     case ISD::SADDO:
14597       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14598         if (C->isOne()) {
14599           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14600           break;
14601         }
14602       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14603     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14604     case ISD::SSUBO:
14605       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14606         if (C->isOne()) {
14607           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14608           break;
14609         }
14610       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14611     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14612     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14613     default: llvm_unreachable("unexpected overflowing operator");
14614     }
14615     if (Inverted)
14616       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14617     if (CondOpcode == ISD::UMULO)
14618       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14619                           MVT::i32);
14620     else
14621       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14622
14623     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14624
14625     if (CondOpcode == ISD::UMULO)
14626       Cond = X86Op.getValue(2);
14627     else
14628       Cond = X86Op.getValue(1);
14629
14630     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14631     addTest = false;
14632   } else {
14633     unsigned CondOpc;
14634     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14635       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14636       if (CondOpc == ISD::OR) {
14637         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14638         // two branches instead of an explicit OR instruction with a
14639         // separate test.
14640         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14641             isX86LogicalCmp(Cmp)) {
14642           CC = Cond.getOperand(0).getOperand(0);
14643           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14644                               Chain, Dest, CC, Cmp);
14645           CC = Cond.getOperand(1).getOperand(0);
14646           Cond = Cmp;
14647           addTest = false;
14648         }
14649       } else { // ISD::AND
14650         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14651         // two branches instead of an explicit AND instruction with a
14652         // separate test. However, we only do this if this block doesn't
14653         // have a fall-through edge, because this requires an explicit
14654         // jmp when the condition is false.
14655         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14656             isX86LogicalCmp(Cmp) &&
14657             Op.getNode()->hasOneUse()) {
14658           X86::CondCode CCode =
14659             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14660           CCode = X86::GetOppositeBranchCondition(CCode);
14661           CC = DAG.getConstant(CCode, dl, MVT::i8);
14662           SDNode *User = *Op.getNode()->use_begin();
14663           // Look for an unconditional branch following this conditional branch.
14664           // We need this because we need to reverse the successors in order
14665           // to implement FCMP_OEQ.
14666           if (User->getOpcode() == ISD::BR) {
14667             SDValue FalseBB = User->getOperand(1);
14668             SDNode *NewBR =
14669               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14670             assert(NewBR == User);
14671             (void)NewBR;
14672             Dest = FalseBB;
14673
14674             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14675                                 Chain, Dest, CC, Cmp);
14676             X86::CondCode CCode =
14677               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14678             CCode = X86::GetOppositeBranchCondition(CCode);
14679             CC = DAG.getConstant(CCode, dl, MVT::i8);
14680             Cond = Cmp;
14681             addTest = false;
14682           }
14683         }
14684       }
14685     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14686       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14687       // It should be transformed during dag combiner except when the condition
14688       // is set by a arithmetics with overflow node.
14689       X86::CondCode CCode =
14690         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14691       CCode = X86::GetOppositeBranchCondition(CCode);
14692       CC = DAG.getConstant(CCode, dl, MVT::i8);
14693       Cond = Cond.getOperand(0).getOperand(1);
14694       addTest = false;
14695     } else if (Cond.getOpcode() == ISD::SETCC &&
14696                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14697       // For FCMP_OEQ, we can emit
14698       // two branches instead of an explicit AND instruction with a
14699       // separate test. However, we only do this if this block doesn't
14700       // have a fall-through edge, because this requires an explicit
14701       // jmp when the condition is false.
14702       if (Op.getNode()->hasOneUse()) {
14703         SDNode *User = *Op.getNode()->use_begin();
14704         // Look for an unconditional branch following this conditional branch.
14705         // We need this because we need to reverse the successors in order
14706         // to implement FCMP_OEQ.
14707         if (User->getOpcode() == ISD::BR) {
14708           SDValue FalseBB = User->getOperand(1);
14709           SDNode *NewBR =
14710             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14711           assert(NewBR == User);
14712           (void)NewBR;
14713           Dest = FalseBB;
14714
14715           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14716                                     Cond.getOperand(0), Cond.getOperand(1));
14717           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14718           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14719           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14720                               Chain, Dest, CC, Cmp);
14721           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14722           Cond = Cmp;
14723           addTest = false;
14724         }
14725       }
14726     } else if (Cond.getOpcode() == ISD::SETCC &&
14727                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14728       // For FCMP_UNE, we can emit
14729       // two branches instead of an explicit AND instruction with a
14730       // separate test. However, we only do this if this block doesn't
14731       // have a fall-through edge, because this requires an explicit
14732       // jmp when the condition is false.
14733       if (Op.getNode()->hasOneUse()) {
14734         SDNode *User = *Op.getNode()->use_begin();
14735         // Look for an unconditional branch following this conditional branch.
14736         // We need this because we need to reverse the successors in order
14737         // to implement FCMP_UNE.
14738         if (User->getOpcode() == ISD::BR) {
14739           SDValue FalseBB = User->getOperand(1);
14740           SDNode *NewBR =
14741             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14742           assert(NewBR == User);
14743           (void)NewBR;
14744
14745           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14746                                     Cond.getOperand(0), Cond.getOperand(1));
14747           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14748           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14749           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14750                               Chain, Dest, CC, Cmp);
14751           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14752           Cond = Cmp;
14753           addTest = false;
14754           Dest = FalseBB;
14755         }
14756       }
14757     }
14758   }
14759
14760   if (addTest) {
14761     // Look pass the truncate if the high bits are known zero.
14762     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14763         Cond = Cond.getOperand(0);
14764
14765     // We know the result of AND is compared against zero. Try to match
14766     // it to BT.
14767     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14768       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14769       if (NewSetCC.getNode()) {
14770         CC = NewSetCC.getOperand(0);
14771         Cond = NewSetCC.getOperand(1);
14772         addTest = false;
14773       }
14774     }
14775   }
14776
14777   if (addTest) {
14778     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14779     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14780     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14781   }
14782   Cond = ConvertCmpIfNecessary(Cond, DAG);
14783   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14784                      Chain, Dest, CC, Cond);
14785 }
14786
14787 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14788 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14789 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14790 // that the guard pages used by the OS virtual memory manager are allocated in
14791 // correct sequence.
14792 SDValue
14793 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14794                                            SelectionDAG &DAG) const {
14795   MachineFunction &MF = DAG.getMachineFunction();
14796   bool SplitStack = MF.shouldSplitStack();
14797   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14798                SplitStack;
14799   SDLoc dl(Op);
14800
14801   if (!Lower) {
14802     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14803     SDNode* Node = Op.getNode();
14804
14805     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14806     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14807         " not tell us which reg is the stack pointer!");
14808     EVT VT = Node->getValueType(0);
14809     SDValue Tmp1 = SDValue(Node, 0);
14810     SDValue Tmp2 = SDValue(Node, 1);
14811     SDValue Tmp3 = Node->getOperand(2);
14812     SDValue Chain = Tmp1.getOperand(0);
14813
14814     // Chain the dynamic stack allocation so that it doesn't modify the stack
14815     // pointer when other instructions are using the stack.
14816     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14817         SDLoc(Node));
14818
14819     SDValue Size = Tmp2.getOperand(1);
14820     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14821     Chain = SP.getValue(1);
14822     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14823     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14824     unsigned StackAlign = TFI.getStackAlignment();
14825     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14826     if (Align > StackAlign)
14827       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14828           DAG.getConstant(-(uint64_t)Align, dl, VT));
14829     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14830
14831     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14832         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14833         SDLoc(Node));
14834
14835     SDValue Ops[2] = { Tmp1, Tmp2 };
14836     return DAG.getMergeValues(Ops, dl);
14837   }
14838
14839   // Get the inputs.
14840   SDValue Chain = Op.getOperand(0);
14841   SDValue Size  = Op.getOperand(1);
14842   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14843   EVT VT = Op.getNode()->getValueType(0);
14844
14845   bool Is64Bit = Subtarget->is64Bit();
14846   EVT SPTy = getPointerTy();
14847
14848   if (SplitStack) {
14849     MachineRegisterInfo &MRI = MF.getRegInfo();
14850
14851     if (Is64Bit) {
14852       // The 64 bit implementation of segmented stacks needs to clobber both r10
14853       // r11. This makes it impossible to use it along with nested parameters.
14854       const Function *F = MF.getFunction();
14855
14856       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14857            I != E; ++I)
14858         if (I->hasNestAttr())
14859           report_fatal_error("Cannot use segmented stacks with functions that "
14860                              "have nested arguments.");
14861     }
14862
14863     const TargetRegisterClass *AddrRegClass =
14864       getRegClassFor(getPointerTy());
14865     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14866     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14867     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14868                                 DAG.getRegister(Vreg, SPTy));
14869     SDValue Ops1[2] = { Value, Chain };
14870     return DAG.getMergeValues(Ops1, dl);
14871   } else {
14872     SDValue Flag;
14873     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14874
14875     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14876     Flag = Chain.getValue(1);
14877     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14878
14879     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14880
14881     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14882     unsigned SPReg = RegInfo->getStackRegister();
14883     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14884     Chain = SP.getValue(1);
14885
14886     if (Align) {
14887       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14888                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14889       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14890     }
14891
14892     SDValue Ops1[2] = { SP, Chain };
14893     return DAG.getMergeValues(Ops1, dl);
14894   }
14895 }
14896
14897 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14898   MachineFunction &MF = DAG.getMachineFunction();
14899   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14900
14901   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14902   SDLoc DL(Op);
14903
14904   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14905     // vastart just stores the address of the VarArgsFrameIndex slot into the
14906     // memory location argument.
14907     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14908                                    getPointerTy());
14909     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14910                         MachinePointerInfo(SV), false, false, 0);
14911   }
14912
14913   // __va_list_tag:
14914   //   gp_offset         (0 - 6 * 8)
14915   //   fp_offset         (48 - 48 + 8 * 16)
14916   //   overflow_arg_area (point to parameters coming in memory).
14917   //   reg_save_area
14918   SmallVector<SDValue, 8> MemOps;
14919   SDValue FIN = Op.getOperand(1);
14920   // Store gp_offset
14921   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14922                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14923                                                DL, MVT::i32),
14924                                FIN, MachinePointerInfo(SV), false, false, 0);
14925   MemOps.push_back(Store);
14926
14927   // Store fp_offset
14928   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14929                     FIN, DAG.getIntPtrConstant(4, DL));
14930   Store = DAG.getStore(Op.getOperand(0), DL,
14931                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14932                                        MVT::i32),
14933                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14934   MemOps.push_back(Store);
14935
14936   // Store ptr to overflow_arg_area
14937   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14938                     FIN, DAG.getIntPtrConstant(4, DL));
14939   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14940                                     getPointerTy());
14941   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14942                        MachinePointerInfo(SV, 8),
14943                        false, false, 0);
14944   MemOps.push_back(Store);
14945
14946   // Store ptr to reg_save_area.
14947   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14948                     FIN, DAG.getIntPtrConstant(8, DL));
14949   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14950                                     getPointerTy());
14951   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14952                        MachinePointerInfo(SV, 16), false, false, 0);
14953   MemOps.push_back(Store);
14954   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14955 }
14956
14957 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14958   assert(Subtarget->is64Bit() &&
14959          "LowerVAARG only handles 64-bit va_arg!");
14960   assert((Subtarget->isTargetLinux() ||
14961           Subtarget->isTargetDarwin()) &&
14962           "Unhandled target in LowerVAARG");
14963   assert(Op.getNode()->getNumOperands() == 4);
14964   SDValue Chain = Op.getOperand(0);
14965   SDValue SrcPtr = Op.getOperand(1);
14966   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14967   unsigned Align = Op.getConstantOperandVal(3);
14968   SDLoc dl(Op);
14969
14970   EVT ArgVT = Op.getNode()->getValueType(0);
14971   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14972   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14973   uint8_t ArgMode;
14974
14975   // Decide which area this value should be read from.
14976   // TODO: Implement the AMD64 ABI in its entirety. This simple
14977   // selection mechanism works only for the basic types.
14978   if (ArgVT == MVT::f80) {
14979     llvm_unreachable("va_arg for f80 not yet implemented");
14980   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14981     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14982   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14983     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14984   } else {
14985     llvm_unreachable("Unhandled argument type in LowerVAARG");
14986   }
14987
14988   if (ArgMode == 2) {
14989     // Sanity Check: Make sure using fp_offset makes sense.
14990     assert(!Subtarget->useSoftFloat() &&
14991            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14992                Attribute::NoImplicitFloat)) &&
14993            Subtarget->hasSSE1());
14994   }
14995
14996   // Insert VAARG_64 node into the DAG
14997   // VAARG_64 returns two values: Variable Argument Address, Chain
14998   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14999                        DAG.getConstant(ArgMode, dl, MVT::i8),
15000                        DAG.getConstant(Align, dl, MVT::i32)};
15001   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
15002   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15003                                           VTs, InstOps, MVT::i64,
15004                                           MachinePointerInfo(SV),
15005                                           /*Align=*/0,
15006                                           /*Volatile=*/false,
15007                                           /*ReadMem=*/true,
15008                                           /*WriteMem=*/true);
15009   Chain = VAARG.getValue(1);
15010
15011   // Load the next argument and return it
15012   return DAG.getLoad(ArgVT, dl,
15013                      Chain,
15014                      VAARG,
15015                      MachinePointerInfo(),
15016                      false, false, false, 0);
15017 }
15018
15019 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15020                            SelectionDAG &DAG) {
15021   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15022   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15023   SDValue Chain = Op.getOperand(0);
15024   SDValue DstPtr = Op.getOperand(1);
15025   SDValue SrcPtr = Op.getOperand(2);
15026   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15027   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15028   SDLoc DL(Op);
15029
15030   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15031                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15032                        false, false,
15033                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15034 }
15035
15036 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15037 // amount is a constant. Takes immediate version of shift as input.
15038 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15039                                           SDValue SrcOp, uint64_t ShiftAmt,
15040                                           SelectionDAG &DAG) {
15041   MVT ElementType = VT.getVectorElementType();
15042
15043   // Fold this packed shift into its first operand if ShiftAmt is 0.
15044   if (ShiftAmt == 0)
15045     return SrcOp;
15046
15047   // Check for ShiftAmt >= element width
15048   if (ShiftAmt >= ElementType.getSizeInBits()) {
15049     if (Opc == X86ISD::VSRAI)
15050       ShiftAmt = ElementType.getSizeInBits() - 1;
15051     else
15052       return DAG.getConstant(0, dl, VT);
15053   }
15054
15055   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15056          && "Unknown target vector shift-by-constant node");
15057
15058   // Fold this packed vector shift into a build vector if SrcOp is a
15059   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15060   if (VT == SrcOp.getSimpleValueType() &&
15061       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15062     SmallVector<SDValue, 8> Elts;
15063     unsigned NumElts = SrcOp->getNumOperands();
15064     ConstantSDNode *ND;
15065
15066     switch(Opc) {
15067     default: llvm_unreachable(nullptr);
15068     case X86ISD::VSHLI:
15069       for (unsigned i=0; i!=NumElts; ++i) {
15070         SDValue CurrentOp = SrcOp->getOperand(i);
15071         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15072           Elts.push_back(CurrentOp);
15073           continue;
15074         }
15075         ND = cast<ConstantSDNode>(CurrentOp);
15076         const APInt &C = ND->getAPIntValue();
15077         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15078       }
15079       break;
15080     case X86ISD::VSRLI:
15081       for (unsigned i=0; i!=NumElts; ++i) {
15082         SDValue CurrentOp = SrcOp->getOperand(i);
15083         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15084           Elts.push_back(CurrentOp);
15085           continue;
15086         }
15087         ND = cast<ConstantSDNode>(CurrentOp);
15088         const APInt &C = ND->getAPIntValue();
15089         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15090       }
15091       break;
15092     case X86ISD::VSRAI:
15093       for (unsigned i=0; i!=NumElts; ++i) {
15094         SDValue CurrentOp = SrcOp->getOperand(i);
15095         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15096           Elts.push_back(CurrentOp);
15097           continue;
15098         }
15099         ND = cast<ConstantSDNode>(CurrentOp);
15100         const APInt &C = ND->getAPIntValue();
15101         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15102       }
15103       break;
15104     }
15105
15106     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15107   }
15108
15109   return DAG.getNode(Opc, dl, VT, SrcOp,
15110                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15111 }
15112
15113 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15114 // may or may not be a constant. Takes immediate version of shift as input.
15115 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15116                                    SDValue SrcOp, SDValue ShAmt,
15117                                    SelectionDAG &DAG) {
15118   MVT SVT = ShAmt.getSimpleValueType();
15119   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15120
15121   // Catch shift-by-constant.
15122   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15123     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15124                                       CShAmt->getZExtValue(), DAG);
15125
15126   // Change opcode to non-immediate version
15127   switch (Opc) {
15128     default: llvm_unreachable("Unknown target vector shift node");
15129     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15130     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15131     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15132   }
15133
15134   const X86Subtarget &Subtarget =
15135       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15136   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15137       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15138     // Let the shuffle legalizer expand this shift amount node.
15139     SDValue Op0 = ShAmt.getOperand(0);
15140     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15141     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15142   } else {
15143     // Need to build a vector containing shift amount.
15144     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15145     SmallVector<SDValue, 4> ShOps;
15146     ShOps.push_back(ShAmt);
15147     if (SVT == MVT::i32) {
15148       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15149       ShOps.push_back(DAG.getUNDEF(SVT));
15150     }
15151     ShOps.push_back(DAG.getUNDEF(SVT));
15152
15153     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15154     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15155   }
15156
15157   // The return type has to be a 128-bit type with the same element
15158   // type as the input type.
15159   MVT EltVT = VT.getVectorElementType();
15160   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15161
15162   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15163   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15164 }
15165
15166 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15167 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15168 /// necessary casting for \p Mask when lowering masking intrinsics.
15169 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15170                                     SDValue PreservedSrc,
15171                                     const X86Subtarget *Subtarget,
15172                                     SelectionDAG &DAG) {
15173     EVT VT = Op.getValueType();
15174     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15175                                   MVT::i1, VT.getVectorNumElements());
15176     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15177                                      Mask.getValueType().getSizeInBits());
15178     SDLoc dl(Op);
15179
15180     assert(MaskVT.isSimple() && "invalid mask type");
15181
15182     if (isAllOnes(Mask))
15183       return Op;
15184
15185     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15186     // are extracted by EXTRACT_SUBVECTOR.
15187     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15188                                 DAG.getBitcast(BitcastVT, Mask),
15189                                 DAG.getIntPtrConstant(0, dl));
15190
15191     switch (Op.getOpcode()) {
15192       default: break;
15193       case X86ISD::PCMPEQM:
15194       case X86ISD::PCMPGTM:
15195       case X86ISD::CMPM:
15196       case X86ISD::CMPMU:
15197         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15198     }
15199     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15200       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15201     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15202 }
15203
15204 /// \brief Creates an SDNode for a predicated scalar operation.
15205 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15206 /// The mask is comming as MVT::i8 and it should be truncated
15207 /// to MVT::i1 while lowering masking intrinsics.
15208 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15209 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15210 /// a scalar instruction.
15211 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15212                                     SDValue PreservedSrc,
15213                                     const X86Subtarget *Subtarget,
15214                                     SelectionDAG &DAG) {
15215     if (isAllOnes(Mask))
15216       return Op;
15217
15218     EVT VT = Op.getValueType();
15219     SDLoc dl(Op);
15220     // The mask should be of type MVT::i1
15221     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15222
15223     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15224       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15225     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15226 }
15227
15228 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15229 /// function or when returning to a parent frame after catching an exception, we
15230 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15231 /// Here's the math:
15232 ///   RegNodeBase = EntryEBP - RegNodeSize
15233 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15234 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15235 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15236 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15237                                    SDValue EntryEBP) {
15238   MachineFunction &MF = DAG.getMachineFunction();
15239   SDLoc dl;
15240
15241   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15242   MVT PtrVT = TLI.getPointerTy();
15243
15244   // It's possible that the parent function no longer has a personality function
15245   // if the exceptional code was optimized away, in which case we just return
15246   // the incoming EBP.
15247   if (!Fn->hasPersonalityFn())
15248     return EntryEBP;
15249
15250   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15251   // WinEHStatePass for the full struct definition.
15252   int RegNodeSize;
15253   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15254   default:
15255     report_fatal_error("can only recover FP for MSVC EH personality functions");
15256   case EHPersonality::MSVC_X86SEH: RegNodeSize = 24; break;
15257   case EHPersonality::MSVC_CXX: RegNodeSize = 16; break;
15258   }
15259
15260   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15261   // registration.
15262   MCSymbol *OffsetSym =
15263       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15264           GlobalValue::getRealLinkageName(Fn->getName()));
15265   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15266   SDValue RegNodeFrameOffset =
15267       DAG.getNode(ISD::FRAME_ALLOC_RECOVER, dl, PtrVT, OffsetSymVal);
15268
15269   // RegNodeBase = EntryEBP - RegNodeSize
15270   // ParentFP = RegNodeBase - RegNodeFrameOffset
15271   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15272                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15273   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15274 }
15275
15276 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15277                                        SelectionDAG &DAG) {
15278   SDLoc dl(Op);
15279   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15280   EVT VT = Op.getValueType();
15281   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15282   if (IntrData) {
15283     switch(IntrData->Type) {
15284     case INTR_TYPE_1OP:
15285       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15286     case INTR_TYPE_2OP:
15287       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15288         Op.getOperand(2));
15289     case INTR_TYPE_3OP:
15290       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15291         Op.getOperand(2), Op.getOperand(3));
15292     case INTR_TYPE_4OP:
15293       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15294         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15295     case INTR_TYPE_1OP_MASK_RM: {
15296       SDValue Src = Op.getOperand(1);
15297       SDValue PassThru = Op.getOperand(2);
15298       SDValue Mask = Op.getOperand(3);
15299       SDValue RoundingMode;
15300       if (Op.getNumOperands() == 4)
15301         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15302       else
15303         RoundingMode = Op.getOperand(4);
15304       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15305       if (IntrWithRoundingModeOpcode != 0) {
15306         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15307         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15308           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15309                                       dl, Op.getValueType(), Src, RoundingMode),
15310                                       Mask, PassThru, Subtarget, DAG);
15311       }
15312       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15313                                               RoundingMode),
15314                                   Mask, PassThru, Subtarget, DAG);
15315     }
15316     case INTR_TYPE_1OP_MASK: {
15317       SDValue Src = Op.getOperand(1);
15318       SDValue Passthru = Op.getOperand(2);
15319       SDValue Mask = Op.getOperand(3);
15320       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15321                                   Mask, Passthru, Subtarget, DAG);
15322     }
15323     case INTR_TYPE_SCALAR_MASK_RM: {
15324       SDValue Src1 = Op.getOperand(1);
15325       SDValue Src2 = Op.getOperand(2);
15326       SDValue Src0 = Op.getOperand(3);
15327       SDValue Mask = Op.getOperand(4);
15328       // There are 2 kinds of intrinsics in this group:
15329       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15330       // (2) With rounding mode and sae - 7 operands.
15331       if (Op.getNumOperands() == 6) {
15332         SDValue Sae  = Op.getOperand(5);
15333         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15334         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15335                                                 Sae),
15336                                     Mask, Src0, Subtarget, DAG);
15337       }
15338       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15339       SDValue RoundingMode  = Op.getOperand(5);
15340       SDValue Sae  = Op.getOperand(6);
15341       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15342                                               RoundingMode, Sae),
15343                                   Mask, Src0, Subtarget, DAG);
15344     }
15345     case INTR_TYPE_2OP_MASK: {
15346       SDValue Src1 = Op.getOperand(1);
15347       SDValue Src2 = Op.getOperand(2);
15348       SDValue PassThru = Op.getOperand(3);
15349       SDValue Mask = Op.getOperand(4);
15350       // We specify 2 possible opcodes for intrinsics with rounding modes.
15351       // First, we check if the intrinsic may have non-default rounding mode,
15352       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15353       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15354       if (IntrWithRoundingModeOpcode != 0) {
15355         SDValue Rnd = Op.getOperand(5);
15356         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15357         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15358           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15359                                       dl, Op.getValueType(),
15360                                       Src1, Src2, Rnd),
15361                                       Mask, PassThru, Subtarget, DAG);
15362         }
15363       }
15364       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15365                                               Src1,Src2),
15366                                   Mask, PassThru, Subtarget, DAG);
15367     }
15368     case INTR_TYPE_2OP_MASK_RM: {
15369       SDValue Src1 = Op.getOperand(1);
15370       SDValue Src2 = Op.getOperand(2);
15371       SDValue PassThru = Op.getOperand(3);
15372       SDValue Mask = Op.getOperand(4);
15373       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15374       // First, we check if the intrinsic have rounding mode (6 operands),
15375       // if not, we set rounding mode to "current".
15376       SDValue Rnd;
15377       if (Op.getNumOperands() == 6)
15378         Rnd = Op.getOperand(5);
15379       else 
15380         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15381       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15382                                               Src1, Src2, Rnd),
15383                                   Mask, PassThru, Subtarget, DAG);
15384     }
15385     case INTR_TYPE_3OP_MASK: {
15386       SDValue Src1 = Op.getOperand(1);
15387       SDValue Src2 = Op.getOperand(2);
15388       SDValue Src3 = Op.getOperand(3);
15389       SDValue PassThru = Op.getOperand(4);
15390       SDValue Mask = Op.getOperand(5);
15391       // We specify 2 possible opcodes for intrinsics with rounding modes.
15392       // First, we check if the intrinsic may have non-default rounding mode,
15393       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15394       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15395       if (IntrWithRoundingModeOpcode != 0) {
15396         SDValue Rnd = Op.getOperand(6);
15397         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15398         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15399           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15400                                       dl, Op.getValueType(),
15401                                       Src1, Src2, Src3, Rnd),
15402                                       Mask, PassThru, Subtarget, DAG);
15403         }
15404       }
15405       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15406                                               Src1, Src2, Src3),
15407                                   Mask, PassThru, Subtarget, DAG);
15408     }
15409     case VPERM_3OP_MASKZ: 
15410     case VPERM_3OP_MASK:
15411     case FMA_OP_MASK3:
15412     case FMA_OP_MASKZ:
15413     case FMA_OP_MASK: {
15414       SDValue Src1 = Op.getOperand(1);
15415       SDValue Src2 = Op.getOperand(2);
15416       SDValue Src3 = Op.getOperand(3);
15417       SDValue Mask = Op.getOperand(4);
15418       EVT VT = Op.getValueType();
15419       SDValue PassThru = SDValue();
15420
15421       // set PassThru element
15422       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15423         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15424       else if (IntrData->Type == FMA_OP_MASK3)
15425         PassThru = Src3;
15426       else
15427         PassThru = Src1;
15428
15429       // We specify 2 possible opcodes for intrinsics with rounding modes.
15430       // First, we check if the intrinsic may have non-default rounding mode,
15431       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15432       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15433       if (IntrWithRoundingModeOpcode != 0) {
15434         SDValue Rnd = Op.getOperand(5);
15435         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15436             X86::STATIC_ROUNDING::CUR_DIRECTION)
15437           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15438                                                   dl, Op.getValueType(),
15439                                                   Src1, Src2, Src3, Rnd),
15440                                       Mask, PassThru, Subtarget, DAG);
15441       }
15442       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15443                                               dl, Op.getValueType(),
15444                                               Src1, Src2, Src3),
15445                                   Mask, PassThru, Subtarget, DAG);
15446     }
15447     case CMP_MASK:
15448     case CMP_MASK_CC: {
15449       // Comparison intrinsics with masks.
15450       // Example of transformation:
15451       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15452       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15453       // (i8 (bitcast
15454       //   (v8i1 (insert_subvector undef,
15455       //           (v2i1 (and (PCMPEQM %a, %b),
15456       //                      (extract_subvector
15457       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15458       EVT VT = Op.getOperand(1).getValueType();
15459       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15460                                     VT.getVectorNumElements());
15461       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15462       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15463                                        Mask.getValueType().getSizeInBits());
15464       SDValue Cmp;
15465       if (IntrData->Type == CMP_MASK_CC) {
15466         SDValue CC = Op.getOperand(3);
15467         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15468         // We specify 2 possible opcodes for intrinsics with rounding modes.
15469         // First, we check if the intrinsic may have non-default rounding mode,
15470         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15471         if (IntrData->Opc1 != 0) {
15472           SDValue Rnd = Op.getOperand(5);
15473           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15474               X86::STATIC_ROUNDING::CUR_DIRECTION)
15475             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15476                               Op.getOperand(2), CC, Rnd);
15477         }
15478         //default rounding mode
15479         if(!Cmp.getNode())
15480             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15481                               Op.getOperand(2), CC);
15482
15483       } else {
15484         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15485         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15486                           Op.getOperand(2));
15487       }
15488       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15489                                              DAG.getTargetConstant(0, dl,
15490                                                                    MaskVT),
15491                                              Subtarget, DAG);
15492       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15493                                 DAG.getUNDEF(BitcastVT), CmpMask,
15494                                 DAG.getIntPtrConstant(0, dl));
15495       return DAG.getBitcast(Op.getValueType(), Res);
15496     }
15497     case COMI: { // Comparison intrinsics
15498       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15499       SDValue LHS = Op.getOperand(1);
15500       SDValue RHS = Op.getOperand(2);
15501       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15502       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15503       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15504       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15505                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15506       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15507     }
15508     case VSHIFT:
15509       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15510                                  Op.getOperand(1), Op.getOperand(2), DAG);
15511     case VSHIFT_MASK:
15512       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15513                                                       Op.getSimpleValueType(),
15514                                                       Op.getOperand(1),
15515                                                       Op.getOperand(2), DAG),
15516                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15517                                   DAG);
15518     case COMPRESS_EXPAND_IN_REG: {
15519       SDValue Mask = Op.getOperand(3);
15520       SDValue DataToCompress = Op.getOperand(1);
15521       SDValue PassThru = Op.getOperand(2);
15522       if (isAllOnes(Mask)) // return data as is
15523         return Op.getOperand(1);
15524
15525       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15526                                               DataToCompress),
15527                                   Mask, PassThru, Subtarget, DAG);
15528     }
15529     case BLEND: {
15530       SDValue Mask = Op.getOperand(3);
15531       EVT VT = Op.getValueType();
15532       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15533                                     VT.getVectorNumElements());
15534       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15535                                        Mask.getValueType().getSizeInBits());
15536       SDLoc dl(Op);
15537       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15538                                   DAG.getBitcast(BitcastVT, Mask),
15539                                   DAG.getIntPtrConstant(0, dl));
15540       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15541                          Op.getOperand(2));
15542     }
15543     default:
15544       break;
15545     }
15546   }
15547
15548   switch (IntNo) {
15549   default: return SDValue();    // Don't custom lower most intrinsics.
15550
15551   case Intrinsic::x86_avx2_permd:
15552   case Intrinsic::x86_avx2_permps:
15553     // Operands intentionally swapped. Mask is last operand to intrinsic,
15554     // but second operand for node/instruction.
15555     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15556                        Op.getOperand(2), Op.getOperand(1));
15557
15558   // ptest and testp intrinsics. The intrinsic these come from are designed to
15559   // return an integer value, not just an instruction so lower it to the ptest
15560   // or testp pattern and a setcc for the result.
15561   case Intrinsic::x86_sse41_ptestz:
15562   case Intrinsic::x86_sse41_ptestc:
15563   case Intrinsic::x86_sse41_ptestnzc:
15564   case Intrinsic::x86_avx_ptestz_256:
15565   case Intrinsic::x86_avx_ptestc_256:
15566   case Intrinsic::x86_avx_ptestnzc_256:
15567   case Intrinsic::x86_avx_vtestz_ps:
15568   case Intrinsic::x86_avx_vtestc_ps:
15569   case Intrinsic::x86_avx_vtestnzc_ps:
15570   case Intrinsic::x86_avx_vtestz_pd:
15571   case Intrinsic::x86_avx_vtestc_pd:
15572   case Intrinsic::x86_avx_vtestnzc_pd:
15573   case Intrinsic::x86_avx_vtestz_ps_256:
15574   case Intrinsic::x86_avx_vtestc_ps_256:
15575   case Intrinsic::x86_avx_vtestnzc_ps_256:
15576   case Intrinsic::x86_avx_vtestz_pd_256:
15577   case Intrinsic::x86_avx_vtestc_pd_256:
15578   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15579     bool IsTestPacked = false;
15580     unsigned X86CC;
15581     switch (IntNo) {
15582     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15583     case Intrinsic::x86_avx_vtestz_ps:
15584     case Intrinsic::x86_avx_vtestz_pd:
15585     case Intrinsic::x86_avx_vtestz_ps_256:
15586     case Intrinsic::x86_avx_vtestz_pd_256:
15587       IsTestPacked = true; // Fallthrough
15588     case Intrinsic::x86_sse41_ptestz:
15589     case Intrinsic::x86_avx_ptestz_256:
15590       // ZF = 1
15591       X86CC = X86::COND_E;
15592       break;
15593     case Intrinsic::x86_avx_vtestc_ps:
15594     case Intrinsic::x86_avx_vtestc_pd:
15595     case Intrinsic::x86_avx_vtestc_ps_256:
15596     case Intrinsic::x86_avx_vtestc_pd_256:
15597       IsTestPacked = true; // Fallthrough
15598     case Intrinsic::x86_sse41_ptestc:
15599     case Intrinsic::x86_avx_ptestc_256:
15600       // CF = 1
15601       X86CC = X86::COND_B;
15602       break;
15603     case Intrinsic::x86_avx_vtestnzc_ps:
15604     case Intrinsic::x86_avx_vtestnzc_pd:
15605     case Intrinsic::x86_avx_vtestnzc_ps_256:
15606     case Intrinsic::x86_avx_vtestnzc_pd_256:
15607       IsTestPacked = true; // Fallthrough
15608     case Intrinsic::x86_sse41_ptestnzc:
15609     case Intrinsic::x86_avx_ptestnzc_256:
15610       // ZF and CF = 0
15611       X86CC = X86::COND_A;
15612       break;
15613     }
15614
15615     SDValue LHS = Op.getOperand(1);
15616     SDValue RHS = Op.getOperand(2);
15617     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15618     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15619     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15620     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15621     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15622   }
15623   case Intrinsic::x86_avx512_kortestz_w:
15624   case Intrinsic::x86_avx512_kortestc_w: {
15625     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15626     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15627     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15628     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15629     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15630     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15631     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15632   }
15633
15634   case Intrinsic::x86_sse42_pcmpistria128:
15635   case Intrinsic::x86_sse42_pcmpestria128:
15636   case Intrinsic::x86_sse42_pcmpistric128:
15637   case Intrinsic::x86_sse42_pcmpestric128:
15638   case Intrinsic::x86_sse42_pcmpistrio128:
15639   case Intrinsic::x86_sse42_pcmpestrio128:
15640   case Intrinsic::x86_sse42_pcmpistris128:
15641   case Intrinsic::x86_sse42_pcmpestris128:
15642   case Intrinsic::x86_sse42_pcmpistriz128:
15643   case Intrinsic::x86_sse42_pcmpestriz128: {
15644     unsigned Opcode;
15645     unsigned X86CC;
15646     switch (IntNo) {
15647     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15648     case Intrinsic::x86_sse42_pcmpistria128:
15649       Opcode = X86ISD::PCMPISTRI;
15650       X86CC = X86::COND_A;
15651       break;
15652     case Intrinsic::x86_sse42_pcmpestria128:
15653       Opcode = X86ISD::PCMPESTRI;
15654       X86CC = X86::COND_A;
15655       break;
15656     case Intrinsic::x86_sse42_pcmpistric128:
15657       Opcode = X86ISD::PCMPISTRI;
15658       X86CC = X86::COND_B;
15659       break;
15660     case Intrinsic::x86_sse42_pcmpestric128:
15661       Opcode = X86ISD::PCMPESTRI;
15662       X86CC = X86::COND_B;
15663       break;
15664     case Intrinsic::x86_sse42_pcmpistrio128:
15665       Opcode = X86ISD::PCMPISTRI;
15666       X86CC = X86::COND_O;
15667       break;
15668     case Intrinsic::x86_sse42_pcmpestrio128:
15669       Opcode = X86ISD::PCMPESTRI;
15670       X86CC = X86::COND_O;
15671       break;
15672     case Intrinsic::x86_sse42_pcmpistris128:
15673       Opcode = X86ISD::PCMPISTRI;
15674       X86CC = X86::COND_S;
15675       break;
15676     case Intrinsic::x86_sse42_pcmpestris128:
15677       Opcode = X86ISD::PCMPESTRI;
15678       X86CC = X86::COND_S;
15679       break;
15680     case Intrinsic::x86_sse42_pcmpistriz128:
15681       Opcode = X86ISD::PCMPISTRI;
15682       X86CC = X86::COND_E;
15683       break;
15684     case Intrinsic::x86_sse42_pcmpestriz128:
15685       Opcode = X86ISD::PCMPESTRI;
15686       X86CC = X86::COND_E;
15687       break;
15688     }
15689     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15690     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15691     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15692     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15693                                 DAG.getConstant(X86CC, dl, MVT::i8),
15694                                 SDValue(PCMP.getNode(), 1));
15695     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15696   }
15697
15698   case Intrinsic::x86_sse42_pcmpistri128:
15699   case Intrinsic::x86_sse42_pcmpestri128: {
15700     unsigned Opcode;
15701     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15702       Opcode = X86ISD::PCMPISTRI;
15703     else
15704       Opcode = X86ISD::PCMPESTRI;
15705
15706     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15707     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15708     return DAG.getNode(Opcode, dl, VTs, NewOps);
15709   }
15710
15711   case Intrinsic::x86_seh_lsda: {
15712     // Compute the symbol for the LSDA. We know it'll get emitted later.
15713     MachineFunction &MF = DAG.getMachineFunction();
15714     SDValue Op1 = Op.getOperand(1);
15715     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15716     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15717         GlobalValue::getRealLinkageName(Fn->getName()));
15718
15719     // Generate a simple absolute symbol reference. This intrinsic is only
15720     // supported on 32-bit Windows, which isn't PIC.
15721     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15722     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15723   }
15724
15725   case Intrinsic::x86_seh_recoverfp: {
15726     SDValue FnOp = Op.getOperand(1);
15727     SDValue IncomingFPOp = Op.getOperand(2);
15728     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15729     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15730     if (!Fn)
15731       report_fatal_error(
15732           "llvm.x86.seh.recoverfp must take a function as the first argument");
15733     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15734   }
15735   }
15736 }
15737
15738 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15739                               SDValue Src, SDValue Mask, SDValue Base,
15740                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15741                               const X86Subtarget * Subtarget) {
15742   SDLoc dl(Op);
15743   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15744   if (!C)
15745     llvm_unreachable("Invalid scale type");
15746   unsigned ScaleVal = C->getZExtValue();
15747   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15748     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15749
15750   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15751   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15752                              Index.getSimpleValueType().getVectorNumElements());
15753   SDValue MaskInReg;
15754   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15755   if (MaskC)
15756     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15757   else {
15758     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15759                                      Mask.getValueType().getSizeInBits());
15760
15761     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15762     // are extracted by EXTRACT_SUBVECTOR.
15763     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15764                             DAG.getBitcast(BitcastVT, Mask),
15765                             DAG.getIntPtrConstant(0, dl));
15766   }
15767   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15768   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15769   SDValue Segment = DAG.getRegister(0, MVT::i32);
15770   if (Src.getOpcode() == ISD::UNDEF)
15771     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15772   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15773   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15774   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15775   return DAG.getMergeValues(RetOps, dl);
15776 }
15777
15778 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15779                                SDValue Src, SDValue Mask, SDValue Base,
15780                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15781   SDLoc dl(Op);
15782   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15783   if (!C)
15784     llvm_unreachable("Invalid scale type");
15785   unsigned ScaleVal = C->getZExtValue();
15786   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15787     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15788
15789   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15790   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15791   SDValue Segment = DAG.getRegister(0, MVT::i32);
15792   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15793                              Index.getSimpleValueType().getVectorNumElements());
15794   SDValue MaskInReg;
15795   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15796   if (MaskC)
15797     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15798   else {
15799     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15800                                      Mask.getValueType().getSizeInBits());
15801
15802     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15803     // are extracted by EXTRACT_SUBVECTOR.
15804     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15805                             DAG.getBitcast(BitcastVT, Mask),
15806                             DAG.getIntPtrConstant(0, dl));
15807   }
15808   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15809   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15810   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15811   return SDValue(Res, 1);
15812 }
15813
15814 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15815                                SDValue Mask, SDValue Base, SDValue Index,
15816                                SDValue ScaleOp, SDValue Chain) {
15817   SDLoc dl(Op);
15818   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15819   assert(C && "Invalid scale type");
15820   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15821   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15822   SDValue Segment = DAG.getRegister(0, MVT::i32);
15823   EVT MaskVT =
15824     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15825   SDValue MaskInReg;
15826   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15827   if (MaskC)
15828     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15829   else
15830     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15831   //SDVTList VTs = DAG.getVTList(MVT::Other);
15832   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15833   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15834   return SDValue(Res, 0);
15835 }
15836
15837 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15838 // read performance monitor counters (x86_rdpmc).
15839 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15840                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15841                               SmallVectorImpl<SDValue> &Results) {
15842   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15843   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15844   SDValue LO, HI;
15845
15846   // The ECX register is used to select the index of the performance counter
15847   // to read.
15848   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15849                                    N->getOperand(2));
15850   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15851
15852   // Reads the content of a 64-bit performance counter and returns it in the
15853   // registers EDX:EAX.
15854   if (Subtarget->is64Bit()) {
15855     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15856     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15857                             LO.getValue(2));
15858   } else {
15859     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15860     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15861                             LO.getValue(2));
15862   }
15863   Chain = HI.getValue(1);
15864
15865   if (Subtarget->is64Bit()) {
15866     // The EAX register is loaded with the low-order 32 bits. The EDX register
15867     // is loaded with the supported high-order bits of the counter.
15868     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15869                               DAG.getConstant(32, DL, MVT::i8));
15870     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15871     Results.push_back(Chain);
15872     return;
15873   }
15874
15875   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15876   SDValue Ops[] = { LO, HI };
15877   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15878   Results.push_back(Pair);
15879   Results.push_back(Chain);
15880 }
15881
15882 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15883 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15884 // also used to custom lower READCYCLECOUNTER nodes.
15885 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15886                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15887                               SmallVectorImpl<SDValue> &Results) {
15888   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15889   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15890   SDValue LO, HI;
15891
15892   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15893   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15894   // and the EAX register is loaded with the low-order 32 bits.
15895   if (Subtarget->is64Bit()) {
15896     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15897     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15898                             LO.getValue(2));
15899   } else {
15900     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15901     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15902                             LO.getValue(2));
15903   }
15904   SDValue Chain = HI.getValue(1);
15905
15906   if (Opcode == X86ISD::RDTSCP_DAG) {
15907     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15908
15909     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15910     // the ECX register. Add 'ecx' explicitly to the chain.
15911     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15912                                      HI.getValue(2));
15913     // Explicitly store the content of ECX at the location passed in input
15914     // to the 'rdtscp' intrinsic.
15915     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15916                          MachinePointerInfo(), false, false, 0);
15917   }
15918
15919   if (Subtarget->is64Bit()) {
15920     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15921     // the EAX register is loaded with the low-order 32 bits.
15922     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15923                               DAG.getConstant(32, DL, MVT::i8));
15924     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15925     Results.push_back(Chain);
15926     return;
15927   }
15928
15929   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15930   SDValue Ops[] = { LO, HI };
15931   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15932   Results.push_back(Pair);
15933   Results.push_back(Chain);
15934 }
15935
15936 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15937                                      SelectionDAG &DAG) {
15938   SmallVector<SDValue, 2> Results;
15939   SDLoc DL(Op);
15940   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15941                           Results);
15942   return DAG.getMergeValues(Results, DL);
15943 }
15944
15945 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15946                                     SelectionDAG &DAG) {
15947   MachineFunction &MF = DAG.getMachineFunction();
15948   SDLoc dl(Op);
15949   SDValue Chain = Op.getOperand(0);
15950
15951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15952   MVT VT = TLI.getPointerTy();
15953
15954   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15955   unsigned FrameReg =
15956       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15957   unsigned SPReg = RegInfo->getStackRegister();
15958
15959   // Get incoming EBP.
15960   SDValue IncomingEBP =
15961       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
15962
15963   // Load [EBP-24] into SP.
15964   SDValue SPAddr =
15965       DAG.getNode(ISD::ADD, dl, VT, IncomingEBP, DAG.getConstant(-24, dl, VT));
15966   SDValue NewSP =
15967       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
15968                   false, VT.getScalarSizeInBits() / 8);
15969   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
15970
15971   // FIXME: Restore the base pointer in case of stack realignment!
15972
15973   // Adjust EBP to point back to the original frame position.
15974   SDValue NewFP = recoverFramePointer(DAG, MF.getFunction(), IncomingEBP);
15975   Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
15976   return Chain;
15977 }
15978
15979 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15980                                       SelectionDAG &DAG) {
15981   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15982
15983   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15984   if (!IntrData) {
15985     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
15986       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
15987     return SDValue();
15988   }
15989
15990   SDLoc dl(Op);
15991   switch(IntrData->Type) {
15992   default:
15993     llvm_unreachable("Unknown Intrinsic Type");
15994     break;
15995   case RDSEED:
15996   case RDRAND: {
15997     // Emit the node with the right value type.
15998     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15999     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16000
16001     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16002     // Otherwise return the value from Rand, which is always 0, casted to i32.
16003     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16004                       DAG.getConstant(1, dl, Op->getValueType(1)),
16005                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16006                       SDValue(Result.getNode(), 1) };
16007     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16008                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16009                                   Ops);
16010
16011     // Return { result, isValid, chain }.
16012     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16013                        SDValue(Result.getNode(), 2));
16014   }
16015   case GATHER: {
16016   //gather(v1, mask, index, base, scale);
16017     SDValue Chain = Op.getOperand(0);
16018     SDValue Src   = Op.getOperand(2);
16019     SDValue Base  = Op.getOperand(3);
16020     SDValue Index = Op.getOperand(4);
16021     SDValue Mask  = Op.getOperand(5);
16022     SDValue Scale = Op.getOperand(6);
16023     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16024                          Chain, Subtarget);
16025   }
16026   case SCATTER: {
16027   //scatter(base, mask, index, v1, scale);
16028     SDValue Chain = Op.getOperand(0);
16029     SDValue Base  = Op.getOperand(2);
16030     SDValue Mask  = Op.getOperand(3);
16031     SDValue Index = Op.getOperand(4);
16032     SDValue Src   = Op.getOperand(5);
16033     SDValue Scale = Op.getOperand(6);
16034     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16035                           Scale, Chain);
16036   }
16037   case PREFETCH: {
16038     SDValue Hint = Op.getOperand(6);
16039     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16040     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16041     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16042     SDValue Chain = Op.getOperand(0);
16043     SDValue Mask  = Op.getOperand(2);
16044     SDValue Index = Op.getOperand(3);
16045     SDValue Base  = Op.getOperand(4);
16046     SDValue Scale = Op.getOperand(5);
16047     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16048   }
16049   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16050   case RDTSC: {
16051     SmallVector<SDValue, 2> Results;
16052     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16053                             Results);
16054     return DAG.getMergeValues(Results, dl);
16055   }
16056   // Read Performance Monitoring Counters.
16057   case RDPMC: {
16058     SmallVector<SDValue, 2> Results;
16059     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16060     return DAG.getMergeValues(Results, dl);
16061   }
16062   // XTEST intrinsics.
16063   case XTEST: {
16064     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16065     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16066     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16067                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16068                                 InTrans);
16069     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16070     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16071                        Ret, SDValue(InTrans.getNode(), 1));
16072   }
16073   // ADC/ADCX/SBB
16074   case ADX: {
16075     SmallVector<SDValue, 2> Results;
16076     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16077     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16078     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16079                                 DAG.getConstant(-1, dl, MVT::i8));
16080     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16081                               Op.getOperand(4), GenCF.getValue(1));
16082     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16083                                  Op.getOperand(5), MachinePointerInfo(),
16084                                  false, false, 0);
16085     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16086                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16087                                 Res.getValue(1));
16088     Results.push_back(SetCC);
16089     Results.push_back(Store);
16090     return DAG.getMergeValues(Results, dl);
16091   }
16092   case COMPRESS_TO_MEM: {
16093     SDLoc dl(Op);
16094     SDValue Mask = Op.getOperand(4);
16095     SDValue DataToCompress = Op.getOperand(3);
16096     SDValue Addr = Op.getOperand(2);
16097     SDValue Chain = Op.getOperand(0);
16098
16099     EVT VT = DataToCompress.getValueType();
16100     if (isAllOnes(Mask)) // return just a store
16101       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16102                           MachinePointerInfo(), false, false,
16103                           VT.getScalarSizeInBits()/8);
16104
16105     SDValue Compressed =
16106       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16107                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16108     return DAG.getStore(Chain, dl, Compressed, Addr,
16109                         MachinePointerInfo(), false, false,
16110                         VT.getScalarSizeInBits()/8);
16111   }
16112   case EXPAND_FROM_MEM: {
16113     SDLoc dl(Op);
16114     SDValue Mask = Op.getOperand(4);
16115     SDValue PassThru = Op.getOperand(3);
16116     SDValue Addr = Op.getOperand(2);
16117     SDValue Chain = Op.getOperand(0);
16118     EVT VT = Op.getValueType();
16119
16120     if (isAllOnes(Mask)) // return just a load
16121       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16122                          false, VT.getScalarSizeInBits()/8);
16123
16124     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16125                                        false, false, false,
16126                                        VT.getScalarSizeInBits()/8);
16127
16128     SDValue Results[] = {
16129       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16130                            Mask, PassThru, Subtarget, DAG), Chain};
16131     return DAG.getMergeValues(Results, dl);
16132   }
16133   }
16134 }
16135
16136 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16137                                            SelectionDAG &DAG) const {
16138   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16139   MFI->setReturnAddressIsTaken(true);
16140
16141   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16142     return SDValue();
16143
16144   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16145   SDLoc dl(Op);
16146   EVT PtrVT = getPointerTy();
16147
16148   if (Depth > 0) {
16149     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16150     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16151     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16152     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16153                        DAG.getNode(ISD::ADD, dl, PtrVT,
16154                                    FrameAddr, Offset),
16155                        MachinePointerInfo(), false, false, false, 0);
16156   }
16157
16158   // Just load the return address.
16159   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16160   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16161                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16162 }
16163
16164 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16165   MachineFunction &MF = DAG.getMachineFunction();
16166   MachineFrameInfo *MFI = MF.getFrameInfo();
16167   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16168   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16169   EVT VT = Op.getValueType();
16170
16171   MFI->setFrameAddressIsTaken(true);
16172
16173   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16174     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16175     // is not possible to crawl up the stack without looking at the unwind codes
16176     // simultaneously.
16177     int FrameAddrIndex = FuncInfo->getFAIndex();
16178     if (!FrameAddrIndex) {
16179       // Set up a frame object for the return address.
16180       unsigned SlotSize = RegInfo->getSlotSize();
16181       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16182           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16183       FuncInfo->setFAIndex(FrameAddrIndex);
16184     }
16185     return DAG.getFrameIndex(FrameAddrIndex, VT);
16186   }
16187
16188   unsigned FrameReg =
16189       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16190   SDLoc dl(Op);  // FIXME probably not meaningful
16191   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16192   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16193           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16194          "Invalid Frame Register!");
16195   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16196   while (Depth--)
16197     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16198                             MachinePointerInfo(),
16199                             false, false, false, 0);
16200   return FrameAddr;
16201 }
16202
16203 // FIXME? Maybe this could be a TableGen attribute on some registers and
16204 // this table could be generated automatically from RegInfo.
16205 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
16206                                               EVT VT) const {
16207   unsigned Reg = StringSwitch<unsigned>(RegName)
16208                        .Case("esp", X86::ESP)
16209                        .Case("rsp", X86::RSP)
16210                        .Default(0);
16211   if (Reg)
16212     return Reg;
16213   report_fatal_error("Invalid register name global variable");
16214 }
16215
16216 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16217                                                      SelectionDAG &DAG) const {
16218   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16219   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16220 }
16221
16222 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16223   SDValue Chain     = Op.getOperand(0);
16224   SDValue Offset    = Op.getOperand(1);
16225   SDValue Handler   = Op.getOperand(2);
16226   SDLoc dl      (Op);
16227
16228   EVT PtrVT = getPointerTy();
16229   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16230   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16231   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16232           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16233          "Invalid Frame Register!");
16234   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16235   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16236
16237   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16238                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16239                                                        dl));
16240   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16241   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16242                        false, false, 0);
16243   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16244
16245   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16246                      DAG.getRegister(StoreAddrReg, PtrVT));
16247 }
16248
16249 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16250                                                SelectionDAG &DAG) const {
16251   SDLoc DL(Op);
16252   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16253                      DAG.getVTList(MVT::i32, MVT::Other),
16254                      Op.getOperand(0), Op.getOperand(1));
16255 }
16256
16257 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16258                                                 SelectionDAG &DAG) const {
16259   SDLoc DL(Op);
16260   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16261                      Op.getOperand(0), Op.getOperand(1));
16262 }
16263
16264 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16265   return Op.getOperand(0);
16266 }
16267
16268 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16269                                                 SelectionDAG &DAG) const {
16270   SDValue Root = Op.getOperand(0);
16271   SDValue Trmp = Op.getOperand(1); // trampoline
16272   SDValue FPtr = Op.getOperand(2); // nested function
16273   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16274   SDLoc dl (Op);
16275
16276   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16277   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16278
16279   if (Subtarget->is64Bit()) {
16280     SDValue OutChains[6];
16281
16282     // Large code-model.
16283     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16284     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16285
16286     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16287     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16288
16289     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16290
16291     // Load the pointer to the nested function into R11.
16292     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16293     SDValue Addr = Trmp;
16294     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16295                                 Addr, MachinePointerInfo(TrmpAddr),
16296                                 false, false, 0);
16297
16298     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16299                        DAG.getConstant(2, dl, MVT::i64));
16300     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16301                                 MachinePointerInfo(TrmpAddr, 2),
16302                                 false, false, 2);
16303
16304     // Load the 'nest' parameter value into R10.
16305     // R10 is specified in X86CallingConv.td
16306     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16307     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16308                        DAG.getConstant(10, dl, MVT::i64));
16309     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16310                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16311                                 false, false, 0);
16312
16313     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16314                        DAG.getConstant(12, dl, MVT::i64));
16315     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16316                                 MachinePointerInfo(TrmpAddr, 12),
16317                                 false, false, 2);
16318
16319     // Jump to the nested function.
16320     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16321     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16322                        DAG.getConstant(20, dl, MVT::i64));
16323     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16324                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16325                                 false, false, 0);
16326
16327     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16328     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16329                        DAG.getConstant(22, dl, MVT::i64));
16330     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16331                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16332                                 false, false, 0);
16333
16334     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16335   } else {
16336     const Function *Func =
16337       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16338     CallingConv::ID CC = Func->getCallingConv();
16339     unsigned NestReg;
16340
16341     switch (CC) {
16342     default:
16343       llvm_unreachable("Unsupported calling convention");
16344     case CallingConv::C:
16345     case CallingConv::X86_StdCall: {
16346       // Pass 'nest' parameter in ECX.
16347       // Must be kept in sync with X86CallingConv.td
16348       NestReg = X86::ECX;
16349
16350       // Check that ECX wasn't needed by an 'inreg' parameter.
16351       FunctionType *FTy = Func->getFunctionType();
16352       const AttributeSet &Attrs = Func->getAttributes();
16353
16354       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16355         unsigned InRegCount = 0;
16356         unsigned Idx = 1;
16357
16358         for (FunctionType::param_iterator I = FTy->param_begin(),
16359              E = FTy->param_end(); I != E; ++I, ++Idx)
16360           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16361             // FIXME: should only count parameters that are lowered to integers.
16362             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16363
16364         if (InRegCount > 2) {
16365           report_fatal_error("Nest register in use - reduce number of inreg"
16366                              " parameters!");
16367         }
16368       }
16369       break;
16370     }
16371     case CallingConv::X86_FastCall:
16372     case CallingConv::X86_ThisCall:
16373     case CallingConv::Fast:
16374       // Pass 'nest' parameter in EAX.
16375       // Must be kept in sync with X86CallingConv.td
16376       NestReg = X86::EAX;
16377       break;
16378     }
16379
16380     SDValue OutChains[4];
16381     SDValue Addr, Disp;
16382
16383     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16384                        DAG.getConstant(10, dl, MVT::i32));
16385     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16386
16387     // This is storing the opcode for MOV32ri.
16388     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16389     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16390     OutChains[0] = DAG.getStore(Root, dl,
16391                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16392                                 Trmp, MachinePointerInfo(TrmpAddr),
16393                                 false, false, 0);
16394
16395     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16396                        DAG.getConstant(1, dl, MVT::i32));
16397     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16398                                 MachinePointerInfo(TrmpAddr, 1),
16399                                 false, false, 1);
16400
16401     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16402     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16403                        DAG.getConstant(5, dl, MVT::i32));
16404     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16405                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16406                                 false, false, 1);
16407
16408     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16409                        DAG.getConstant(6, dl, MVT::i32));
16410     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16411                                 MachinePointerInfo(TrmpAddr, 6),
16412                                 false, false, 1);
16413
16414     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16415   }
16416 }
16417
16418 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16419                                             SelectionDAG &DAG) const {
16420   /*
16421    The rounding mode is in bits 11:10 of FPSR, and has the following
16422    settings:
16423      00 Round to nearest
16424      01 Round to -inf
16425      10 Round to +inf
16426      11 Round to 0
16427
16428   FLT_ROUNDS, on the other hand, expects the following:
16429     -1 Undefined
16430      0 Round to 0
16431      1 Round to nearest
16432      2 Round to +inf
16433      3 Round to -inf
16434
16435   To perform the conversion, we do:
16436     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16437   */
16438
16439   MachineFunction &MF = DAG.getMachineFunction();
16440   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16441   unsigned StackAlignment = TFI.getStackAlignment();
16442   MVT VT = Op.getSimpleValueType();
16443   SDLoc DL(Op);
16444
16445   // Save FP Control Word to stack slot
16446   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16447   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16448
16449   MachineMemOperand *MMO =
16450    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16451                            MachineMemOperand::MOStore, 2, 2);
16452
16453   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16454   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16455                                           DAG.getVTList(MVT::Other),
16456                                           Ops, MVT::i16, MMO);
16457
16458   // Load FP Control Word from stack slot
16459   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16460                             MachinePointerInfo(), false, false, false, 0);
16461
16462   // Transform as necessary
16463   SDValue CWD1 =
16464     DAG.getNode(ISD::SRL, DL, MVT::i16,
16465                 DAG.getNode(ISD::AND, DL, MVT::i16,
16466                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16467                 DAG.getConstant(11, DL, MVT::i8));
16468   SDValue CWD2 =
16469     DAG.getNode(ISD::SRL, DL, MVT::i16,
16470                 DAG.getNode(ISD::AND, DL, MVT::i16,
16471                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16472                 DAG.getConstant(9, DL, MVT::i8));
16473
16474   SDValue RetVal =
16475     DAG.getNode(ISD::AND, DL, MVT::i16,
16476                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16477                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16478                             DAG.getConstant(1, DL, MVT::i16)),
16479                 DAG.getConstant(3, DL, MVT::i16));
16480
16481   return DAG.getNode((VT.getSizeInBits() < 16 ?
16482                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16483 }
16484
16485 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16486   MVT VT = Op.getSimpleValueType();
16487   EVT OpVT = VT;
16488   unsigned NumBits = VT.getSizeInBits();
16489   SDLoc dl(Op);
16490
16491   Op = Op.getOperand(0);
16492   if (VT == MVT::i8) {
16493     // Zero extend to i32 since there is not an i8 bsr.
16494     OpVT = MVT::i32;
16495     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16496   }
16497
16498   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16499   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16500   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16501
16502   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16503   SDValue Ops[] = {
16504     Op,
16505     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16506     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16507     Op.getValue(1)
16508   };
16509   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16510
16511   // Finally xor with NumBits-1.
16512   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16513                    DAG.getConstant(NumBits - 1, dl, OpVT));
16514
16515   if (VT == MVT::i8)
16516     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16517   return Op;
16518 }
16519
16520 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16521   MVT VT = Op.getSimpleValueType();
16522   EVT OpVT = VT;
16523   unsigned NumBits = VT.getSizeInBits();
16524   SDLoc dl(Op);
16525
16526   Op = Op.getOperand(0);
16527   if (VT == MVT::i8) {
16528     // Zero extend to i32 since there is not an i8 bsr.
16529     OpVT = MVT::i32;
16530     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16531   }
16532
16533   // Issue a bsr (scan bits in reverse).
16534   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16535   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16536
16537   // And xor with NumBits-1.
16538   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16539                    DAG.getConstant(NumBits - 1, dl, OpVT));
16540
16541   if (VT == MVT::i8)
16542     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16543   return Op;
16544 }
16545
16546 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16547   MVT VT = Op.getSimpleValueType();
16548   unsigned NumBits = VT.getSizeInBits();
16549   SDLoc dl(Op);
16550   Op = Op.getOperand(0);
16551
16552   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16553   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16554   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16555
16556   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16557   SDValue Ops[] = {
16558     Op,
16559     DAG.getConstant(NumBits, dl, VT),
16560     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16561     Op.getValue(1)
16562   };
16563   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16564 }
16565
16566 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16567 // ones, and then concatenate the result back.
16568 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16569   MVT VT = Op.getSimpleValueType();
16570
16571   assert(VT.is256BitVector() && VT.isInteger() &&
16572          "Unsupported value type for operation");
16573
16574   unsigned NumElems = VT.getVectorNumElements();
16575   SDLoc dl(Op);
16576
16577   // Extract the LHS vectors
16578   SDValue LHS = Op.getOperand(0);
16579   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16580   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16581
16582   // Extract the RHS vectors
16583   SDValue RHS = Op.getOperand(1);
16584   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16585   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16586
16587   MVT EltVT = VT.getVectorElementType();
16588   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16589
16590   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16591                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16592                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16593 }
16594
16595 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16596   if (Op.getValueType() == MVT::i1)
16597     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16598                        Op.getOperand(0), Op.getOperand(1));
16599   assert(Op.getSimpleValueType().is256BitVector() &&
16600          Op.getSimpleValueType().isInteger() &&
16601          "Only handle AVX 256-bit vector integer operation");
16602   return Lower256IntArith(Op, DAG);
16603 }
16604
16605 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16606   if (Op.getValueType() == MVT::i1)
16607     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16608                        Op.getOperand(0), Op.getOperand(1));
16609   assert(Op.getSimpleValueType().is256BitVector() &&
16610          Op.getSimpleValueType().isInteger() &&
16611          "Only handle AVX 256-bit vector integer operation");
16612   return Lower256IntArith(Op, DAG);
16613 }
16614
16615 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16616                         SelectionDAG &DAG) {
16617   SDLoc dl(Op);
16618   MVT VT = Op.getSimpleValueType();
16619
16620   if (VT == MVT::i1)
16621     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16622
16623   // Decompose 256-bit ops into smaller 128-bit ops.
16624   if (VT.is256BitVector() && !Subtarget->hasInt256())
16625     return Lower256IntArith(Op, DAG);
16626
16627   SDValue A = Op.getOperand(0);
16628   SDValue B = Op.getOperand(1);
16629
16630   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16631   // pairs, multiply and truncate.
16632   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16633     if (Subtarget->hasInt256()) {
16634       if (VT == MVT::v32i8) {
16635         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16636         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16637         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16638         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16639         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16640         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16641         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16642         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16643                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16644                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16645       }
16646
16647       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16648       return DAG.getNode(
16649           ISD::TRUNCATE, dl, VT,
16650           DAG.getNode(ISD::MUL, dl, ExVT,
16651                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16652                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16653     }
16654
16655     assert(VT == MVT::v16i8 &&
16656            "Pre-AVX2 support only supports v16i8 multiplication");
16657     MVT ExVT = MVT::v8i16;
16658
16659     // Extract the lo parts and sign extend to i16
16660     SDValue ALo, BLo;
16661     if (Subtarget->hasSSE41()) {
16662       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16663       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16664     } else {
16665       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16666                               -1, 4, -1, 5, -1, 6, -1, 7};
16667       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16668       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16669       ALo = DAG.getBitcast(ExVT, ALo);
16670       BLo = DAG.getBitcast(ExVT, BLo);
16671       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16672       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16673     }
16674
16675     // Extract the hi parts and sign extend to i16
16676     SDValue AHi, BHi;
16677     if (Subtarget->hasSSE41()) {
16678       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16679                               -1, -1, -1, -1, -1, -1, -1, -1};
16680       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16681       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16682       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16683       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16684     } else {
16685       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16686                               -1, 12, -1, 13, -1, 14, -1, 15};
16687       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16688       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16689       AHi = DAG.getBitcast(ExVT, AHi);
16690       BHi = DAG.getBitcast(ExVT, BHi);
16691       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16692       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16693     }
16694
16695     // Multiply, mask the lower 8bits of the lo/hi results and pack
16696     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16697     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16698     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16699     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16700     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16701   }
16702
16703   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16704   if (VT == MVT::v4i32) {
16705     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16706            "Should not custom lower when pmuldq is available!");
16707
16708     // Extract the odd parts.
16709     static const int UnpackMask[] = { 1, -1, 3, -1 };
16710     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16711     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16712
16713     // Multiply the even parts.
16714     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16715     // Now multiply odd parts.
16716     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16717
16718     Evens = DAG.getBitcast(VT, Evens);
16719     Odds = DAG.getBitcast(VT, Odds);
16720
16721     // Merge the two vectors back together with a shuffle. This expands into 2
16722     // shuffles.
16723     static const int ShufMask[] = { 0, 4, 2, 6 };
16724     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16725   }
16726
16727   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16728          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16729
16730   //  Ahi = psrlqi(a, 32);
16731   //  Bhi = psrlqi(b, 32);
16732   //
16733   //  AloBlo = pmuludq(a, b);
16734   //  AloBhi = pmuludq(a, Bhi);
16735   //  AhiBlo = pmuludq(Ahi, b);
16736
16737   //  AloBhi = psllqi(AloBhi, 32);
16738   //  AhiBlo = psllqi(AhiBlo, 32);
16739   //  return AloBlo + AloBhi + AhiBlo;
16740
16741   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16742   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16743
16744   SDValue AhiBlo = Ahi;
16745   SDValue AloBhi = Bhi;
16746   // Bit cast to 32-bit vectors for MULUDQ
16747   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16748                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16749   A = DAG.getBitcast(MulVT, A);
16750   B = DAG.getBitcast(MulVT, B);
16751   Ahi = DAG.getBitcast(MulVT, Ahi);
16752   Bhi = DAG.getBitcast(MulVT, Bhi);
16753
16754   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16755   // After shifting right const values the result may be all-zero.
16756   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16757     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16758     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16759   }
16760   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16761     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16762     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16763   }
16764
16765   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16766   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16767 }
16768
16769 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16770   assert(Subtarget->isTargetWin64() && "Unexpected target");
16771   EVT VT = Op.getValueType();
16772   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16773          "Unexpected return type for lowering");
16774
16775   RTLIB::Libcall LC;
16776   bool isSigned;
16777   switch (Op->getOpcode()) {
16778   default: llvm_unreachable("Unexpected request for libcall!");
16779   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16780   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16781   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16782   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16783   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16784   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16785   }
16786
16787   SDLoc dl(Op);
16788   SDValue InChain = DAG.getEntryNode();
16789
16790   TargetLowering::ArgListTy Args;
16791   TargetLowering::ArgListEntry Entry;
16792   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16793     EVT ArgVT = Op->getOperand(i).getValueType();
16794     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16795            "Unexpected argument type for lowering");
16796     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16797     Entry.Node = StackPtr;
16798     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16799                            false, false, 16);
16800     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16801     Entry.Ty = PointerType::get(ArgTy,0);
16802     Entry.isSExt = false;
16803     Entry.isZExt = false;
16804     Args.push_back(Entry);
16805   }
16806
16807   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16808                                          getPointerTy());
16809
16810   TargetLowering::CallLoweringInfo CLI(DAG);
16811   CLI.setDebugLoc(dl).setChain(InChain)
16812     .setCallee(getLibcallCallingConv(LC),
16813                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16814                Callee, std::move(Args), 0)
16815     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16816
16817   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16818   return DAG.getBitcast(VT, CallInfo.first);
16819 }
16820
16821 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16822                              SelectionDAG &DAG) {
16823   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16824   EVT VT = Op0.getValueType();
16825   SDLoc dl(Op);
16826
16827   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16828          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16829
16830   // PMULxD operations multiply each even value (starting at 0) of LHS with
16831   // the related value of RHS and produce a widen result.
16832   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16833   // => <2 x i64> <ae|cg>
16834   //
16835   // In other word, to have all the results, we need to perform two PMULxD:
16836   // 1. one with the even values.
16837   // 2. one with the odd values.
16838   // To achieve #2, with need to place the odd values at an even position.
16839   //
16840   // Place the odd value at an even position (basically, shift all values 1
16841   // step to the left):
16842   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16843   // <a|b|c|d> => <b|undef|d|undef>
16844   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16845   // <e|f|g|h> => <f|undef|h|undef>
16846   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16847
16848   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16849   // ints.
16850   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16851   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16852   unsigned Opcode =
16853       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16854   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16855   // => <2 x i64> <ae|cg>
16856   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16857   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16858   // => <2 x i64> <bf|dh>
16859   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16860
16861   // Shuffle it back into the right order.
16862   SDValue Highs, Lows;
16863   if (VT == MVT::v8i32) {
16864     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16865     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16866     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16867     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16868   } else {
16869     const int HighMask[] = {1, 5, 3, 7};
16870     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16871     const int LowMask[] = {0, 4, 2, 6};
16872     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16873   }
16874
16875   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16876   // unsigned multiply.
16877   if (IsSigned && !Subtarget->hasSSE41()) {
16878     SDValue ShAmt =
16879         DAG.getConstant(31, dl,
16880                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16881     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16882                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16883     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16884                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16885
16886     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16887     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16888   }
16889
16890   // The first result of MUL_LOHI is actually the low value, followed by the
16891   // high value.
16892   SDValue Ops[] = {Lows, Highs};
16893   return DAG.getMergeValues(Ops, dl);
16894 }
16895
16896 // Return true if the requred (according to Opcode) shift-imm form is natively
16897 // supported by the Subtarget
16898 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16899                                         unsigned Opcode) {
16900   if (VT.getScalarSizeInBits() < 16)
16901     return false;
16902
16903   if (VT.is512BitVector() &&
16904       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16905     return true;
16906
16907   bool LShift = VT.is128BitVector() ||
16908     (VT.is256BitVector() && Subtarget->hasInt256());
16909
16910   bool AShift = LShift && (Subtarget->hasVLX() ||
16911     (VT != MVT::v2i64 && VT != MVT::v4i64));
16912   return (Opcode == ISD::SRA) ? AShift : LShift;
16913 }
16914
16915 // The shift amount is a variable, but it is the same for all vector lanes.
16916 // These instrcutions are defined together with shift-immediate.
16917 static
16918 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16919                                       unsigned Opcode) {
16920   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16921 }
16922
16923 // Return true if the requred (according to Opcode) variable-shift form is
16924 // natively supported by the Subtarget
16925 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16926                                     unsigned Opcode) {
16927
16928   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16929     return false;
16930
16931   // vXi16 supported only on AVX-512, BWI
16932   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16933     return false;
16934
16935   if (VT.is512BitVector() || Subtarget->hasVLX())
16936     return true;
16937
16938   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16939   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16940   return (Opcode == ISD::SRA) ? AShift : LShift;
16941 }
16942
16943 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16944                                          const X86Subtarget *Subtarget) {
16945   MVT VT = Op.getSimpleValueType();
16946   SDLoc dl(Op);
16947   SDValue R = Op.getOperand(0);
16948   SDValue Amt = Op.getOperand(1);
16949
16950   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16951     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16952
16953   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
16954     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
16955     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
16956     SDValue Ex = DAG.getBitcast(ExVT, R);
16957
16958     if (ShiftAmt >= 32) {
16959       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
16960       SDValue Upper =
16961           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
16962       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
16963                                                  ShiftAmt - 32, DAG);
16964       if (VT == MVT::v2i64)
16965         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
16966       if (VT == MVT::v4i64)
16967         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
16968                                   {9, 1, 11, 3, 13, 5, 15, 7});
16969     } else {
16970       // SRA upper i32, SHL whole i64 and select lower i32.
16971       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
16972                                                  ShiftAmt, DAG);
16973       SDValue Lower =
16974           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
16975       Lower = DAG.getBitcast(ExVT, Lower);
16976       if (VT == MVT::v2i64)
16977         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
16978       if (VT == MVT::v4i64)
16979         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
16980                                   {8, 1, 10, 3, 12, 5, 14, 7});
16981     }
16982     return DAG.getBitcast(VT, Ex);
16983   };
16984
16985   // Optimize shl/srl/sra with constant shift amount.
16986   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16987     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16988       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16989
16990       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16991         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16992
16993       // i64 SRA needs to be performed as partial shifts.
16994       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16995           Op.getOpcode() == ISD::SRA)
16996         return ArithmeticShiftRight64(ShiftAmt);
16997
16998       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16999         unsigned NumElts = VT.getVectorNumElements();
17000         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17001
17002         if (Op.getOpcode() == ISD::SHL) {
17003           // Simple i8 add case
17004           if (ShiftAmt == 1)
17005             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17006
17007           // Make a large shift.
17008           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17009                                                    R, ShiftAmt, DAG);
17010           SHL = DAG.getBitcast(VT, SHL);
17011           // Zero out the rightmost bits.
17012           SmallVector<SDValue, 32> V(
17013               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17014           return DAG.getNode(ISD::AND, dl, VT, SHL,
17015                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17016         }
17017         if (Op.getOpcode() == ISD::SRL) {
17018           // Make a large shift.
17019           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17020                                                    R, ShiftAmt, DAG);
17021           SRL = DAG.getBitcast(VT, SRL);
17022           // Zero out the leftmost bits.
17023           SmallVector<SDValue, 32> V(
17024               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17025           return DAG.getNode(ISD::AND, dl, VT, SRL,
17026                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17027         }
17028         if (Op.getOpcode() == ISD::SRA) {
17029           if (ShiftAmt == 7) {
17030             // R s>> 7  ===  R s< 0
17031             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17032             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17033           }
17034
17035           // R s>> a === ((R u>> a) ^ m) - m
17036           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17037           SmallVector<SDValue, 32> V(NumElts,
17038                                      DAG.getConstant(128 >> ShiftAmt, dl,
17039                                                      MVT::i8));
17040           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17041           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17042           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17043           return Res;
17044         }
17045         llvm_unreachable("Unknown shift opcode.");
17046       }
17047     }
17048   }
17049
17050   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17051   if (!Subtarget->is64Bit() &&
17052       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17053       Amt.getOpcode() == ISD::BITCAST &&
17054       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17055     Amt = Amt.getOperand(0);
17056     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17057                      VT.getVectorNumElements();
17058     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17059     uint64_t ShiftAmt = 0;
17060     for (unsigned i = 0; i != Ratio; ++i) {
17061       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17062       if (!C)
17063         return SDValue();
17064       // 6 == Log2(64)
17065       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17066     }
17067     // Check remaining shift amounts.
17068     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17069       uint64_t ShAmt = 0;
17070       for (unsigned j = 0; j != Ratio; ++j) {
17071         ConstantSDNode *C =
17072           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17073         if (!C)
17074           return SDValue();
17075         // 6 == Log2(64)
17076         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17077       }
17078       if (ShAmt != ShiftAmt)
17079         return SDValue();
17080     }
17081
17082     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17083       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17084
17085     if (Op.getOpcode() == ISD::SRA)
17086       return ArithmeticShiftRight64(ShiftAmt);
17087   }
17088
17089   return SDValue();
17090 }
17091
17092 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17093                                         const X86Subtarget* Subtarget) {
17094   MVT VT = Op.getSimpleValueType();
17095   SDLoc dl(Op);
17096   SDValue R = Op.getOperand(0);
17097   SDValue Amt = Op.getOperand(1);
17098
17099   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17100     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17101
17102   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17103     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17104
17105   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17106     SDValue BaseShAmt;
17107     EVT EltVT = VT.getVectorElementType();
17108
17109     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17110       // Check if this build_vector node is doing a splat.
17111       // If so, then set BaseShAmt equal to the splat value.
17112       BaseShAmt = BV->getSplatValue();
17113       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17114         BaseShAmt = SDValue();
17115     } else {
17116       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17117         Amt = Amt.getOperand(0);
17118
17119       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17120       if (SVN && SVN->isSplat()) {
17121         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17122         SDValue InVec = Amt.getOperand(0);
17123         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17124           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17125                  "Unexpected shuffle index found!");
17126           BaseShAmt = InVec.getOperand(SplatIdx);
17127         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17128            if (ConstantSDNode *C =
17129                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17130              if (C->getZExtValue() == SplatIdx)
17131                BaseShAmt = InVec.getOperand(1);
17132            }
17133         }
17134
17135         if (!BaseShAmt)
17136           // Avoid introducing an extract element from a shuffle.
17137           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17138                                   DAG.getIntPtrConstant(SplatIdx, dl));
17139       }
17140     }
17141
17142     if (BaseShAmt.getNode()) {
17143       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17144       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17145         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17146       else if (EltVT.bitsLT(MVT::i32))
17147         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17148
17149       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17150     }
17151   }
17152
17153   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17154   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17155       Amt.getOpcode() == ISD::BITCAST &&
17156       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17157     Amt = Amt.getOperand(0);
17158     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17159                      VT.getVectorNumElements();
17160     std::vector<SDValue> Vals(Ratio);
17161     for (unsigned i = 0; i != Ratio; ++i)
17162       Vals[i] = Amt.getOperand(i);
17163     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17164       for (unsigned j = 0; j != Ratio; ++j)
17165         if (Vals[j] != Amt.getOperand(i + j))
17166           return SDValue();
17167     }
17168
17169     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17170       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17171   }
17172   return SDValue();
17173 }
17174
17175 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17176                           SelectionDAG &DAG) {
17177   MVT VT = Op.getSimpleValueType();
17178   SDLoc dl(Op);
17179   SDValue R = Op.getOperand(0);
17180   SDValue Amt = Op.getOperand(1);
17181
17182   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17183   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17184
17185   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17186     return V;
17187
17188   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17189       return V;
17190
17191   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17192     return Op;
17193
17194   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17195   // shifts per-lane and then shuffle the partial results back together.
17196   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17197     // Splat the shift amounts so the scalar shifts above will catch it.
17198     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17199     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17200     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17201     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17202     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17203   }
17204
17205   // If possible, lower this packed shift into a vector multiply instead of
17206   // expanding it into a sequence of scalar shifts.
17207   // Do this only if the vector shift count is a constant build_vector.
17208   if (Op.getOpcode() == ISD::SHL &&
17209       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17210        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17211       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17212     SmallVector<SDValue, 8> Elts;
17213     EVT SVT = VT.getScalarType();
17214     unsigned SVTBits = SVT.getSizeInBits();
17215     const APInt &One = APInt(SVTBits, 1);
17216     unsigned NumElems = VT.getVectorNumElements();
17217
17218     for (unsigned i=0; i !=NumElems; ++i) {
17219       SDValue Op = Amt->getOperand(i);
17220       if (Op->getOpcode() == ISD::UNDEF) {
17221         Elts.push_back(Op);
17222         continue;
17223       }
17224
17225       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17226       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17227       uint64_t ShAmt = C.getZExtValue();
17228       if (ShAmt >= SVTBits) {
17229         Elts.push_back(DAG.getUNDEF(SVT));
17230         continue;
17231       }
17232       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17233     }
17234     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17235     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17236   }
17237
17238   // Lower SHL with variable shift amount.
17239   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17240     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17241
17242     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17243                      DAG.getConstant(0x3f800000U, dl, VT));
17244     Op = DAG.getBitcast(MVT::v4f32, Op);
17245     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17246     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17247   }
17248
17249   // If possible, lower this shift as a sequence of two shifts by
17250   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17251   // Example:
17252   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17253   //
17254   // Could be rewritten as:
17255   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17256   //
17257   // The advantage is that the two shifts from the example would be
17258   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17259   // the vector shift into four scalar shifts plus four pairs of vector
17260   // insert/extract.
17261   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17262       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17263     unsigned TargetOpcode = X86ISD::MOVSS;
17264     bool CanBeSimplified;
17265     // The splat value for the first packed shift (the 'X' from the example).
17266     SDValue Amt1 = Amt->getOperand(0);
17267     // The splat value for the second packed shift (the 'Y' from the example).
17268     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17269                                         Amt->getOperand(2);
17270
17271     // See if it is possible to replace this node with a sequence of
17272     // two shifts followed by a MOVSS/MOVSD
17273     if (VT == MVT::v4i32) {
17274       // Check if it is legal to use a MOVSS.
17275       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17276                         Amt2 == Amt->getOperand(3);
17277       if (!CanBeSimplified) {
17278         // Otherwise, check if we can still simplify this node using a MOVSD.
17279         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17280                           Amt->getOperand(2) == Amt->getOperand(3);
17281         TargetOpcode = X86ISD::MOVSD;
17282         Amt2 = Amt->getOperand(2);
17283       }
17284     } else {
17285       // Do similar checks for the case where the machine value type
17286       // is MVT::v8i16.
17287       CanBeSimplified = Amt1 == Amt->getOperand(1);
17288       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17289         CanBeSimplified = Amt2 == Amt->getOperand(i);
17290
17291       if (!CanBeSimplified) {
17292         TargetOpcode = X86ISD::MOVSD;
17293         CanBeSimplified = true;
17294         Amt2 = Amt->getOperand(4);
17295         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17296           CanBeSimplified = Amt1 == Amt->getOperand(i);
17297         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17298           CanBeSimplified = Amt2 == Amt->getOperand(j);
17299       }
17300     }
17301
17302     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17303         isa<ConstantSDNode>(Amt2)) {
17304       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17305       EVT CastVT = MVT::v4i32;
17306       SDValue Splat1 =
17307         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17308       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17309       SDValue Splat2 =
17310         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17311       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17312       if (TargetOpcode == X86ISD::MOVSD)
17313         CastVT = MVT::v2i64;
17314       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17315       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17316       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17317                                             BitCast1, DAG);
17318       return DAG.getBitcast(VT, Result);
17319     }
17320   }
17321
17322   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17323     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17324     unsigned ShiftOpcode = Op->getOpcode();
17325
17326     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17327       // On SSE41 targets we make use of the fact that VSELECT lowers
17328       // to PBLENDVB which selects bytes based just on the sign bit.
17329       if (Subtarget->hasSSE41()) {
17330         V0 = DAG.getBitcast(VT, V0);
17331         V1 = DAG.getBitcast(VT, V1);
17332         Sel = DAG.getBitcast(VT, Sel);
17333         return DAG.getBitcast(SelVT,
17334                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17335       }
17336       // On pre-SSE41 targets we test for the sign bit by comparing to
17337       // zero - a negative value will set all bits of the lanes to true
17338       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17339       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17340       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17341       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17342     };
17343
17344     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17345     // We can safely do this using i16 shifts as we're only interested in
17346     // the 3 lower bits of each byte.
17347     Amt = DAG.getBitcast(ExtVT, Amt);
17348     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17349     Amt = DAG.getBitcast(VT, Amt);
17350
17351     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17352       // r = VSELECT(r, shift(r, 4), a);
17353       SDValue M =
17354           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17355       R = SignBitSelect(VT, Amt, M, R);
17356
17357       // a += a
17358       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17359
17360       // r = VSELECT(r, shift(r, 2), a);
17361       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17362       R = SignBitSelect(VT, Amt, M, R);
17363
17364       // a += a
17365       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17366
17367       // return VSELECT(r, shift(r, 1), a);
17368       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17369       R = SignBitSelect(VT, Amt, M, R);
17370       return R;
17371     }
17372
17373     if (Op->getOpcode() == ISD::SRA) {
17374       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17375       // so we can correctly sign extend. We don't care what happens to the
17376       // lower byte.
17377       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17378       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17379       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17380       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17381       ALo = DAG.getBitcast(ExtVT, ALo);
17382       AHi = DAG.getBitcast(ExtVT, AHi);
17383       RLo = DAG.getBitcast(ExtVT, RLo);
17384       RHi = DAG.getBitcast(ExtVT, RHi);
17385
17386       // r = VSELECT(r, shift(r, 4), a);
17387       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17388                                 DAG.getConstant(4, dl, ExtVT));
17389       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17390                                 DAG.getConstant(4, dl, ExtVT));
17391       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17392       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17393
17394       // a += a
17395       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17396       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17397
17398       // r = VSELECT(r, shift(r, 2), a);
17399       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17400                         DAG.getConstant(2, dl, ExtVT));
17401       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17402                         DAG.getConstant(2, dl, ExtVT));
17403       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17404       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17405
17406       // a += a
17407       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17408       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17409
17410       // r = VSELECT(r, shift(r, 1), a);
17411       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17412                         DAG.getConstant(1, dl, ExtVT));
17413       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17414                         DAG.getConstant(1, dl, ExtVT));
17415       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17416       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17417
17418       // Logical shift the result back to the lower byte, leaving a zero upper
17419       // byte
17420       // meaning that we can safely pack with PACKUSWB.
17421       RLo =
17422           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17423       RHi =
17424           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17425       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17426     }
17427   }
17428
17429   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17430   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17431   // solution better.
17432   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17433     MVT ExtVT = MVT::v8i32;
17434     unsigned ExtOpc =
17435         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17436     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17437     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17438     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17439                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17440   }
17441
17442   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17443     MVT ExtVT = MVT::v8i32;
17444     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17445     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17446     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17447     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17448     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17449     ALo = DAG.getBitcast(ExtVT, ALo);
17450     AHi = DAG.getBitcast(ExtVT, AHi);
17451     RLo = DAG.getBitcast(ExtVT, RLo);
17452     RHi = DAG.getBitcast(ExtVT, RHi);
17453     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17454     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17455     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17456     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17457     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17458   }
17459
17460   if (VT == MVT::v8i16) {
17461     unsigned ShiftOpcode = Op->getOpcode();
17462
17463     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17464       // On SSE41 targets we make use of the fact that VSELECT lowers
17465       // to PBLENDVB which selects bytes based just on the sign bit.
17466       if (Subtarget->hasSSE41()) {
17467         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17468         V0 = DAG.getBitcast(ExtVT, V0);
17469         V1 = DAG.getBitcast(ExtVT, V1);
17470         Sel = DAG.getBitcast(ExtVT, Sel);
17471         return DAG.getBitcast(
17472             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17473       }
17474       // On pre-SSE41 targets we splat the sign bit - a negative value will
17475       // set all bits of the lanes to true and VSELECT uses that in
17476       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17477       SDValue C =
17478           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17479       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17480     };
17481
17482     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17483     if (Subtarget->hasSSE41()) {
17484       // On SSE41 targets we need to replicate the shift mask in both
17485       // bytes for PBLENDVB.
17486       Amt = DAG.getNode(
17487           ISD::OR, dl, VT,
17488           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17489           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17490     } else {
17491       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17492     }
17493
17494     // r = VSELECT(r, shift(r, 8), a);
17495     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17496     R = SignBitSelect(Amt, M, R);
17497
17498     // a += a
17499     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17500
17501     // r = VSELECT(r, shift(r, 4), a);
17502     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17503     R = SignBitSelect(Amt, M, R);
17504
17505     // a += a
17506     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17507
17508     // r = VSELECT(r, shift(r, 2), a);
17509     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17510     R = SignBitSelect(Amt, M, R);
17511
17512     // a += a
17513     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17514
17515     // return VSELECT(r, shift(r, 1), a);
17516     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17517     R = SignBitSelect(Amt, M, R);
17518     return R;
17519   }
17520
17521   // Decompose 256-bit shifts into smaller 128-bit shifts.
17522   if (VT.is256BitVector()) {
17523     unsigned NumElems = VT.getVectorNumElements();
17524     MVT EltVT = VT.getVectorElementType();
17525     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17526
17527     // Extract the two vectors
17528     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17529     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17530
17531     // Recreate the shift amount vectors
17532     SDValue Amt1, Amt2;
17533     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17534       // Constant shift amount
17535       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17536       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17537       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17538
17539       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17540       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17541     } else {
17542       // Variable shift amount
17543       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17544       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17545     }
17546
17547     // Issue new vector shifts for the smaller types
17548     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17549     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17550
17551     // Concatenate the result back
17552     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17553   }
17554
17555   return SDValue();
17556 }
17557
17558 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17559   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17560   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17561   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17562   // has only one use.
17563   SDNode *N = Op.getNode();
17564   SDValue LHS = N->getOperand(0);
17565   SDValue RHS = N->getOperand(1);
17566   unsigned BaseOp = 0;
17567   unsigned Cond = 0;
17568   SDLoc DL(Op);
17569   switch (Op.getOpcode()) {
17570   default: llvm_unreachable("Unknown ovf instruction!");
17571   case ISD::SADDO:
17572     // A subtract of one will be selected as a INC. Note that INC doesn't
17573     // set CF, so we can't do this for UADDO.
17574     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17575       if (C->isOne()) {
17576         BaseOp = X86ISD::INC;
17577         Cond = X86::COND_O;
17578         break;
17579       }
17580     BaseOp = X86ISD::ADD;
17581     Cond = X86::COND_O;
17582     break;
17583   case ISD::UADDO:
17584     BaseOp = X86ISD::ADD;
17585     Cond = X86::COND_B;
17586     break;
17587   case ISD::SSUBO:
17588     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17589     // set CF, so we can't do this for USUBO.
17590     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17591       if (C->isOne()) {
17592         BaseOp = X86ISD::DEC;
17593         Cond = X86::COND_O;
17594         break;
17595       }
17596     BaseOp = X86ISD::SUB;
17597     Cond = X86::COND_O;
17598     break;
17599   case ISD::USUBO:
17600     BaseOp = X86ISD::SUB;
17601     Cond = X86::COND_B;
17602     break;
17603   case ISD::SMULO:
17604     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17605     Cond = X86::COND_O;
17606     break;
17607   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17608     if (N->getValueType(0) == MVT::i8) {
17609       BaseOp = X86ISD::UMUL8;
17610       Cond = X86::COND_O;
17611       break;
17612     }
17613     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17614                                  MVT::i32);
17615     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17616
17617     SDValue SetCC =
17618       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17619                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17620                   SDValue(Sum.getNode(), 2));
17621
17622     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17623   }
17624   }
17625
17626   // Also sets EFLAGS.
17627   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17628   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17629
17630   SDValue SetCC =
17631     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17632                 DAG.getConstant(Cond, DL, MVT::i32),
17633                 SDValue(Sum.getNode(), 1));
17634
17635   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17636 }
17637
17638 /// Returns true if the operand type is exactly twice the native width, and
17639 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17640 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17641 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17642 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17643   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17644
17645   if (OpWidth == 64)
17646     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17647   else if (OpWidth == 128)
17648     return Subtarget->hasCmpxchg16b();
17649   else
17650     return false;
17651 }
17652
17653 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17654   return needsCmpXchgNb(SI->getValueOperand()->getType());
17655 }
17656
17657 // Note: this turns large loads into lock cmpxchg8b/16b.
17658 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17659 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17660   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17661   return needsCmpXchgNb(PTy->getElementType());
17662 }
17663
17664 TargetLoweringBase::AtomicRMWExpansionKind
17665 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17666   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17667   const Type *MemType = AI->getType();
17668
17669   // If the operand is too big, we must see if cmpxchg8/16b is available
17670   // and default to library calls otherwise.
17671   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17672     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17673                                    : AtomicRMWExpansionKind::None;
17674   }
17675
17676   AtomicRMWInst::BinOp Op = AI->getOperation();
17677   switch (Op) {
17678   default:
17679     llvm_unreachable("Unknown atomic operation");
17680   case AtomicRMWInst::Xchg:
17681   case AtomicRMWInst::Add:
17682   case AtomicRMWInst::Sub:
17683     // It's better to use xadd, xsub or xchg for these in all cases.
17684     return AtomicRMWExpansionKind::None;
17685   case AtomicRMWInst::Or:
17686   case AtomicRMWInst::And:
17687   case AtomicRMWInst::Xor:
17688     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17689     // prefix to a normal instruction for these operations.
17690     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17691                             : AtomicRMWExpansionKind::None;
17692   case AtomicRMWInst::Nand:
17693   case AtomicRMWInst::Max:
17694   case AtomicRMWInst::Min:
17695   case AtomicRMWInst::UMax:
17696   case AtomicRMWInst::UMin:
17697     // These always require a non-trivial set of data operations on x86. We must
17698     // use a cmpxchg loop.
17699     return AtomicRMWExpansionKind::CmpXChg;
17700   }
17701 }
17702
17703 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17704   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17705   // no-sse2). There isn't any reason to disable it if the target processor
17706   // supports it.
17707   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17708 }
17709
17710 LoadInst *
17711 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17712   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17713   const Type *MemType = AI->getType();
17714   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17715   // there is no benefit in turning such RMWs into loads, and it is actually
17716   // harmful as it introduces a mfence.
17717   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17718     return nullptr;
17719
17720   auto Builder = IRBuilder<>(AI);
17721   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17722   auto SynchScope = AI->getSynchScope();
17723   // We must restrict the ordering to avoid generating loads with Release or
17724   // ReleaseAcquire orderings.
17725   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17726   auto Ptr = AI->getPointerOperand();
17727
17728   // Before the load we need a fence. Here is an example lifted from
17729   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17730   // is required:
17731   // Thread 0:
17732   //   x.store(1, relaxed);
17733   //   r1 = y.fetch_add(0, release);
17734   // Thread 1:
17735   //   y.fetch_add(42, acquire);
17736   //   r2 = x.load(relaxed);
17737   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17738   // lowered to just a load without a fence. A mfence flushes the store buffer,
17739   // making the optimization clearly correct.
17740   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17741   // otherwise, we might be able to be more agressive on relaxed idempotent
17742   // rmw. In practice, they do not look useful, so we don't try to be
17743   // especially clever.
17744   if (SynchScope == SingleThread)
17745     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17746     // the IR level, so we must wrap it in an intrinsic.
17747     return nullptr;
17748
17749   if (!hasMFENCE(*Subtarget))
17750     // FIXME: it might make sense to use a locked operation here but on a
17751     // different cache-line to prevent cache-line bouncing. In practice it
17752     // is probably a small win, and x86 processors without mfence are rare
17753     // enough that we do not bother.
17754     return nullptr;
17755
17756   Function *MFence =
17757       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17758   Builder.CreateCall(MFence, {});
17759
17760   // Finally we can emit the atomic load.
17761   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17762           AI->getType()->getPrimitiveSizeInBits());
17763   Loaded->setAtomic(Order, SynchScope);
17764   AI->replaceAllUsesWith(Loaded);
17765   AI->eraseFromParent();
17766   return Loaded;
17767 }
17768
17769 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17770                                  SelectionDAG &DAG) {
17771   SDLoc dl(Op);
17772   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17773     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17774   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17775     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17776
17777   // The only fence that needs an instruction is a sequentially-consistent
17778   // cross-thread fence.
17779   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17780     if (hasMFENCE(*Subtarget))
17781       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17782
17783     SDValue Chain = Op.getOperand(0);
17784     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17785     SDValue Ops[] = {
17786       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17787       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17788       DAG.getRegister(0, MVT::i32),            // Index
17789       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17790       DAG.getRegister(0, MVT::i32),            // Segment.
17791       Zero,
17792       Chain
17793     };
17794     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17795     return SDValue(Res, 0);
17796   }
17797
17798   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17799   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17800 }
17801
17802 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17803                              SelectionDAG &DAG) {
17804   MVT T = Op.getSimpleValueType();
17805   SDLoc DL(Op);
17806   unsigned Reg = 0;
17807   unsigned size = 0;
17808   switch(T.SimpleTy) {
17809   default: llvm_unreachable("Invalid value type!");
17810   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17811   case MVT::i16: Reg = X86::AX;  size = 2; break;
17812   case MVT::i32: Reg = X86::EAX; size = 4; break;
17813   case MVT::i64:
17814     assert(Subtarget->is64Bit() && "Node not type legal!");
17815     Reg = X86::RAX; size = 8;
17816     break;
17817   }
17818   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17819                                   Op.getOperand(2), SDValue());
17820   SDValue Ops[] = { cpIn.getValue(0),
17821                     Op.getOperand(1),
17822                     Op.getOperand(3),
17823                     DAG.getTargetConstant(size, DL, MVT::i8),
17824                     cpIn.getValue(1) };
17825   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17826   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17827   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17828                                            Ops, T, MMO);
17829
17830   SDValue cpOut =
17831     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17832   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17833                                       MVT::i32, cpOut.getValue(2));
17834   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17835                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17836                                 EFLAGS);
17837
17838   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17839   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17840   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17841   return SDValue();
17842 }
17843
17844 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17845                             SelectionDAG &DAG) {
17846   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17847   MVT DstVT = Op.getSimpleValueType();
17848
17849   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17850     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17851     if (DstVT != MVT::f64)
17852       // This conversion needs to be expanded.
17853       return SDValue();
17854
17855     SDValue InVec = Op->getOperand(0);
17856     SDLoc dl(Op);
17857     unsigned NumElts = SrcVT.getVectorNumElements();
17858     EVT SVT = SrcVT.getVectorElementType();
17859
17860     // Widen the vector in input in the case of MVT::v2i32.
17861     // Example: from MVT::v2i32 to MVT::v4i32.
17862     SmallVector<SDValue, 16> Elts;
17863     for (unsigned i = 0, e = NumElts; i != e; ++i)
17864       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17865                                  DAG.getIntPtrConstant(i, dl)));
17866
17867     // Explicitly mark the extra elements as Undef.
17868     Elts.append(NumElts, DAG.getUNDEF(SVT));
17869
17870     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17871     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17872     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
17873     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17874                        DAG.getIntPtrConstant(0, dl));
17875   }
17876
17877   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17878          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17879   assert((DstVT == MVT::i64 ||
17880           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17881          "Unexpected custom BITCAST");
17882   // i64 <=> MMX conversions are Legal.
17883   if (SrcVT==MVT::i64 && DstVT.isVector())
17884     return Op;
17885   if (DstVT==MVT::i64 && SrcVT.isVector())
17886     return Op;
17887   // MMX <=> MMX conversions are Legal.
17888   if (SrcVT.isVector() && DstVT.isVector())
17889     return Op;
17890   // All other conversions need to be expanded.
17891   return SDValue();
17892 }
17893
17894 /// Compute the horizontal sum of bytes in V for the elements of VT.
17895 ///
17896 /// Requires V to be a byte vector and VT to be an integer vector type with
17897 /// wider elements than V's type. The width of the elements of VT determines
17898 /// how many bytes of V are summed horizontally to produce each element of the
17899 /// result.
17900 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
17901                                       const X86Subtarget *Subtarget,
17902                                       SelectionDAG &DAG) {
17903   SDLoc DL(V);
17904   MVT ByteVecVT = V.getSimpleValueType();
17905   MVT EltVT = VT.getVectorElementType();
17906   int NumElts = VT.getVectorNumElements();
17907   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
17908          "Expected value to have byte element type.");
17909   assert(EltVT != MVT::i8 &&
17910          "Horizontal byte sum only makes sense for wider elements!");
17911   unsigned VecSize = VT.getSizeInBits();
17912   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
17913
17914   // PSADBW instruction horizontally add all bytes and leave the result in i64
17915   // chunks, thus directly computes the pop count for v2i64 and v4i64.
17916   if (EltVT == MVT::i64) {
17917     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17918     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
17919     return DAG.getBitcast(VT, V);
17920   }
17921
17922   if (EltVT == MVT::i32) {
17923     // We unpack the low half and high half into i32s interleaved with zeros so
17924     // that we can use PSADBW to horizontally sum them. The most useful part of
17925     // this is that it lines up the results of two PSADBW instructions to be
17926     // two v2i64 vectors which concatenated are the 4 population counts. We can
17927     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
17928     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
17929     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
17930     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
17931
17932     // Do the horizontal sums into two v2i64s.
17933     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17934     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17935                       DAG.getBitcast(ByteVecVT, Low), Zeros);
17936     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17937                        DAG.getBitcast(ByteVecVT, High), Zeros);
17938
17939     // Merge them together.
17940     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
17941     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
17942                     DAG.getBitcast(ShortVecVT, Low),
17943                     DAG.getBitcast(ShortVecVT, High));
17944
17945     return DAG.getBitcast(VT, V);
17946   }
17947
17948   // The only element type left is i16.
17949   assert(EltVT == MVT::i16 && "Unknown how to handle type");
17950
17951   // To obtain pop count for each i16 element starting from the pop count for
17952   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
17953   // right by 8. It is important to shift as i16s as i8 vector shift isn't
17954   // directly supported.
17955   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
17956   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
17957   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17958   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
17959                   DAG.getBitcast(ByteVecVT, V));
17960   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17961 }
17962
17963 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
17964                                         const X86Subtarget *Subtarget,
17965                                         SelectionDAG &DAG) {
17966   MVT VT = Op.getSimpleValueType();
17967   MVT EltVT = VT.getVectorElementType();
17968   unsigned VecSize = VT.getSizeInBits();
17969
17970   // Implement a lookup table in register by using an algorithm based on:
17971   // http://wm.ite.pl/articles/sse-popcount.html
17972   //
17973   // The general idea is that every lower byte nibble in the input vector is an
17974   // index into a in-register pre-computed pop count table. We then split up the
17975   // input vector in two new ones: (1) a vector with only the shifted-right
17976   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
17977   // masked out higher ones) for each byte. PSHUB is used separately with both
17978   // to index the in-register table. Next, both are added and the result is a
17979   // i8 vector where each element contains the pop count for input byte.
17980   //
17981   // To obtain the pop count for elements != i8, we follow up with the same
17982   // approach and use additional tricks as described below.
17983   //
17984   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
17985                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
17986                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
17987                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
17988
17989   int NumByteElts = VecSize / 8;
17990   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
17991   SDValue In = DAG.getBitcast(ByteVecVT, Op);
17992   SmallVector<SDValue, 16> LUTVec;
17993   for (int i = 0; i < NumByteElts; ++i)
17994     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
17995   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
17996   SmallVector<SDValue, 16> Mask0F(NumByteElts,
17997                                   DAG.getConstant(0x0F, DL, MVT::i8));
17998   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
17999
18000   // High nibbles
18001   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18002   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18003   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18004
18005   // Low nibbles
18006   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18007
18008   // The input vector is used as the shuffle mask that index elements into the
18009   // LUT. After counting low and high nibbles, add the vector to obtain the
18010   // final pop count per i8 element.
18011   SDValue HighPopCnt =
18012       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18013   SDValue LowPopCnt =
18014       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18015   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18016
18017   if (EltVT == MVT::i8)
18018     return PopCnt;
18019
18020   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18021 }
18022
18023 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18024                                        const X86Subtarget *Subtarget,
18025                                        SelectionDAG &DAG) {
18026   MVT VT = Op.getSimpleValueType();
18027   assert(VT.is128BitVector() &&
18028          "Only 128-bit vector bitmath lowering supported.");
18029
18030   int VecSize = VT.getSizeInBits();
18031   MVT EltVT = VT.getVectorElementType();
18032   int Len = EltVT.getSizeInBits();
18033
18034   // This is the vectorized version of the "best" algorithm from
18035   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18036   // with a minor tweak to use a series of adds + shifts instead of vector
18037   // multiplications. Implemented for all integer vector types. We only use
18038   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18039   // much faster, even faster than using native popcnt instructions.
18040
18041   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18042     MVT VT = V.getSimpleValueType();
18043     SmallVector<SDValue, 32> Shifters(
18044         VT.getVectorNumElements(),
18045         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18046     return DAG.getNode(OpCode, DL, VT, V,
18047                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18048   };
18049   auto GetMask = [&](SDValue V, APInt Mask) {
18050     MVT VT = V.getSimpleValueType();
18051     SmallVector<SDValue, 32> Masks(
18052         VT.getVectorNumElements(),
18053         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18054     return DAG.getNode(ISD::AND, DL, VT, V,
18055                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18056   };
18057
18058   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18059   // x86, so set the SRL type to have elements at least i16 wide. This is
18060   // correct because all of our SRLs are followed immediately by a mask anyways
18061   // that handles any bits that sneak into the high bits of the byte elements.
18062   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18063
18064   SDValue V = Op;
18065
18066   // v = v - ((v >> 1) & 0x55555555...)
18067   SDValue Srl =
18068       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18069   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18070   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18071
18072   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18073   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18074   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18075   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18076   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18077
18078   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18079   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18080   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18081   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18082
18083   // At this point, V contains the byte-wise population count, and we are
18084   // merely doing a horizontal sum if necessary to get the wider element
18085   // counts.
18086   if (EltVT == MVT::i8)
18087     return V;
18088
18089   return LowerHorizontalByteSum(
18090       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18091       DAG);
18092 }
18093
18094 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18095                                 SelectionDAG &DAG) {
18096   MVT VT = Op.getSimpleValueType();
18097   // FIXME: Need to add AVX-512 support here!
18098   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18099          "Unknown CTPOP type to handle");
18100   SDLoc DL(Op.getNode());
18101   SDValue Op0 = Op.getOperand(0);
18102
18103   if (!Subtarget->hasSSSE3()) {
18104     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18105     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18106     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18107   }
18108
18109   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18110     unsigned NumElems = VT.getVectorNumElements();
18111
18112     // Extract each 128-bit vector, compute pop count and concat the result.
18113     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18114     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18115
18116     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18117                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18118                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18119   }
18120
18121   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18122 }
18123
18124 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18125                           SelectionDAG &DAG) {
18126   assert(Op.getValueType().isVector() &&
18127          "We only do custom lowering for vector population count.");
18128   return LowerVectorCTPOP(Op, Subtarget, DAG);
18129 }
18130
18131 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18132   SDNode *Node = Op.getNode();
18133   SDLoc dl(Node);
18134   EVT T = Node->getValueType(0);
18135   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18136                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18137   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18138                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18139                        Node->getOperand(0),
18140                        Node->getOperand(1), negOp,
18141                        cast<AtomicSDNode>(Node)->getMemOperand(),
18142                        cast<AtomicSDNode>(Node)->getOrdering(),
18143                        cast<AtomicSDNode>(Node)->getSynchScope());
18144 }
18145
18146 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18147   SDNode *Node = Op.getNode();
18148   SDLoc dl(Node);
18149   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18150
18151   // Convert seq_cst store -> xchg
18152   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18153   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18154   //        (The only way to get a 16-byte store is cmpxchg16b)
18155   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18156   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18157       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18158     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18159                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18160                                  Node->getOperand(0),
18161                                  Node->getOperand(1), Node->getOperand(2),
18162                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18163                                  cast<AtomicSDNode>(Node)->getOrdering(),
18164                                  cast<AtomicSDNode>(Node)->getSynchScope());
18165     return Swap.getValue(1);
18166   }
18167   // Other atomic stores have a simple pattern.
18168   return Op;
18169 }
18170
18171 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18172   EVT VT = Op.getNode()->getSimpleValueType(0);
18173
18174   // Let legalize expand this if it isn't a legal type yet.
18175   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18176     return SDValue();
18177
18178   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18179
18180   unsigned Opc;
18181   bool ExtraOp = false;
18182   switch (Op.getOpcode()) {
18183   default: llvm_unreachable("Invalid code");
18184   case ISD::ADDC: Opc = X86ISD::ADD; break;
18185   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18186   case ISD::SUBC: Opc = X86ISD::SUB; break;
18187   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18188   }
18189
18190   if (!ExtraOp)
18191     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18192                        Op.getOperand(1));
18193   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18194                      Op.getOperand(1), Op.getOperand(2));
18195 }
18196
18197 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18198                             SelectionDAG &DAG) {
18199   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18200
18201   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18202   // which returns the values as { float, float } (in XMM0) or
18203   // { double, double } (which is returned in XMM0, XMM1).
18204   SDLoc dl(Op);
18205   SDValue Arg = Op.getOperand(0);
18206   EVT ArgVT = Arg.getValueType();
18207   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18208
18209   TargetLowering::ArgListTy Args;
18210   TargetLowering::ArgListEntry Entry;
18211
18212   Entry.Node = Arg;
18213   Entry.Ty = ArgTy;
18214   Entry.isSExt = false;
18215   Entry.isZExt = false;
18216   Args.push_back(Entry);
18217
18218   bool isF64 = ArgVT == MVT::f64;
18219   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18220   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18221   // the results are returned via SRet in memory.
18222   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18223   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18224   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18225
18226   Type *RetTy = isF64
18227     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18228     : (Type*)VectorType::get(ArgTy, 4);
18229
18230   TargetLowering::CallLoweringInfo CLI(DAG);
18231   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18232     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18233
18234   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18235
18236   if (isF64)
18237     // Returned in xmm0 and xmm1.
18238     return CallResult.first;
18239
18240   // Returned in bits 0:31 and 32:64 xmm0.
18241   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18242                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18243   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18244                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18245   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18246   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18247 }
18248
18249 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18250                              SelectionDAG &DAG) {
18251   assert(Subtarget->hasAVX512() &&
18252          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18253
18254   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18255   EVT VT = N->getValue().getValueType();
18256   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18257   SDLoc dl(Op);
18258
18259   // X86 scatter kills mask register, so its type should be added to
18260   // the list of return values
18261   if (N->getNumValues() == 1) {
18262     SDValue Index = N->getIndex();
18263     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18264         !Index.getValueType().is512BitVector())
18265       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18266
18267     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18268     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18269                       N->getOperand(3), Index };
18270
18271     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18272     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18273     return SDValue(NewScatter.getNode(), 0);
18274   }
18275   return Op;
18276 }
18277
18278 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18279                             SelectionDAG &DAG) {
18280   assert(Subtarget->hasAVX512() &&
18281          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18282
18283   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18284   EVT VT = Op.getValueType();
18285   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18286   SDLoc dl(Op);
18287
18288   SDValue Index = N->getIndex();
18289   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18290       !Index.getValueType().is512BitVector()) {
18291     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18292     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18293                       N->getOperand(3), Index };
18294     DAG.UpdateNodeOperands(N, Ops);
18295   }
18296   return Op;
18297 }
18298
18299 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18300                                                     SelectionDAG &DAG) const {
18301   // TODO: Eventually, the lowering of these nodes should be informed by or
18302   // deferred to the GC strategy for the function in which they appear. For
18303   // now, however, they must be lowered to something. Since they are logically
18304   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18305   // require special handling for these nodes), lower them as literal NOOPs for
18306   // the time being.
18307   SmallVector<SDValue, 2> Ops;
18308
18309   Ops.push_back(Op.getOperand(0));
18310   if (Op->getGluedNode())
18311     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18312
18313   SDLoc OpDL(Op);
18314   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18315   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18316
18317   return NOOP;
18318 }
18319
18320 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18321                                                   SelectionDAG &DAG) const {
18322   // TODO: Eventually, the lowering of these nodes should be informed by or
18323   // deferred to the GC strategy for the function in which they appear. For
18324   // now, however, they must be lowered to something. Since they are logically
18325   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18326   // require special handling for these nodes), lower them as literal NOOPs for
18327   // the time being.
18328   SmallVector<SDValue, 2> Ops;
18329
18330   Ops.push_back(Op.getOperand(0));
18331   if (Op->getGluedNode())
18332     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18333
18334   SDLoc OpDL(Op);
18335   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18336   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18337
18338   return NOOP;
18339 }
18340
18341 /// LowerOperation - Provide custom lowering hooks for some operations.
18342 ///
18343 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18344   switch (Op.getOpcode()) {
18345   default: llvm_unreachable("Should not custom lower this!");
18346   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18347   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18348     return LowerCMP_SWAP(Op, Subtarget, DAG);
18349   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18350   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18351   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18352   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18353   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18354   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18355   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18356   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18357   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18358   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18359   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18360   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18361   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18362   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18363   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18364   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18365   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18366   case ISD::SHL_PARTS:
18367   case ISD::SRA_PARTS:
18368   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18369   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18370   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18371   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18372   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18373   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18374   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18375   case ISD::SIGN_EXTEND_VECTOR_INREG:
18376     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18377   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18378   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18379   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18380   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18381   case ISD::FABS:
18382   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18383   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18384   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18385   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18386   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18387   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18388   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18389   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18390   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18391   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18392   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18393   case ISD::INTRINSIC_VOID:
18394   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18395   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18396   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18397   case ISD::FRAME_TO_ARGS_OFFSET:
18398                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18399   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18400   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18401   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18402   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18403   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18404   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18405   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18406   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18407   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18408   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18409   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18410   case ISD::UMUL_LOHI:
18411   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18412   case ISD::SRA:
18413   case ISD::SRL:
18414   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18415   case ISD::SADDO:
18416   case ISD::UADDO:
18417   case ISD::SSUBO:
18418   case ISD::USUBO:
18419   case ISD::SMULO:
18420   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18421   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18422   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18423   case ISD::ADDC:
18424   case ISD::ADDE:
18425   case ISD::SUBC:
18426   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18427   case ISD::ADD:                return LowerADD(Op, DAG);
18428   case ISD::SUB:                return LowerSUB(Op, DAG);
18429   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18430   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18431   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18432   case ISD::GC_TRANSITION_START:
18433                                 return LowerGC_TRANSITION_START(Op, DAG);
18434   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18435   }
18436 }
18437
18438 /// ReplaceNodeResults - Replace a node with an illegal result type
18439 /// with a new node built out of custom code.
18440 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18441                                            SmallVectorImpl<SDValue>&Results,
18442                                            SelectionDAG &DAG) const {
18443   SDLoc dl(N);
18444   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18445   switch (N->getOpcode()) {
18446   default:
18447     llvm_unreachable("Do not know how to custom type legalize this operation!");
18448   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18449   case X86ISD::FMINC:
18450   case X86ISD::FMIN:
18451   case X86ISD::FMAXC:
18452   case X86ISD::FMAX: {
18453     EVT VT = N->getValueType(0);
18454     if (VT != MVT::v2f32)
18455       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18456     SDValue UNDEF = DAG.getUNDEF(VT);
18457     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18458                               N->getOperand(0), UNDEF);
18459     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18460                               N->getOperand(1), UNDEF);
18461     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18462     return;
18463   }
18464   case ISD::SIGN_EXTEND_INREG:
18465   case ISD::ADDC:
18466   case ISD::ADDE:
18467   case ISD::SUBC:
18468   case ISD::SUBE:
18469     // We don't want to expand or promote these.
18470     return;
18471   case ISD::SDIV:
18472   case ISD::UDIV:
18473   case ISD::SREM:
18474   case ISD::UREM:
18475   case ISD::SDIVREM:
18476   case ISD::UDIVREM: {
18477     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18478     Results.push_back(V);
18479     return;
18480   }
18481   case ISD::FP_TO_SINT:
18482     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18483     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18484     if (N->getOperand(0).getValueType() == MVT::f16)
18485       break;
18486     // fallthrough
18487   case ISD::FP_TO_UINT: {
18488     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18489
18490     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18491       return;
18492
18493     std::pair<SDValue,SDValue> Vals =
18494         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18495     SDValue FIST = Vals.first, StackSlot = Vals.second;
18496     if (FIST.getNode()) {
18497       EVT VT = N->getValueType(0);
18498       // Return a load from the stack slot.
18499       if (StackSlot.getNode())
18500         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18501                                       MachinePointerInfo(),
18502                                       false, false, false, 0));
18503       else
18504         Results.push_back(FIST);
18505     }
18506     return;
18507   }
18508   case ISD::UINT_TO_FP: {
18509     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18510     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18511         N->getValueType(0) != MVT::v2f32)
18512       return;
18513     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18514                                  N->getOperand(0));
18515     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18516                                      MVT::f64);
18517     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18518     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18519                              DAG.getBitcast(MVT::v2i64, VBias));
18520     Or = DAG.getBitcast(MVT::v2f64, Or);
18521     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18522     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18523     return;
18524   }
18525   case ISD::FP_ROUND: {
18526     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18527         return;
18528     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18529     Results.push_back(V);
18530     return;
18531   }
18532   case ISD::FP_EXTEND: {
18533     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18534     // No other ValueType for FP_EXTEND should reach this point.
18535     assert(N->getValueType(0) == MVT::v2f32 &&
18536            "Do not know how to legalize this Node");
18537     return;
18538   }
18539   case ISD::INTRINSIC_W_CHAIN: {
18540     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18541     switch (IntNo) {
18542     default : llvm_unreachable("Do not know how to custom type "
18543                                "legalize this intrinsic operation!");
18544     case Intrinsic::x86_rdtsc:
18545       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18546                                      Results);
18547     case Intrinsic::x86_rdtscp:
18548       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18549                                      Results);
18550     case Intrinsic::x86_rdpmc:
18551       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18552     }
18553   }
18554   case ISD::READCYCLECOUNTER: {
18555     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18556                                    Results);
18557   }
18558   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18559     EVT T = N->getValueType(0);
18560     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18561     bool Regs64bit = T == MVT::i128;
18562     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18563     SDValue cpInL, cpInH;
18564     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18565                         DAG.getConstant(0, dl, HalfT));
18566     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18567                         DAG.getConstant(1, dl, HalfT));
18568     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18569                              Regs64bit ? X86::RAX : X86::EAX,
18570                              cpInL, SDValue());
18571     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18572                              Regs64bit ? X86::RDX : X86::EDX,
18573                              cpInH, cpInL.getValue(1));
18574     SDValue swapInL, swapInH;
18575     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18576                           DAG.getConstant(0, dl, HalfT));
18577     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18578                           DAG.getConstant(1, dl, HalfT));
18579     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18580                                Regs64bit ? X86::RBX : X86::EBX,
18581                                swapInL, cpInH.getValue(1));
18582     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18583                                Regs64bit ? X86::RCX : X86::ECX,
18584                                swapInH, swapInL.getValue(1));
18585     SDValue Ops[] = { swapInH.getValue(0),
18586                       N->getOperand(1),
18587                       swapInH.getValue(1) };
18588     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18589     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18590     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18591                                   X86ISD::LCMPXCHG8_DAG;
18592     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18593     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18594                                         Regs64bit ? X86::RAX : X86::EAX,
18595                                         HalfT, Result.getValue(1));
18596     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18597                                         Regs64bit ? X86::RDX : X86::EDX,
18598                                         HalfT, cpOutL.getValue(2));
18599     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18600
18601     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18602                                         MVT::i32, cpOutH.getValue(2));
18603     SDValue Success =
18604         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18605                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18606     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18607
18608     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18609     Results.push_back(Success);
18610     Results.push_back(EFLAGS.getValue(1));
18611     return;
18612   }
18613   case ISD::ATOMIC_SWAP:
18614   case ISD::ATOMIC_LOAD_ADD:
18615   case ISD::ATOMIC_LOAD_SUB:
18616   case ISD::ATOMIC_LOAD_AND:
18617   case ISD::ATOMIC_LOAD_OR:
18618   case ISD::ATOMIC_LOAD_XOR:
18619   case ISD::ATOMIC_LOAD_NAND:
18620   case ISD::ATOMIC_LOAD_MIN:
18621   case ISD::ATOMIC_LOAD_MAX:
18622   case ISD::ATOMIC_LOAD_UMIN:
18623   case ISD::ATOMIC_LOAD_UMAX:
18624   case ISD::ATOMIC_LOAD: {
18625     // Delegate to generic TypeLegalization. Situations we can really handle
18626     // should have already been dealt with by AtomicExpandPass.cpp.
18627     break;
18628   }
18629   case ISD::BITCAST: {
18630     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18631     EVT DstVT = N->getValueType(0);
18632     EVT SrcVT = N->getOperand(0)->getValueType(0);
18633
18634     if (SrcVT != MVT::f64 ||
18635         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18636       return;
18637
18638     unsigned NumElts = DstVT.getVectorNumElements();
18639     EVT SVT = DstVT.getVectorElementType();
18640     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18641     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18642                                    MVT::v2f64, N->getOperand(0));
18643     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18644
18645     if (ExperimentalVectorWideningLegalization) {
18646       // If we are legalizing vectors by widening, we already have the desired
18647       // legal vector type, just return it.
18648       Results.push_back(ToVecInt);
18649       return;
18650     }
18651
18652     SmallVector<SDValue, 8> Elts;
18653     for (unsigned i = 0, e = NumElts; i != e; ++i)
18654       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18655                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18656
18657     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18658   }
18659   }
18660 }
18661
18662 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18663   switch ((X86ISD::NodeType)Opcode) {
18664   case X86ISD::FIRST_NUMBER:       break;
18665   case X86ISD::BSF:                return "X86ISD::BSF";
18666   case X86ISD::BSR:                return "X86ISD::BSR";
18667   case X86ISD::SHLD:               return "X86ISD::SHLD";
18668   case X86ISD::SHRD:               return "X86ISD::SHRD";
18669   case X86ISD::FAND:               return "X86ISD::FAND";
18670   case X86ISD::FANDN:              return "X86ISD::FANDN";
18671   case X86ISD::FOR:                return "X86ISD::FOR";
18672   case X86ISD::FXOR:               return "X86ISD::FXOR";
18673   case X86ISD::FILD:               return "X86ISD::FILD";
18674   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18675   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18676   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18677   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18678   case X86ISD::FLD:                return "X86ISD::FLD";
18679   case X86ISD::FST:                return "X86ISD::FST";
18680   case X86ISD::CALL:               return "X86ISD::CALL";
18681   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18682   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18683   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18684   case X86ISD::BT:                 return "X86ISD::BT";
18685   case X86ISD::CMP:                return "X86ISD::CMP";
18686   case X86ISD::COMI:               return "X86ISD::COMI";
18687   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18688   case X86ISD::CMPM:               return "X86ISD::CMPM";
18689   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18690   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18691   case X86ISD::SETCC:              return "X86ISD::SETCC";
18692   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18693   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18694   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18695   case X86ISD::CMOV:               return "X86ISD::CMOV";
18696   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18697   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18698   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18699   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18700   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18701   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18702   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18703   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18704   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18705   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18706   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18707   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18708   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18709   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18710   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18711   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18712   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18713   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18714   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18715   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18716   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18717   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18718   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18719   case X86ISD::HADD:               return "X86ISD::HADD";
18720   case X86ISD::HSUB:               return "X86ISD::HSUB";
18721   case X86ISD::FHADD:              return "X86ISD::FHADD";
18722   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18723   case X86ISD::ABS:                return "X86ISD::ABS";
18724   case X86ISD::FMAX:               return "X86ISD::FMAX";
18725   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18726   case X86ISD::FMIN:               return "X86ISD::FMIN";
18727   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18728   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18729   case X86ISD::FMINC:              return "X86ISD::FMINC";
18730   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18731   case X86ISD::FRCP:               return "X86ISD::FRCP";
18732   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18733   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18734   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18735   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18736   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18737   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18738   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18739   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18740   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18741   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18742   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18743   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18744   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18745   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18746   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18747   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18748   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18749   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18750   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18751   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18752   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18753   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18754   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18755   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18756   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18757   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18758   case X86ISD::VSHL:               return "X86ISD::VSHL";
18759   case X86ISD::VSRL:               return "X86ISD::VSRL";
18760   case X86ISD::VSRA:               return "X86ISD::VSRA";
18761   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18762   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18763   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18764   case X86ISD::CMPP:               return "X86ISD::CMPP";
18765   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18766   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18767   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18768   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18769   case X86ISD::ADD:                return "X86ISD::ADD";
18770   case X86ISD::SUB:                return "X86ISD::SUB";
18771   case X86ISD::ADC:                return "X86ISD::ADC";
18772   case X86ISD::SBB:                return "X86ISD::SBB";
18773   case X86ISD::SMUL:               return "X86ISD::SMUL";
18774   case X86ISD::UMUL:               return "X86ISD::UMUL";
18775   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18776   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18777   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18778   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18779   case X86ISD::INC:                return "X86ISD::INC";
18780   case X86ISD::DEC:                return "X86ISD::DEC";
18781   case X86ISD::OR:                 return "X86ISD::OR";
18782   case X86ISD::XOR:                return "X86ISD::XOR";
18783   case X86ISD::AND:                return "X86ISD::AND";
18784   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18785   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18786   case X86ISD::PTEST:              return "X86ISD::PTEST";
18787   case X86ISD::TESTP:              return "X86ISD::TESTP";
18788   case X86ISD::TESTM:              return "X86ISD::TESTM";
18789   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18790   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18791   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18792   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18793   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18794   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18795   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18796   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18797   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18798   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18799   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18800   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18801   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18802   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18803   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18804   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18805   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18806   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18807   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18808   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18809   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18810   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18811   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18812   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18813   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18814   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18815   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18816   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18817   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18818   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18819   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18820   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18821   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18822   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18823   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18824   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18825   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18826   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18827   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18828   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18829   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18830   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18831   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18832   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18833   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18834   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18835   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18836   case X86ISD::SAHF:               return "X86ISD::SAHF";
18837   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18838   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18839   case X86ISD::FMADD:              return "X86ISD::FMADD";
18840   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18841   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18842   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18843   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18844   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18845   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18846   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18847   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18848   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18849   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18850   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18851   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18852   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18853   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18854   case X86ISD::XTEST:              return "X86ISD::XTEST";
18855   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18856   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18857   case X86ISD::SELECT:             return "X86ISD::SELECT";
18858   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18859   case X86ISD::RCP28:              return "X86ISD::RCP28";
18860   case X86ISD::EXP2:               return "X86ISD::EXP2";
18861   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18862   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18863   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18864   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18865   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18866   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
18867   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
18868   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
18869   case X86ISD::ADDS:               return "X86ISD::ADDS";
18870   case X86ISD::SUBS:               return "X86ISD::SUBS";
18871   case X86ISD::AVG:                return "X86ISD::AVG";
18872   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
18873   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
18874   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
18875   }
18876   return nullptr;
18877 }
18878
18879 // isLegalAddressingMode - Return true if the addressing mode represented
18880 // by AM is legal for this target, for a load/store of the specified type.
18881 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18882                                               Type *Ty,
18883                                               unsigned AS) const {
18884   // X86 supports extremely general addressing modes.
18885   CodeModel::Model M = getTargetMachine().getCodeModel();
18886   Reloc::Model R = getTargetMachine().getRelocationModel();
18887
18888   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18889   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18890     return false;
18891
18892   if (AM.BaseGV) {
18893     unsigned GVFlags =
18894       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18895
18896     // If a reference to this global requires an extra load, we can't fold it.
18897     if (isGlobalStubReference(GVFlags))
18898       return false;
18899
18900     // If BaseGV requires a register for the PIC base, we cannot also have a
18901     // BaseReg specified.
18902     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18903       return false;
18904
18905     // If lower 4G is not available, then we must use rip-relative addressing.
18906     if ((M != CodeModel::Small || R != Reloc::Static) &&
18907         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18908       return false;
18909   }
18910
18911   switch (AM.Scale) {
18912   case 0:
18913   case 1:
18914   case 2:
18915   case 4:
18916   case 8:
18917     // These scales always work.
18918     break;
18919   case 3:
18920   case 5:
18921   case 9:
18922     // These scales are formed with basereg+scalereg.  Only accept if there is
18923     // no basereg yet.
18924     if (AM.HasBaseReg)
18925       return false;
18926     break;
18927   default:  // Other stuff never works.
18928     return false;
18929   }
18930
18931   return true;
18932 }
18933
18934 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18935   unsigned Bits = Ty->getScalarSizeInBits();
18936
18937   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18938   // particularly cheaper than those without.
18939   if (Bits == 8)
18940     return false;
18941
18942   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18943   // variable shifts just as cheap as scalar ones.
18944   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18945     return false;
18946
18947   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18948   // fully general vector.
18949   return true;
18950 }
18951
18952 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18953   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18954     return false;
18955   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18956   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18957   return NumBits1 > NumBits2;
18958 }
18959
18960 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18961   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18962     return false;
18963
18964   if (!isTypeLegal(EVT::getEVT(Ty1)))
18965     return false;
18966
18967   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18968
18969   // Assuming the caller doesn't have a zeroext or signext return parameter,
18970   // truncation all the way down to i1 is valid.
18971   return true;
18972 }
18973
18974 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18975   return isInt<32>(Imm);
18976 }
18977
18978 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18979   // Can also use sub to handle negated immediates.
18980   return isInt<32>(Imm);
18981 }
18982
18983 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18984   if (!VT1.isInteger() || !VT2.isInteger())
18985     return false;
18986   unsigned NumBits1 = VT1.getSizeInBits();
18987   unsigned NumBits2 = VT2.getSizeInBits();
18988   return NumBits1 > NumBits2;
18989 }
18990
18991 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18992   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18993   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18994 }
18995
18996 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18997   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18998   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18999 }
19000
19001 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19002   EVT VT1 = Val.getValueType();
19003   if (isZExtFree(VT1, VT2))
19004     return true;
19005
19006   if (Val.getOpcode() != ISD::LOAD)
19007     return false;
19008
19009   if (!VT1.isSimple() || !VT1.isInteger() ||
19010       !VT2.isSimple() || !VT2.isInteger())
19011     return false;
19012
19013   switch (VT1.getSimpleVT().SimpleTy) {
19014   default: break;
19015   case MVT::i8:
19016   case MVT::i16:
19017   case MVT::i32:
19018     // X86 has 8, 16, and 32-bit zero-extending loads.
19019     return true;
19020   }
19021
19022   return false;
19023 }
19024
19025 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19026
19027 bool
19028 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19029   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19030     return false;
19031
19032   VT = VT.getScalarType();
19033
19034   if (!VT.isSimple())
19035     return false;
19036
19037   switch (VT.getSimpleVT().SimpleTy) {
19038   case MVT::f32:
19039   case MVT::f64:
19040     return true;
19041   default:
19042     break;
19043   }
19044
19045   return false;
19046 }
19047
19048 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19049   // i16 instructions are longer (0x66 prefix) and potentially slower.
19050   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19051 }
19052
19053 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19054 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19055 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19056 /// are assumed to be legal.
19057 bool
19058 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19059                                       EVT VT) const {
19060   if (!VT.isSimple())
19061     return false;
19062
19063   // Not for i1 vectors
19064   if (VT.getScalarType() == MVT::i1)
19065     return false;
19066
19067   // Very little shuffling can be done for 64-bit vectors right now.
19068   if (VT.getSizeInBits() == 64)
19069     return false;
19070
19071   // We only care that the types being shuffled are legal. The lowering can
19072   // handle any possible shuffle mask that results.
19073   return isTypeLegal(VT.getSimpleVT());
19074 }
19075
19076 bool
19077 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19078                                           EVT VT) const {
19079   // Just delegate to the generic legality, clear masks aren't special.
19080   return isShuffleMaskLegal(Mask, VT);
19081 }
19082
19083 //===----------------------------------------------------------------------===//
19084 //                           X86 Scheduler Hooks
19085 //===----------------------------------------------------------------------===//
19086
19087 /// Utility function to emit xbegin specifying the start of an RTM region.
19088 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19089                                      const TargetInstrInfo *TII) {
19090   DebugLoc DL = MI->getDebugLoc();
19091
19092   const BasicBlock *BB = MBB->getBasicBlock();
19093   MachineFunction::iterator I = MBB;
19094   ++I;
19095
19096   // For the v = xbegin(), we generate
19097   //
19098   // thisMBB:
19099   //  xbegin sinkMBB
19100   //
19101   // mainMBB:
19102   //  eax = -1
19103   //
19104   // sinkMBB:
19105   //  v = eax
19106
19107   MachineBasicBlock *thisMBB = MBB;
19108   MachineFunction *MF = MBB->getParent();
19109   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19110   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19111   MF->insert(I, mainMBB);
19112   MF->insert(I, sinkMBB);
19113
19114   // Transfer the remainder of BB and its successor edges to sinkMBB.
19115   sinkMBB->splice(sinkMBB->begin(), MBB,
19116                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19117   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19118
19119   // thisMBB:
19120   //  xbegin sinkMBB
19121   //  # fallthrough to mainMBB
19122   //  # abortion to sinkMBB
19123   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19124   thisMBB->addSuccessor(mainMBB);
19125   thisMBB->addSuccessor(sinkMBB);
19126
19127   // mainMBB:
19128   //  EAX = -1
19129   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19130   mainMBB->addSuccessor(sinkMBB);
19131
19132   // sinkMBB:
19133   // EAX is live into the sinkMBB
19134   sinkMBB->addLiveIn(X86::EAX);
19135   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19136           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19137     .addReg(X86::EAX);
19138
19139   MI->eraseFromParent();
19140   return sinkMBB;
19141 }
19142
19143 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19144 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19145 // in the .td file.
19146 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19147                                        const TargetInstrInfo *TII) {
19148   unsigned Opc;
19149   switch (MI->getOpcode()) {
19150   default: llvm_unreachable("illegal opcode!");
19151   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19152   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19153   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19154   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19155   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19156   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19157   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19158   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19159   }
19160
19161   DebugLoc dl = MI->getDebugLoc();
19162   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19163
19164   unsigned NumArgs = MI->getNumOperands();
19165   for (unsigned i = 1; i < NumArgs; ++i) {
19166     MachineOperand &Op = MI->getOperand(i);
19167     if (!(Op.isReg() && Op.isImplicit()))
19168       MIB.addOperand(Op);
19169   }
19170   if (MI->hasOneMemOperand())
19171     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19172
19173   BuildMI(*BB, MI, dl,
19174     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19175     .addReg(X86::XMM0);
19176
19177   MI->eraseFromParent();
19178   return BB;
19179 }
19180
19181 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19182 // defs in an instruction pattern
19183 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19184                                        const TargetInstrInfo *TII) {
19185   unsigned Opc;
19186   switch (MI->getOpcode()) {
19187   default: llvm_unreachable("illegal opcode!");
19188   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19189   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19190   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19191   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19192   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19193   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19194   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19195   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19196   }
19197
19198   DebugLoc dl = MI->getDebugLoc();
19199   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19200
19201   unsigned NumArgs = MI->getNumOperands(); // remove the results
19202   for (unsigned i = 1; i < NumArgs; ++i) {
19203     MachineOperand &Op = MI->getOperand(i);
19204     if (!(Op.isReg() && Op.isImplicit()))
19205       MIB.addOperand(Op);
19206   }
19207   if (MI->hasOneMemOperand())
19208     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19209
19210   BuildMI(*BB, MI, dl,
19211     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19212     .addReg(X86::ECX);
19213
19214   MI->eraseFromParent();
19215   return BB;
19216 }
19217
19218 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19219                                       const X86Subtarget *Subtarget) {
19220   DebugLoc dl = MI->getDebugLoc();
19221   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19222   // Address into RAX/EAX, other two args into ECX, EDX.
19223   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19224   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19225   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19226   for (int i = 0; i < X86::AddrNumOperands; ++i)
19227     MIB.addOperand(MI->getOperand(i));
19228
19229   unsigned ValOps = X86::AddrNumOperands;
19230   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19231     .addReg(MI->getOperand(ValOps).getReg());
19232   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19233     .addReg(MI->getOperand(ValOps+1).getReg());
19234
19235   // The instruction doesn't actually take any operands though.
19236   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19237
19238   MI->eraseFromParent(); // The pseudo is gone now.
19239   return BB;
19240 }
19241
19242 MachineBasicBlock *
19243 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19244                                                  MachineBasicBlock *MBB) const {
19245   // Emit va_arg instruction on X86-64.
19246
19247   // Operands to this pseudo-instruction:
19248   // 0  ) Output        : destination address (reg)
19249   // 1-5) Input         : va_list address (addr, i64mem)
19250   // 6  ) ArgSize       : Size (in bytes) of vararg type
19251   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19252   // 8  ) Align         : Alignment of type
19253   // 9  ) EFLAGS (implicit-def)
19254
19255   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19256   static_assert(X86::AddrNumOperands == 5,
19257                 "VAARG_64 assumes 5 address operands");
19258
19259   unsigned DestReg = MI->getOperand(0).getReg();
19260   MachineOperand &Base = MI->getOperand(1);
19261   MachineOperand &Scale = MI->getOperand(2);
19262   MachineOperand &Index = MI->getOperand(3);
19263   MachineOperand &Disp = MI->getOperand(4);
19264   MachineOperand &Segment = MI->getOperand(5);
19265   unsigned ArgSize = MI->getOperand(6).getImm();
19266   unsigned ArgMode = MI->getOperand(7).getImm();
19267   unsigned Align = MI->getOperand(8).getImm();
19268
19269   // Memory Reference
19270   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19271   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19272   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19273
19274   // Machine Information
19275   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19276   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19277   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19278   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19279   DebugLoc DL = MI->getDebugLoc();
19280
19281   // struct va_list {
19282   //   i32   gp_offset
19283   //   i32   fp_offset
19284   //   i64   overflow_area (address)
19285   //   i64   reg_save_area (address)
19286   // }
19287   // sizeof(va_list) = 24
19288   // alignment(va_list) = 8
19289
19290   unsigned TotalNumIntRegs = 6;
19291   unsigned TotalNumXMMRegs = 8;
19292   bool UseGPOffset = (ArgMode == 1);
19293   bool UseFPOffset = (ArgMode == 2);
19294   unsigned MaxOffset = TotalNumIntRegs * 8 +
19295                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19296
19297   /* Align ArgSize to a multiple of 8 */
19298   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19299   bool NeedsAlign = (Align > 8);
19300
19301   MachineBasicBlock *thisMBB = MBB;
19302   MachineBasicBlock *overflowMBB;
19303   MachineBasicBlock *offsetMBB;
19304   MachineBasicBlock *endMBB;
19305
19306   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19307   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19308   unsigned OffsetReg = 0;
19309
19310   if (!UseGPOffset && !UseFPOffset) {
19311     // If we only pull from the overflow region, we don't create a branch.
19312     // We don't need to alter control flow.
19313     OffsetDestReg = 0; // unused
19314     OverflowDestReg = DestReg;
19315
19316     offsetMBB = nullptr;
19317     overflowMBB = thisMBB;
19318     endMBB = thisMBB;
19319   } else {
19320     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19321     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19322     // If not, pull from overflow_area. (branch to overflowMBB)
19323     //
19324     //       thisMBB
19325     //         |     .
19326     //         |        .
19327     //     offsetMBB   overflowMBB
19328     //         |        .
19329     //         |     .
19330     //        endMBB
19331
19332     // Registers for the PHI in endMBB
19333     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19334     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19335
19336     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19337     MachineFunction *MF = MBB->getParent();
19338     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19339     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19340     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19341
19342     MachineFunction::iterator MBBIter = MBB;
19343     ++MBBIter;
19344
19345     // Insert the new basic blocks
19346     MF->insert(MBBIter, offsetMBB);
19347     MF->insert(MBBIter, overflowMBB);
19348     MF->insert(MBBIter, endMBB);
19349
19350     // Transfer the remainder of MBB and its successor edges to endMBB.
19351     endMBB->splice(endMBB->begin(), thisMBB,
19352                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19353     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19354
19355     // Make offsetMBB and overflowMBB successors of thisMBB
19356     thisMBB->addSuccessor(offsetMBB);
19357     thisMBB->addSuccessor(overflowMBB);
19358
19359     // endMBB is a successor of both offsetMBB and overflowMBB
19360     offsetMBB->addSuccessor(endMBB);
19361     overflowMBB->addSuccessor(endMBB);
19362
19363     // Load the offset value into a register
19364     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19365     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19366       .addOperand(Base)
19367       .addOperand(Scale)
19368       .addOperand(Index)
19369       .addDisp(Disp, UseFPOffset ? 4 : 0)
19370       .addOperand(Segment)
19371       .setMemRefs(MMOBegin, MMOEnd);
19372
19373     // Check if there is enough room left to pull this argument.
19374     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19375       .addReg(OffsetReg)
19376       .addImm(MaxOffset + 8 - ArgSizeA8);
19377
19378     // Branch to "overflowMBB" if offset >= max
19379     // Fall through to "offsetMBB" otherwise
19380     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19381       .addMBB(overflowMBB);
19382   }
19383
19384   // In offsetMBB, emit code to use the reg_save_area.
19385   if (offsetMBB) {
19386     assert(OffsetReg != 0);
19387
19388     // Read the reg_save_area address.
19389     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19390     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19391       .addOperand(Base)
19392       .addOperand(Scale)
19393       .addOperand(Index)
19394       .addDisp(Disp, 16)
19395       .addOperand(Segment)
19396       .setMemRefs(MMOBegin, MMOEnd);
19397
19398     // Zero-extend the offset
19399     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19400       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19401         .addImm(0)
19402         .addReg(OffsetReg)
19403         .addImm(X86::sub_32bit);
19404
19405     // Add the offset to the reg_save_area to get the final address.
19406     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19407       .addReg(OffsetReg64)
19408       .addReg(RegSaveReg);
19409
19410     // Compute the offset for the next argument
19411     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19412     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19413       .addReg(OffsetReg)
19414       .addImm(UseFPOffset ? 16 : 8);
19415
19416     // Store it back into the va_list.
19417     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19418       .addOperand(Base)
19419       .addOperand(Scale)
19420       .addOperand(Index)
19421       .addDisp(Disp, UseFPOffset ? 4 : 0)
19422       .addOperand(Segment)
19423       .addReg(NextOffsetReg)
19424       .setMemRefs(MMOBegin, MMOEnd);
19425
19426     // Jump to endMBB
19427     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19428       .addMBB(endMBB);
19429   }
19430
19431   //
19432   // Emit code to use overflow area
19433   //
19434
19435   // Load the overflow_area address into a register.
19436   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19437   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19438     .addOperand(Base)
19439     .addOperand(Scale)
19440     .addOperand(Index)
19441     .addDisp(Disp, 8)
19442     .addOperand(Segment)
19443     .setMemRefs(MMOBegin, MMOEnd);
19444
19445   // If we need to align it, do so. Otherwise, just copy the address
19446   // to OverflowDestReg.
19447   if (NeedsAlign) {
19448     // Align the overflow address
19449     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19450     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19451
19452     // aligned_addr = (addr + (align-1)) & ~(align-1)
19453     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19454       .addReg(OverflowAddrReg)
19455       .addImm(Align-1);
19456
19457     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19458       .addReg(TmpReg)
19459       .addImm(~(uint64_t)(Align-1));
19460   } else {
19461     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19462       .addReg(OverflowAddrReg);
19463   }
19464
19465   // Compute the next overflow address after this argument.
19466   // (the overflow address should be kept 8-byte aligned)
19467   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19468   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19469     .addReg(OverflowDestReg)
19470     .addImm(ArgSizeA8);
19471
19472   // Store the new overflow address.
19473   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19474     .addOperand(Base)
19475     .addOperand(Scale)
19476     .addOperand(Index)
19477     .addDisp(Disp, 8)
19478     .addOperand(Segment)
19479     .addReg(NextAddrReg)
19480     .setMemRefs(MMOBegin, MMOEnd);
19481
19482   // If we branched, emit the PHI to the front of endMBB.
19483   if (offsetMBB) {
19484     BuildMI(*endMBB, endMBB->begin(), DL,
19485             TII->get(X86::PHI), DestReg)
19486       .addReg(OffsetDestReg).addMBB(offsetMBB)
19487       .addReg(OverflowDestReg).addMBB(overflowMBB);
19488   }
19489
19490   // Erase the pseudo instruction
19491   MI->eraseFromParent();
19492
19493   return endMBB;
19494 }
19495
19496 MachineBasicBlock *
19497 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19498                                                  MachineInstr *MI,
19499                                                  MachineBasicBlock *MBB) const {
19500   // Emit code to save XMM registers to the stack. The ABI says that the
19501   // number of registers to save is given in %al, so it's theoretically
19502   // possible to do an indirect jump trick to avoid saving all of them,
19503   // however this code takes a simpler approach and just executes all
19504   // of the stores if %al is non-zero. It's less code, and it's probably
19505   // easier on the hardware branch predictor, and stores aren't all that
19506   // expensive anyway.
19507
19508   // Create the new basic blocks. One block contains all the XMM stores,
19509   // and one block is the final destination regardless of whether any
19510   // stores were performed.
19511   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19512   MachineFunction *F = MBB->getParent();
19513   MachineFunction::iterator MBBIter = MBB;
19514   ++MBBIter;
19515   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19516   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19517   F->insert(MBBIter, XMMSaveMBB);
19518   F->insert(MBBIter, EndMBB);
19519
19520   // Transfer the remainder of MBB and its successor edges to EndMBB.
19521   EndMBB->splice(EndMBB->begin(), MBB,
19522                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19523   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19524
19525   // The original block will now fall through to the XMM save block.
19526   MBB->addSuccessor(XMMSaveMBB);
19527   // The XMMSaveMBB will fall through to the end block.
19528   XMMSaveMBB->addSuccessor(EndMBB);
19529
19530   // Now add the instructions.
19531   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19532   DebugLoc DL = MI->getDebugLoc();
19533
19534   unsigned CountReg = MI->getOperand(0).getReg();
19535   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19536   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19537
19538   if (!Subtarget->isTargetWin64()) {
19539     // If %al is 0, branch around the XMM save block.
19540     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19541     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19542     MBB->addSuccessor(EndMBB);
19543   }
19544
19545   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19546   // that was just emitted, but clearly shouldn't be "saved".
19547   assert((MI->getNumOperands() <= 3 ||
19548           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19549           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19550          && "Expected last argument to be EFLAGS");
19551   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19552   // In the XMM save block, save all the XMM argument registers.
19553   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19554     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19555     MachineMemOperand *MMO =
19556       F->getMachineMemOperand(
19557           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19558         MachineMemOperand::MOStore,
19559         /*Size=*/16, /*Align=*/16);
19560     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19561       .addFrameIndex(RegSaveFrameIndex)
19562       .addImm(/*Scale=*/1)
19563       .addReg(/*IndexReg=*/0)
19564       .addImm(/*Disp=*/Offset)
19565       .addReg(/*Segment=*/0)
19566       .addReg(MI->getOperand(i).getReg())
19567       .addMemOperand(MMO);
19568   }
19569
19570   MI->eraseFromParent();   // The pseudo instruction is gone now.
19571
19572   return EndMBB;
19573 }
19574
19575 // The EFLAGS operand of SelectItr might be missing a kill marker
19576 // because there were multiple uses of EFLAGS, and ISel didn't know
19577 // which to mark. Figure out whether SelectItr should have had a
19578 // kill marker, and set it if it should. Returns the correct kill
19579 // marker value.
19580 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19581                                      MachineBasicBlock* BB,
19582                                      const TargetRegisterInfo* TRI) {
19583   // Scan forward through BB for a use/def of EFLAGS.
19584   MachineBasicBlock::iterator miI(std::next(SelectItr));
19585   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19586     const MachineInstr& mi = *miI;
19587     if (mi.readsRegister(X86::EFLAGS))
19588       return false;
19589     if (mi.definesRegister(X86::EFLAGS))
19590       break; // Should have kill-flag - update below.
19591   }
19592
19593   // If we hit the end of the block, check whether EFLAGS is live into a
19594   // successor.
19595   if (miI == BB->end()) {
19596     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19597                                           sEnd = BB->succ_end();
19598          sItr != sEnd; ++sItr) {
19599       MachineBasicBlock* succ = *sItr;
19600       if (succ->isLiveIn(X86::EFLAGS))
19601         return false;
19602     }
19603   }
19604
19605   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19606   // out. SelectMI should have a kill flag on EFLAGS.
19607   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19608   return true;
19609 }
19610
19611 MachineBasicBlock *
19612 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19613                                      MachineBasicBlock *BB) const {
19614   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19615   DebugLoc DL = MI->getDebugLoc();
19616
19617   // To "insert" a SELECT_CC instruction, we actually have to insert the
19618   // diamond control-flow pattern.  The incoming instruction knows the
19619   // destination vreg to set, the condition code register to branch on, the
19620   // true/false values to select between, and a branch opcode to use.
19621   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19622   MachineFunction::iterator It = BB;
19623   ++It;
19624
19625   //  thisMBB:
19626   //  ...
19627   //   TrueVal = ...
19628   //   cmpTY ccX, r1, r2
19629   //   bCC copy1MBB
19630   //   fallthrough --> copy0MBB
19631   MachineBasicBlock *thisMBB = BB;
19632   MachineFunction *F = BB->getParent();
19633
19634   // We also lower double CMOVs:
19635   //   (CMOV (CMOV F, T, cc1), T, cc2)
19636   // to two successives branches.  For that, we look for another CMOV as the
19637   // following instruction.
19638   //
19639   // Without this, we would add a PHI between the two jumps, which ends up
19640   // creating a few copies all around. For instance, for
19641   //
19642   //    (sitofp (zext (fcmp une)))
19643   //
19644   // we would generate:
19645   //
19646   //         ucomiss %xmm1, %xmm0
19647   //         movss  <1.0f>, %xmm0
19648   //         movaps  %xmm0, %xmm1
19649   //         jne     .LBB5_2
19650   //         xorps   %xmm1, %xmm1
19651   // .LBB5_2:
19652   //         jp      .LBB5_4
19653   //         movaps  %xmm1, %xmm0
19654   // .LBB5_4:
19655   //         retq
19656   //
19657   // because this custom-inserter would have generated:
19658   //
19659   //   A
19660   //   | \
19661   //   |  B
19662   //   | /
19663   //   C
19664   //   | \
19665   //   |  D
19666   //   | /
19667   //   E
19668   //
19669   // A: X = ...; Y = ...
19670   // B: empty
19671   // C: Z = PHI [X, A], [Y, B]
19672   // D: empty
19673   // E: PHI [X, C], [Z, D]
19674   //
19675   // If we lower both CMOVs in a single step, we can instead generate:
19676   //
19677   //   A
19678   //   | \
19679   //   |  C
19680   //   | /|
19681   //   |/ |
19682   //   |  |
19683   //   |  D
19684   //   | /
19685   //   E
19686   //
19687   // A: X = ...; Y = ...
19688   // D: empty
19689   // E: PHI [X, A], [X, C], [Y, D]
19690   //
19691   // Which, in our sitofp/fcmp example, gives us something like:
19692   //
19693   //         ucomiss %xmm1, %xmm0
19694   //         movss  <1.0f>, %xmm0
19695   //         jne     .LBB5_4
19696   //         jp      .LBB5_4
19697   //         xorps   %xmm0, %xmm0
19698   // .LBB5_4:
19699   //         retq
19700   //
19701   MachineInstr *NextCMOV = nullptr;
19702   MachineBasicBlock::iterator NextMIIt =
19703       std::next(MachineBasicBlock::iterator(MI));
19704   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19705       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19706       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19707     NextCMOV = &*NextMIIt;
19708
19709   MachineBasicBlock *jcc1MBB = nullptr;
19710
19711   // If we have a double CMOV, we lower it to two successive branches to
19712   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19713   if (NextCMOV) {
19714     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19715     F->insert(It, jcc1MBB);
19716     jcc1MBB->addLiveIn(X86::EFLAGS);
19717   }
19718
19719   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19720   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19721   F->insert(It, copy0MBB);
19722   F->insert(It, sinkMBB);
19723
19724   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19725   // live into the sink and copy blocks.
19726   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19727
19728   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19729   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19730       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19731     copy0MBB->addLiveIn(X86::EFLAGS);
19732     sinkMBB->addLiveIn(X86::EFLAGS);
19733   }
19734
19735   // Transfer the remainder of BB and its successor edges to sinkMBB.
19736   sinkMBB->splice(sinkMBB->begin(), BB,
19737                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19738   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19739
19740   // Add the true and fallthrough blocks as its successors.
19741   if (NextCMOV) {
19742     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19743     BB->addSuccessor(jcc1MBB);
19744
19745     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19746     // jump to the sinkMBB.
19747     jcc1MBB->addSuccessor(copy0MBB);
19748     jcc1MBB->addSuccessor(sinkMBB);
19749   } else {
19750     BB->addSuccessor(copy0MBB);
19751   }
19752
19753   // The true block target of the first (or only) branch is always sinkMBB.
19754   BB->addSuccessor(sinkMBB);
19755
19756   // Create the conditional branch instruction.
19757   unsigned Opc =
19758     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19759   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19760
19761   if (NextCMOV) {
19762     unsigned Opc2 = X86::GetCondBranchFromCond(
19763         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19764     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19765   }
19766
19767   //  copy0MBB:
19768   //   %FalseValue = ...
19769   //   # fallthrough to sinkMBB
19770   copy0MBB->addSuccessor(sinkMBB);
19771
19772   //  sinkMBB:
19773   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19774   //  ...
19775   MachineInstrBuilder MIB =
19776       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19777               MI->getOperand(0).getReg())
19778           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19779           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19780
19781   // If we have a double CMOV, the second Jcc provides the same incoming
19782   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19783   if (NextCMOV) {
19784     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19785     // Copy the PHI result to the register defined by the second CMOV.
19786     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19787             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19788         .addReg(MI->getOperand(0).getReg());
19789     NextCMOV->eraseFromParent();
19790   }
19791
19792   MI->eraseFromParent();   // The pseudo instruction is gone now.
19793   return sinkMBB;
19794 }
19795
19796 MachineBasicBlock *
19797 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19798                                         MachineBasicBlock *BB) const {
19799   MachineFunction *MF = BB->getParent();
19800   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19801   DebugLoc DL = MI->getDebugLoc();
19802   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19803
19804   assert(MF->shouldSplitStack());
19805
19806   const bool Is64Bit = Subtarget->is64Bit();
19807   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19808
19809   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19810   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19811
19812   // BB:
19813   //  ... [Till the alloca]
19814   // If stacklet is not large enough, jump to mallocMBB
19815   //
19816   // bumpMBB:
19817   //  Allocate by subtracting from RSP
19818   //  Jump to continueMBB
19819   //
19820   // mallocMBB:
19821   //  Allocate by call to runtime
19822   //
19823   // continueMBB:
19824   //  ...
19825   //  [rest of original BB]
19826   //
19827
19828   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19829   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19830   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19831
19832   MachineRegisterInfo &MRI = MF->getRegInfo();
19833   const TargetRegisterClass *AddrRegClass =
19834     getRegClassFor(getPointerTy());
19835
19836   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19837     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19838     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19839     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19840     sizeVReg = MI->getOperand(1).getReg(),
19841     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19842
19843   MachineFunction::iterator MBBIter = BB;
19844   ++MBBIter;
19845
19846   MF->insert(MBBIter, bumpMBB);
19847   MF->insert(MBBIter, mallocMBB);
19848   MF->insert(MBBIter, continueMBB);
19849
19850   continueMBB->splice(continueMBB->begin(), BB,
19851                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19852   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19853
19854   // Add code to the main basic block to check if the stack limit has been hit,
19855   // and if so, jump to mallocMBB otherwise to bumpMBB.
19856   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19857   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19858     .addReg(tmpSPVReg).addReg(sizeVReg);
19859   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19860     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19861     .addReg(SPLimitVReg);
19862   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19863
19864   // bumpMBB simply decreases the stack pointer, since we know the current
19865   // stacklet has enough space.
19866   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19867     .addReg(SPLimitVReg);
19868   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19869     .addReg(SPLimitVReg);
19870   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19871
19872   // Calls into a routine in libgcc to allocate more space from the heap.
19873   const uint32_t *RegMask =
19874       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19875   if (IsLP64) {
19876     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19877       .addReg(sizeVReg);
19878     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19879       .addExternalSymbol("__morestack_allocate_stack_space")
19880       .addRegMask(RegMask)
19881       .addReg(X86::RDI, RegState::Implicit)
19882       .addReg(X86::RAX, RegState::ImplicitDefine);
19883   } else if (Is64Bit) {
19884     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19885       .addReg(sizeVReg);
19886     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19887       .addExternalSymbol("__morestack_allocate_stack_space")
19888       .addRegMask(RegMask)
19889       .addReg(X86::EDI, RegState::Implicit)
19890       .addReg(X86::EAX, RegState::ImplicitDefine);
19891   } else {
19892     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19893       .addImm(12);
19894     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19895     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19896       .addExternalSymbol("__morestack_allocate_stack_space")
19897       .addRegMask(RegMask)
19898       .addReg(X86::EAX, RegState::ImplicitDefine);
19899   }
19900
19901   if (!Is64Bit)
19902     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19903       .addImm(16);
19904
19905   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19906     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19907   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19908
19909   // Set up the CFG correctly.
19910   BB->addSuccessor(bumpMBB);
19911   BB->addSuccessor(mallocMBB);
19912   mallocMBB->addSuccessor(continueMBB);
19913   bumpMBB->addSuccessor(continueMBB);
19914
19915   // Take care of the PHI nodes.
19916   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19917           MI->getOperand(0).getReg())
19918     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19919     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19920
19921   // Delete the original pseudo instruction.
19922   MI->eraseFromParent();
19923
19924   // And we're done.
19925   return continueMBB;
19926 }
19927
19928 MachineBasicBlock *
19929 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19930                                         MachineBasicBlock *BB) const {
19931   DebugLoc DL = MI->getDebugLoc();
19932
19933   assert(!Subtarget->isTargetMachO());
19934
19935   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
19936                                                     DL);
19937
19938   MI->eraseFromParent();   // The pseudo instruction is gone now.
19939   return BB;
19940 }
19941
19942 MachineBasicBlock *
19943 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19944                                       MachineBasicBlock *BB) const {
19945   // This is pretty easy.  We're taking the value that we received from
19946   // our load from the relocation, sticking it in either RDI (x86-64)
19947   // or EAX and doing an indirect call.  The return value will then
19948   // be in the normal return register.
19949   MachineFunction *F = BB->getParent();
19950   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19951   DebugLoc DL = MI->getDebugLoc();
19952
19953   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19954   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19955
19956   // Get a register mask for the lowered call.
19957   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19958   // proper register mask.
19959   const uint32_t *RegMask =
19960       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19961   if (Subtarget->is64Bit()) {
19962     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19963                                       TII->get(X86::MOV64rm), X86::RDI)
19964     .addReg(X86::RIP)
19965     .addImm(0).addReg(0)
19966     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19967                       MI->getOperand(3).getTargetFlags())
19968     .addReg(0);
19969     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19970     addDirectMem(MIB, X86::RDI);
19971     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19972   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19973     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19974                                       TII->get(X86::MOV32rm), X86::EAX)
19975     .addReg(0)
19976     .addImm(0).addReg(0)
19977     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19978                       MI->getOperand(3).getTargetFlags())
19979     .addReg(0);
19980     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19981     addDirectMem(MIB, X86::EAX);
19982     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19983   } else {
19984     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19985                                       TII->get(X86::MOV32rm), X86::EAX)
19986     .addReg(TII->getGlobalBaseReg(F))
19987     .addImm(0).addReg(0)
19988     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19989                       MI->getOperand(3).getTargetFlags())
19990     .addReg(0);
19991     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19992     addDirectMem(MIB, X86::EAX);
19993     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19994   }
19995
19996   MI->eraseFromParent(); // The pseudo instruction is gone now.
19997   return BB;
19998 }
19999
20000 MachineBasicBlock *
20001 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20002                                     MachineBasicBlock *MBB) const {
20003   DebugLoc DL = MI->getDebugLoc();
20004   MachineFunction *MF = MBB->getParent();
20005   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20006   MachineRegisterInfo &MRI = MF->getRegInfo();
20007
20008   const BasicBlock *BB = MBB->getBasicBlock();
20009   MachineFunction::iterator I = MBB;
20010   ++I;
20011
20012   // Memory Reference
20013   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20014   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20015
20016   unsigned DstReg;
20017   unsigned MemOpndSlot = 0;
20018
20019   unsigned CurOp = 0;
20020
20021   DstReg = MI->getOperand(CurOp++).getReg();
20022   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20023   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20024   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20025   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20026
20027   MemOpndSlot = CurOp;
20028
20029   MVT PVT = getPointerTy();
20030   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20031          "Invalid Pointer Size!");
20032
20033   // For v = setjmp(buf), we generate
20034   //
20035   // thisMBB:
20036   //  buf[LabelOffset] = restoreMBB
20037   //  SjLjSetup restoreMBB
20038   //
20039   // mainMBB:
20040   //  v_main = 0
20041   //
20042   // sinkMBB:
20043   //  v = phi(main, restore)
20044   //
20045   // restoreMBB:
20046   //  if base pointer being used, load it from frame
20047   //  v_restore = 1
20048
20049   MachineBasicBlock *thisMBB = MBB;
20050   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20051   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20052   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20053   MF->insert(I, mainMBB);
20054   MF->insert(I, sinkMBB);
20055   MF->push_back(restoreMBB);
20056
20057   MachineInstrBuilder MIB;
20058
20059   // Transfer the remainder of BB and its successor edges to sinkMBB.
20060   sinkMBB->splice(sinkMBB->begin(), MBB,
20061                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20062   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20063
20064   // thisMBB:
20065   unsigned PtrStoreOpc = 0;
20066   unsigned LabelReg = 0;
20067   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20068   Reloc::Model RM = MF->getTarget().getRelocationModel();
20069   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20070                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20071
20072   // Prepare IP either in reg or imm.
20073   if (!UseImmLabel) {
20074     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20075     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20076     LabelReg = MRI.createVirtualRegister(PtrRC);
20077     if (Subtarget->is64Bit()) {
20078       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20079               .addReg(X86::RIP)
20080               .addImm(0)
20081               .addReg(0)
20082               .addMBB(restoreMBB)
20083               .addReg(0);
20084     } else {
20085       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20086       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20087               .addReg(XII->getGlobalBaseReg(MF))
20088               .addImm(0)
20089               .addReg(0)
20090               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20091               .addReg(0);
20092     }
20093   } else
20094     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20095   // Store IP
20096   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20097   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20098     if (i == X86::AddrDisp)
20099       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20100     else
20101       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20102   }
20103   if (!UseImmLabel)
20104     MIB.addReg(LabelReg);
20105   else
20106     MIB.addMBB(restoreMBB);
20107   MIB.setMemRefs(MMOBegin, MMOEnd);
20108   // Setup
20109   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20110           .addMBB(restoreMBB);
20111
20112   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20113   MIB.addRegMask(RegInfo->getNoPreservedMask());
20114   thisMBB->addSuccessor(mainMBB);
20115   thisMBB->addSuccessor(restoreMBB);
20116
20117   // mainMBB:
20118   //  EAX = 0
20119   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20120   mainMBB->addSuccessor(sinkMBB);
20121
20122   // sinkMBB:
20123   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20124           TII->get(X86::PHI), DstReg)
20125     .addReg(mainDstReg).addMBB(mainMBB)
20126     .addReg(restoreDstReg).addMBB(restoreMBB);
20127
20128   // restoreMBB:
20129   if (RegInfo->hasBasePointer(*MF)) {
20130     const bool Uses64BitFramePtr =
20131         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20132     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20133     X86FI->setRestoreBasePointer(MF);
20134     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20135     unsigned BasePtr = RegInfo->getBaseRegister();
20136     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20137     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20138                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20139       .setMIFlag(MachineInstr::FrameSetup);
20140   }
20141   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20142   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20143   restoreMBB->addSuccessor(sinkMBB);
20144
20145   MI->eraseFromParent();
20146   return sinkMBB;
20147 }
20148
20149 MachineBasicBlock *
20150 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20151                                      MachineBasicBlock *MBB) const {
20152   DebugLoc DL = MI->getDebugLoc();
20153   MachineFunction *MF = MBB->getParent();
20154   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20155   MachineRegisterInfo &MRI = MF->getRegInfo();
20156
20157   // Memory Reference
20158   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20159   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20160
20161   MVT PVT = getPointerTy();
20162   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20163          "Invalid Pointer Size!");
20164
20165   const TargetRegisterClass *RC =
20166     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20167   unsigned Tmp = MRI.createVirtualRegister(RC);
20168   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20169   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20170   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20171   unsigned SP = RegInfo->getStackRegister();
20172
20173   MachineInstrBuilder MIB;
20174
20175   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20176   const int64_t SPOffset = 2 * PVT.getStoreSize();
20177
20178   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20179   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20180
20181   // Reload FP
20182   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20183   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20184     MIB.addOperand(MI->getOperand(i));
20185   MIB.setMemRefs(MMOBegin, MMOEnd);
20186   // Reload IP
20187   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20188   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20189     if (i == X86::AddrDisp)
20190       MIB.addDisp(MI->getOperand(i), LabelOffset);
20191     else
20192       MIB.addOperand(MI->getOperand(i));
20193   }
20194   MIB.setMemRefs(MMOBegin, MMOEnd);
20195   // Reload SP
20196   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20197   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20198     if (i == X86::AddrDisp)
20199       MIB.addDisp(MI->getOperand(i), SPOffset);
20200     else
20201       MIB.addOperand(MI->getOperand(i));
20202   }
20203   MIB.setMemRefs(MMOBegin, MMOEnd);
20204   // Jump
20205   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20206
20207   MI->eraseFromParent();
20208   return MBB;
20209 }
20210
20211 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20212 // accumulator loops. Writing back to the accumulator allows the coalescer
20213 // to remove extra copies in the loop.
20214 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20215 MachineBasicBlock *
20216 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20217                                  MachineBasicBlock *MBB) const {
20218   MachineOperand &AddendOp = MI->getOperand(3);
20219
20220   // Bail out early if the addend isn't a register - we can't switch these.
20221   if (!AddendOp.isReg())
20222     return MBB;
20223
20224   MachineFunction &MF = *MBB->getParent();
20225   MachineRegisterInfo &MRI = MF.getRegInfo();
20226
20227   // Check whether the addend is defined by a PHI:
20228   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20229   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20230   if (!AddendDef.isPHI())
20231     return MBB;
20232
20233   // Look for the following pattern:
20234   // loop:
20235   //   %addend = phi [%entry, 0], [%loop, %result]
20236   //   ...
20237   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20238
20239   // Replace with:
20240   //   loop:
20241   //   %addend = phi [%entry, 0], [%loop, %result]
20242   //   ...
20243   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20244
20245   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20246     assert(AddendDef.getOperand(i).isReg());
20247     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20248     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20249     if (&PHISrcInst == MI) {
20250       // Found a matching instruction.
20251       unsigned NewFMAOpc = 0;
20252       switch (MI->getOpcode()) {
20253         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20254         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20255         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20256         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20257         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20258         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20259         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20260         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20261         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20262         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20263         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20264         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20265         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20266         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20267         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20268         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20269         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20270         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20271         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20272         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20273
20274         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20275         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20276         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20277         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20278         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20279         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20280         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20281         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20282         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20283         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20284         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20285         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20286         default: llvm_unreachable("Unrecognized FMA variant.");
20287       }
20288
20289       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20290       MachineInstrBuilder MIB =
20291         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20292         .addOperand(MI->getOperand(0))
20293         .addOperand(MI->getOperand(3))
20294         .addOperand(MI->getOperand(2))
20295         .addOperand(MI->getOperand(1));
20296       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20297       MI->eraseFromParent();
20298     }
20299   }
20300
20301   return MBB;
20302 }
20303
20304 MachineBasicBlock *
20305 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20306                                                MachineBasicBlock *BB) const {
20307   switch (MI->getOpcode()) {
20308   default: llvm_unreachable("Unexpected instr type to insert");
20309   case X86::TAILJMPd64:
20310   case X86::TAILJMPr64:
20311   case X86::TAILJMPm64:
20312   case X86::TAILJMPd64_REX:
20313   case X86::TAILJMPr64_REX:
20314   case X86::TAILJMPm64_REX:
20315     llvm_unreachable("TAILJMP64 would not be touched here.");
20316   case X86::TCRETURNdi64:
20317   case X86::TCRETURNri64:
20318   case X86::TCRETURNmi64:
20319     return BB;
20320   case X86::WIN_ALLOCA:
20321     return EmitLoweredWinAlloca(MI, BB);
20322   case X86::SEG_ALLOCA_32:
20323   case X86::SEG_ALLOCA_64:
20324     return EmitLoweredSegAlloca(MI, BB);
20325   case X86::TLSCall_32:
20326   case X86::TLSCall_64:
20327     return EmitLoweredTLSCall(MI, BB);
20328   case X86::CMOV_GR8:
20329   case X86::CMOV_FR32:
20330   case X86::CMOV_FR64:
20331   case X86::CMOV_V4F32:
20332   case X86::CMOV_V2F64:
20333   case X86::CMOV_V2I64:
20334   case X86::CMOV_V8F32:
20335   case X86::CMOV_V4F64:
20336   case X86::CMOV_V4I64:
20337   case X86::CMOV_V16F32:
20338   case X86::CMOV_V8F64:
20339   case X86::CMOV_V8I64:
20340   case X86::CMOV_GR16:
20341   case X86::CMOV_GR32:
20342   case X86::CMOV_RFP32:
20343   case X86::CMOV_RFP64:
20344   case X86::CMOV_RFP80:
20345   case X86::CMOV_V8I1:
20346   case X86::CMOV_V16I1:
20347   case X86::CMOV_V32I1:
20348   case X86::CMOV_V64I1:
20349     return EmitLoweredSelect(MI, BB);
20350
20351   case X86::FP32_TO_INT16_IN_MEM:
20352   case X86::FP32_TO_INT32_IN_MEM:
20353   case X86::FP32_TO_INT64_IN_MEM:
20354   case X86::FP64_TO_INT16_IN_MEM:
20355   case X86::FP64_TO_INT32_IN_MEM:
20356   case X86::FP64_TO_INT64_IN_MEM:
20357   case X86::FP80_TO_INT16_IN_MEM:
20358   case X86::FP80_TO_INT32_IN_MEM:
20359   case X86::FP80_TO_INT64_IN_MEM: {
20360     MachineFunction *F = BB->getParent();
20361     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20362     DebugLoc DL = MI->getDebugLoc();
20363
20364     // Change the floating point control register to use "round towards zero"
20365     // mode when truncating to an integer value.
20366     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20367     addFrameReference(BuildMI(*BB, MI, DL,
20368                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20369
20370     // Load the old value of the high byte of the control word...
20371     unsigned OldCW =
20372       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20373     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20374                       CWFrameIdx);
20375
20376     // Set the high part to be round to zero...
20377     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20378       .addImm(0xC7F);
20379
20380     // Reload the modified control word now...
20381     addFrameReference(BuildMI(*BB, MI, DL,
20382                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20383
20384     // Restore the memory image of control word to original value
20385     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20386       .addReg(OldCW);
20387
20388     // Get the X86 opcode to use.
20389     unsigned Opc;
20390     switch (MI->getOpcode()) {
20391     default: llvm_unreachable("illegal opcode!");
20392     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20393     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20394     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20395     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20396     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20397     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20398     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20399     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20400     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20401     }
20402
20403     X86AddressMode AM;
20404     MachineOperand &Op = MI->getOperand(0);
20405     if (Op.isReg()) {
20406       AM.BaseType = X86AddressMode::RegBase;
20407       AM.Base.Reg = Op.getReg();
20408     } else {
20409       AM.BaseType = X86AddressMode::FrameIndexBase;
20410       AM.Base.FrameIndex = Op.getIndex();
20411     }
20412     Op = MI->getOperand(1);
20413     if (Op.isImm())
20414       AM.Scale = Op.getImm();
20415     Op = MI->getOperand(2);
20416     if (Op.isImm())
20417       AM.IndexReg = Op.getImm();
20418     Op = MI->getOperand(3);
20419     if (Op.isGlobal()) {
20420       AM.GV = Op.getGlobal();
20421     } else {
20422       AM.Disp = Op.getImm();
20423     }
20424     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20425                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20426
20427     // Reload the original control word now.
20428     addFrameReference(BuildMI(*BB, MI, DL,
20429                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20430
20431     MI->eraseFromParent();   // The pseudo instruction is gone now.
20432     return BB;
20433   }
20434     // String/text processing lowering.
20435   case X86::PCMPISTRM128REG:
20436   case X86::VPCMPISTRM128REG:
20437   case X86::PCMPISTRM128MEM:
20438   case X86::VPCMPISTRM128MEM:
20439   case X86::PCMPESTRM128REG:
20440   case X86::VPCMPESTRM128REG:
20441   case X86::PCMPESTRM128MEM:
20442   case X86::VPCMPESTRM128MEM:
20443     assert(Subtarget->hasSSE42() &&
20444            "Target must have SSE4.2 or AVX features enabled");
20445     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20446
20447   // String/text processing lowering.
20448   case X86::PCMPISTRIREG:
20449   case X86::VPCMPISTRIREG:
20450   case X86::PCMPISTRIMEM:
20451   case X86::VPCMPISTRIMEM:
20452   case X86::PCMPESTRIREG:
20453   case X86::VPCMPESTRIREG:
20454   case X86::PCMPESTRIMEM:
20455   case X86::VPCMPESTRIMEM:
20456     assert(Subtarget->hasSSE42() &&
20457            "Target must have SSE4.2 or AVX features enabled");
20458     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20459
20460   // Thread synchronization.
20461   case X86::MONITOR:
20462     return EmitMonitor(MI, BB, Subtarget);
20463
20464   // xbegin
20465   case X86::XBEGIN:
20466     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20467
20468   case X86::VASTART_SAVE_XMM_REGS:
20469     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20470
20471   case X86::VAARG_64:
20472     return EmitVAARG64WithCustomInserter(MI, BB);
20473
20474   case X86::EH_SjLj_SetJmp32:
20475   case X86::EH_SjLj_SetJmp64:
20476     return emitEHSjLjSetJmp(MI, BB);
20477
20478   case X86::EH_SjLj_LongJmp32:
20479   case X86::EH_SjLj_LongJmp64:
20480     return emitEHSjLjLongJmp(MI, BB);
20481
20482   case TargetOpcode::STATEPOINT:
20483     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20484     // this point in the process.  We diverge later.
20485     return emitPatchPoint(MI, BB);
20486
20487   case TargetOpcode::STACKMAP:
20488   case TargetOpcode::PATCHPOINT:
20489     return emitPatchPoint(MI, BB);
20490
20491   case X86::VFMADDPDr213r:
20492   case X86::VFMADDPSr213r:
20493   case X86::VFMADDSDr213r:
20494   case X86::VFMADDSSr213r:
20495   case X86::VFMSUBPDr213r:
20496   case X86::VFMSUBPSr213r:
20497   case X86::VFMSUBSDr213r:
20498   case X86::VFMSUBSSr213r:
20499   case X86::VFNMADDPDr213r:
20500   case X86::VFNMADDPSr213r:
20501   case X86::VFNMADDSDr213r:
20502   case X86::VFNMADDSSr213r:
20503   case X86::VFNMSUBPDr213r:
20504   case X86::VFNMSUBPSr213r:
20505   case X86::VFNMSUBSDr213r:
20506   case X86::VFNMSUBSSr213r:
20507   case X86::VFMADDSUBPDr213r:
20508   case X86::VFMADDSUBPSr213r:
20509   case X86::VFMSUBADDPDr213r:
20510   case X86::VFMSUBADDPSr213r:
20511   case X86::VFMADDPDr213rY:
20512   case X86::VFMADDPSr213rY:
20513   case X86::VFMSUBPDr213rY:
20514   case X86::VFMSUBPSr213rY:
20515   case X86::VFNMADDPDr213rY:
20516   case X86::VFNMADDPSr213rY:
20517   case X86::VFNMSUBPDr213rY:
20518   case X86::VFNMSUBPSr213rY:
20519   case X86::VFMADDSUBPDr213rY:
20520   case X86::VFMADDSUBPSr213rY:
20521   case X86::VFMSUBADDPDr213rY:
20522   case X86::VFMSUBADDPSr213rY:
20523     return emitFMA3Instr(MI, BB);
20524   }
20525 }
20526
20527 //===----------------------------------------------------------------------===//
20528 //                           X86 Optimization Hooks
20529 //===----------------------------------------------------------------------===//
20530
20531 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20532                                                       APInt &KnownZero,
20533                                                       APInt &KnownOne,
20534                                                       const SelectionDAG &DAG,
20535                                                       unsigned Depth) const {
20536   unsigned BitWidth = KnownZero.getBitWidth();
20537   unsigned Opc = Op.getOpcode();
20538   assert((Opc >= ISD::BUILTIN_OP_END ||
20539           Opc == ISD::INTRINSIC_WO_CHAIN ||
20540           Opc == ISD::INTRINSIC_W_CHAIN ||
20541           Opc == ISD::INTRINSIC_VOID) &&
20542          "Should use MaskedValueIsZero if you don't know whether Op"
20543          " is a target node!");
20544
20545   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20546   switch (Opc) {
20547   default: break;
20548   case X86ISD::ADD:
20549   case X86ISD::SUB:
20550   case X86ISD::ADC:
20551   case X86ISD::SBB:
20552   case X86ISD::SMUL:
20553   case X86ISD::UMUL:
20554   case X86ISD::INC:
20555   case X86ISD::DEC:
20556   case X86ISD::OR:
20557   case X86ISD::XOR:
20558   case X86ISD::AND:
20559     // These nodes' second result is a boolean.
20560     if (Op.getResNo() == 0)
20561       break;
20562     // Fallthrough
20563   case X86ISD::SETCC:
20564     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20565     break;
20566   case ISD::INTRINSIC_WO_CHAIN: {
20567     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20568     unsigned NumLoBits = 0;
20569     switch (IntId) {
20570     default: break;
20571     case Intrinsic::x86_sse_movmsk_ps:
20572     case Intrinsic::x86_avx_movmsk_ps_256:
20573     case Intrinsic::x86_sse2_movmsk_pd:
20574     case Intrinsic::x86_avx_movmsk_pd_256:
20575     case Intrinsic::x86_mmx_pmovmskb:
20576     case Intrinsic::x86_sse2_pmovmskb_128:
20577     case Intrinsic::x86_avx2_pmovmskb: {
20578       // High bits of movmskp{s|d}, pmovmskb are known zero.
20579       switch (IntId) {
20580         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20581         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20582         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20583         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20584         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20585         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20586         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20587         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20588       }
20589       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20590       break;
20591     }
20592     }
20593     break;
20594   }
20595   }
20596 }
20597
20598 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20599   SDValue Op,
20600   const SelectionDAG &,
20601   unsigned Depth) const {
20602   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20603   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20604     return Op.getValueType().getScalarType().getSizeInBits();
20605
20606   // Fallback case.
20607   return 1;
20608 }
20609
20610 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20611 /// node is a GlobalAddress + offset.
20612 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20613                                        const GlobalValue* &GA,
20614                                        int64_t &Offset) const {
20615   if (N->getOpcode() == X86ISD::Wrapper) {
20616     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20617       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20618       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20619       return true;
20620     }
20621   }
20622   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20623 }
20624
20625 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20626 /// same as extracting the high 128-bit part of 256-bit vector and then
20627 /// inserting the result into the low part of a new 256-bit vector
20628 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20629   EVT VT = SVOp->getValueType(0);
20630   unsigned NumElems = VT.getVectorNumElements();
20631
20632   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20633   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20634     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20635         SVOp->getMaskElt(j) >= 0)
20636       return false;
20637
20638   return true;
20639 }
20640
20641 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20642 /// same as extracting the low 128-bit part of 256-bit vector and then
20643 /// inserting the result into the high part of a new 256-bit vector
20644 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20645   EVT VT = SVOp->getValueType(0);
20646   unsigned NumElems = VT.getVectorNumElements();
20647
20648   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20649   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20650     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20651         SVOp->getMaskElt(j) >= 0)
20652       return false;
20653
20654   return true;
20655 }
20656
20657 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20658 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20659                                         TargetLowering::DAGCombinerInfo &DCI,
20660                                         const X86Subtarget* Subtarget) {
20661   SDLoc dl(N);
20662   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20663   SDValue V1 = SVOp->getOperand(0);
20664   SDValue V2 = SVOp->getOperand(1);
20665   EVT VT = SVOp->getValueType(0);
20666   unsigned NumElems = VT.getVectorNumElements();
20667
20668   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20669       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20670     //
20671     //                   0,0,0,...
20672     //                      |
20673     //    V      UNDEF    BUILD_VECTOR    UNDEF
20674     //     \      /           \           /
20675     //  CONCAT_VECTOR         CONCAT_VECTOR
20676     //         \                  /
20677     //          \                /
20678     //          RESULT: V + zero extended
20679     //
20680     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20681         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20682         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20683       return SDValue();
20684
20685     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20686       return SDValue();
20687
20688     // To match the shuffle mask, the first half of the mask should
20689     // be exactly the first vector, and all the rest a splat with the
20690     // first element of the second one.
20691     for (unsigned i = 0; i != NumElems/2; ++i)
20692       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20693           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20694         return SDValue();
20695
20696     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20697     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20698       if (Ld->hasNUsesOfValue(1, 0)) {
20699         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20700         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20701         SDValue ResNode =
20702           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20703                                   Ld->getMemoryVT(),
20704                                   Ld->getPointerInfo(),
20705                                   Ld->getAlignment(),
20706                                   false/*isVolatile*/, true/*ReadMem*/,
20707                                   false/*WriteMem*/);
20708
20709         // Make sure the newly-created LOAD is in the same position as Ld in
20710         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20711         // and update uses of Ld's output chain to use the TokenFactor.
20712         if (Ld->hasAnyUseOfValue(1)) {
20713           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20714                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20715           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20716           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20717                                  SDValue(ResNode.getNode(), 1));
20718         }
20719
20720         return DAG.getBitcast(VT, ResNode);
20721       }
20722     }
20723
20724     // Emit a zeroed vector and insert the desired subvector on its
20725     // first half.
20726     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20727     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20728     return DCI.CombineTo(N, InsV);
20729   }
20730
20731   //===--------------------------------------------------------------------===//
20732   // Combine some shuffles into subvector extracts and inserts:
20733   //
20734
20735   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20736   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20737     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20738     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20739     return DCI.CombineTo(N, InsV);
20740   }
20741
20742   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20743   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20744     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20745     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20746     return DCI.CombineTo(N, InsV);
20747   }
20748
20749   return SDValue();
20750 }
20751
20752 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20753 /// possible.
20754 ///
20755 /// This is the leaf of the recursive combinine below. When we have found some
20756 /// chain of single-use x86 shuffle instructions and accumulated the combined
20757 /// shuffle mask represented by them, this will try to pattern match that mask
20758 /// into either a single instruction if there is a special purpose instruction
20759 /// for this operation, or into a PSHUFB instruction which is a fully general
20760 /// instruction but should only be used to replace chains over a certain depth.
20761 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20762                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20763                                    TargetLowering::DAGCombinerInfo &DCI,
20764                                    const X86Subtarget *Subtarget) {
20765   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20766
20767   // Find the operand that enters the chain. Note that multiple uses are OK
20768   // here, we're not going to remove the operand we find.
20769   SDValue Input = Op.getOperand(0);
20770   while (Input.getOpcode() == ISD::BITCAST)
20771     Input = Input.getOperand(0);
20772
20773   MVT VT = Input.getSimpleValueType();
20774   MVT RootVT = Root.getSimpleValueType();
20775   SDLoc DL(Root);
20776
20777   // Just remove no-op shuffle masks.
20778   if (Mask.size() == 1) {
20779     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20780                   /*AddTo*/ true);
20781     return true;
20782   }
20783
20784   // Use the float domain if the operand type is a floating point type.
20785   bool FloatDomain = VT.isFloatingPoint();
20786
20787   // For floating point shuffles, we don't have free copies in the shuffle
20788   // instructions or the ability to load as part of the instruction, so
20789   // canonicalize their shuffles to UNPCK or MOV variants.
20790   //
20791   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20792   // vectors because it can have a load folded into it that UNPCK cannot. This
20793   // doesn't preclude something switching to the shorter encoding post-RA.
20794   //
20795   // FIXME: Should teach these routines about AVX vector widths.
20796   if (FloatDomain && VT.getSizeInBits() == 128) {
20797     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20798       bool Lo = Mask.equals({0, 0});
20799       unsigned Shuffle;
20800       MVT ShuffleVT;
20801       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20802       // is no slower than UNPCKLPD but has the option to fold the input operand
20803       // into even an unaligned memory load.
20804       if (Lo && Subtarget->hasSSE3()) {
20805         Shuffle = X86ISD::MOVDDUP;
20806         ShuffleVT = MVT::v2f64;
20807       } else {
20808         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20809         // than the UNPCK variants.
20810         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20811         ShuffleVT = MVT::v4f32;
20812       }
20813       if (Depth == 1 && Root->getOpcode() == Shuffle)
20814         return false; // Nothing to do!
20815       Op = DAG.getBitcast(ShuffleVT, Input);
20816       DCI.AddToWorklist(Op.getNode());
20817       if (Shuffle == X86ISD::MOVDDUP)
20818         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20819       else
20820         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20821       DCI.AddToWorklist(Op.getNode());
20822       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20823                     /*AddTo*/ true);
20824       return true;
20825     }
20826     if (Subtarget->hasSSE3() &&
20827         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20828       bool Lo = Mask.equals({0, 0, 2, 2});
20829       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20830       MVT ShuffleVT = MVT::v4f32;
20831       if (Depth == 1 && Root->getOpcode() == Shuffle)
20832         return false; // Nothing to do!
20833       Op = DAG.getBitcast(ShuffleVT, Input);
20834       DCI.AddToWorklist(Op.getNode());
20835       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20836       DCI.AddToWorklist(Op.getNode());
20837       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20838                     /*AddTo*/ true);
20839       return true;
20840     }
20841     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20842       bool Lo = Mask.equals({0, 0, 1, 1});
20843       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20844       MVT ShuffleVT = MVT::v4f32;
20845       if (Depth == 1 && Root->getOpcode() == Shuffle)
20846         return false; // Nothing to do!
20847       Op = DAG.getBitcast(ShuffleVT, Input);
20848       DCI.AddToWorklist(Op.getNode());
20849       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20850       DCI.AddToWorklist(Op.getNode());
20851       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20852                     /*AddTo*/ true);
20853       return true;
20854     }
20855   }
20856
20857   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20858   // variants as none of these have single-instruction variants that are
20859   // superior to the UNPCK formulation.
20860   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20861       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20862        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20863        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20864        Mask.equals(
20865            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20866     bool Lo = Mask[0] == 0;
20867     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20868     if (Depth == 1 && Root->getOpcode() == Shuffle)
20869       return false; // Nothing to do!
20870     MVT ShuffleVT;
20871     switch (Mask.size()) {
20872     case 8:
20873       ShuffleVT = MVT::v8i16;
20874       break;
20875     case 16:
20876       ShuffleVT = MVT::v16i8;
20877       break;
20878     default:
20879       llvm_unreachable("Impossible mask size!");
20880     };
20881     Op = DAG.getBitcast(ShuffleVT, Input);
20882     DCI.AddToWorklist(Op.getNode());
20883     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20884     DCI.AddToWorklist(Op.getNode());
20885     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20886                   /*AddTo*/ true);
20887     return true;
20888   }
20889
20890   // Don't try to re-form single instruction chains under any circumstances now
20891   // that we've done encoding canonicalization for them.
20892   if (Depth < 2)
20893     return false;
20894
20895   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20896   // can replace them with a single PSHUFB instruction profitably. Intel's
20897   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20898   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20899   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20900     SmallVector<SDValue, 16> PSHUFBMask;
20901     int NumBytes = VT.getSizeInBits() / 8;
20902     int Ratio = NumBytes / Mask.size();
20903     for (int i = 0; i < NumBytes; ++i) {
20904       if (Mask[i / Ratio] == SM_SentinelUndef) {
20905         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20906         continue;
20907       }
20908       int M = Mask[i / Ratio] != SM_SentinelZero
20909                   ? Ratio * Mask[i / Ratio] + i % Ratio
20910                   : 255;
20911       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20912     }
20913     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20914     Op = DAG.getBitcast(ByteVT, Input);
20915     DCI.AddToWorklist(Op.getNode());
20916     SDValue PSHUFBMaskOp =
20917         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20918     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20919     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20920     DCI.AddToWorklist(Op.getNode());
20921     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20922                   /*AddTo*/ true);
20923     return true;
20924   }
20925
20926   // Failed to find any combines.
20927   return false;
20928 }
20929
20930 /// \brief Fully generic combining of x86 shuffle instructions.
20931 ///
20932 /// This should be the last combine run over the x86 shuffle instructions. Once
20933 /// they have been fully optimized, this will recursively consider all chains
20934 /// of single-use shuffle instructions, build a generic model of the cumulative
20935 /// shuffle operation, and check for simpler instructions which implement this
20936 /// operation. We use this primarily for two purposes:
20937 ///
20938 /// 1) Collapse generic shuffles to specialized single instructions when
20939 ///    equivalent. In most cases, this is just an encoding size win, but
20940 ///    sometimes we will collapse multiple generic shuffles into a single
20941 ///    special-purpose shuffle.
20942 /// 2) Look for sequences of shuffle instructions with 3 or more total
20943 ///    instructions, and replace them with the slightly more expensive SSSE3
20944 ///    PSHUFB instruction if available. We do this as the last combining step
20945 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20946 ///    a suitable short sequence of other instructions. The PHUFB will either
20947 ///    use a register or have to read from memory and so is slightly (but only
20948 ///    slightly) more expensive than the other shuffle instructions.
20949 ///
20950 /// Because this is inherently a quadratic operation (for each shuffle in
20951 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20952 /// This should never be an issue in practice as the shuffle lowering doesn't
20953 /// produce sequences of more than 8 instructions.
20954 ///
20955 /// FIXME: We will currently miss some cases where the redundant shuffling
20956 /// would simplify under the threshold for PSHUFB formation because of
20957 /// combine-ordering. To fix this, we should do the redundant instruction
20958 /// combining in this recursive walk.
20959 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20960                                           ArrayRef<int> RootMask,
20961                                           int Depth, bool HasPSHUFB,
20962                                           SelectionDAG &DAG,
20963                                           TargetLowering::DAGCombinerInfo &DCI,
20964                                           const X86Subtarget *Subtarget) {
20965   // Bound the depth of our recursive combine because this is ultimately
20966   // quadratic in nature.
20967   if (Depth > 8)
20968     return false;
20969
20970   // Directly rip through bitcasts to find the underlying operand.
20971   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20972     Op = Op.getOperand(0);
20973
20974   MVT VT = Op.getSimpleValueType();
20975   if (!VT.isVector())
20976     return false; // Bail if we hit a non-vector.
20977
20978   assert(Root.getSimpleValueType().isVector() &&
20979          "Shuffles operate on vector types!");
20980   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20981          "Can only combine shuffles of the same vector register size.");
20982
20983   if (!isTargetShuffle(Op.getOpcode()))
20984     return false;
20985   SmallVector<int, 16> OpMask;
20986   bool IsUnary;
20987   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20988   // We only can combine unary shuffles which we can decode the mask for.
20989   if (!HaveMask || !IsUnary)
20990     return false;
20991
20992   assert(VT.getVectorNumElements() == OpMask.size() &&
20993          "Different mask size from vector size!");
20994   assert(((RootMask.size() > OpMask.size() &&
20995            RootMask.size() % OpMask.size() == 0) ||
20996           (OpMask.size() > RootMask.size() &&
20997            OpMask.size() % RootMask.size() == 0) ||
20998           OpMask.size() == RootMask.size()) &&
20999          "The smaller number of elements must divide the larger.");
21000   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21001   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21002   assert(((RootRatio == 1 && OpRatio == 1) ||
21003           (RootRatio == 1) != (OpRatio == 1)) &&
21004          "Must not have a ratio for both incoming and op masks!");
21005
21006   SmallVector<int, 16> Mask;
21007   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21008
21009   // Merge this shuffle operation's mask into our accumulated mask. Note that
21010   // this shuffle's mask will be the first applied to the input, followed by the
21011   // root mask to get us all the way to the root value arrangement. The reason
21012   // for this order is that we are recursing up the operation chain.
21013   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21014     int RootIdx = i / RootRatio;
21015     if (RootMask[RootIdx] < 0) {
21016       // This is a zero or undef lane, we're done.
21017       Mask.push_back(RootMask[RootIdx]);
21018       continue;
21019     }
21020
21021     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21022     int OpIdx = RootMaskedIdx / OpRatio;
21023     if (OpMask[OpIdx] < 0) {
21024       // The incoming lanes are zero or undef, it doesn't matter which ones we
21025       // are using.
21026       Mask.push_back(OpMask[OpIdx]);
21027       continue;
21028     }
21029
21030     // Ok, we have non-zero lanes, map them through.
21031     Mask.push_back(OpMask[OpIdx] * OpRatio +
21032                    RootMaskedIdx % OpRatio);
21033   }
21034
21035   // See if we can recurse into the operand to combine more things.
21036   switch (Op.getOpcode()) {
21037     case X86ISD::PSHUFB:
21038       HasPSHUFB = true;
21039     case X86ISD::PSHUFD:
21040     case X86ISD::PSHUFHW:
21041     case X86ISD::PSHUFLW:
21042       if (Op.getOperand(0).hasOneUse() &&
21043           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21044                                         HasPSHUFB, DAG, DCI, Subtarget))
21045         return true;
21046       break;
21047
21048     case X86ISD::UNPCKL:
21049     case X86ISD::UNPCKH:
21050       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21051       // We can't check for single use, we have to check that this shuffle is the only user.
21052       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21053           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21054                                         HasPSHUFB, DAG, DCI, Subtarget))
21055           return true;
21056       break;
21057   }
21058
21059   // Minor canonicalization of the accumulated shuffle mask to make it easier
21060   // to match below. All this does is detect masks with squential pairs of
21061   // elements, and shrink them to the half-width mask. It does this in a loop
21062   // so it will reduce the size of the mask to the minimal width mask which
21063   // performs an equivalent shuffle.
21064   SmallVector<int, 16> WidenedMask;
21065   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21066     Mask = std::move(WidenedMask);
21067     WidenedMask.clear();
21068   }
21069
21070   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21071                                 Subtarget);
21072 }
21073
21074 /// \brief Get the PSHUF-style mask from PSHUF node.
21075 ///
21076 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21077 /// PSHUF-style masks that can be reused with such instructions.
21078 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21079   MVT VT = N.getSimpleValueType();
21080   SmallVector<int, 4> Mask;
21081   bool IsUnary;
21082   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21083   (void)HaveMask;
21084   assert(HaveMask);
21085
21086   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21087   // matter. Check that the upper masks are repeats and remove them.
21088   if (VT.getSizeInBits() > 128) {
21089     int LaneElts = 128 / VT.getScalarSizeInBits();
21090 #ifndef NDEBUG
21091     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21092       for (int j = 0; j < LaneElts; ++j)
21093         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21094                "Mask doesn't repeat in high 128-bit lanes!");
21095 #endif
21096     Mask.resize(LaneElts);
21097   }
21098
21099   switch (N.getOpcode()) {
21100   case X86ISD::PSHUFD:
21101     return Mask;
21102   case X86ISD::PSHUFLW:
21103     Mask.resize(4);
21104     return Mask;
21105   case X86ISD::PSHUFHW:
21106     Mask.erase(Mask.begin(), Mask.begin() + 4);
21107     for (int &M : Mask)
21108       M -= 4;
21109     return Mask;
21110   default:
21111     llvm_unreachable("No valid shuffle instruction found!");
21112   }
21113 }
21114
21115 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21116 ///
21117 /// We walk up the chain and look for a combinable shuffle, skipping over
21118 /// shuffles that we could hoist this shuffle's transformation past without
21119 /// altering anything.
21120 static SDValue
21121 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21122                              SelectionDAG &DAG,
21123                              TargetLowering::DAGCombinerInfo &DCI) {
21124   assert(N.getOpcode() == X86ISD::PSHUFD &&
21125          "Called with something other than an x86 128-bit half shuffle!");
21126   SDLoc DL(N);
21127
21128   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21129   // of the shuffles in the chain so that we can form a fresh chain to replace
21130   // this one.
21131   SmallVector<SDValue, 8> Chain;
21132   SDValue V = N.getOperand(0);
21133   for (; V.hasOneUse(); V = V.getOperand(0)) {
21134     switch (V.getOpcode()) {
21135     default:
21136       return SDValue(); // Nothing combined!
21137
21138     case ISD::BITCAST:
21139       // Skip bitcasts as we always know the type for the target specific
21140       // instructions.
21141       continue;
21142
21143     case X86ISD::PSHUFD:
21144       // Found another dword shuffle.
21145       break;
21146
21147     case X86ISD::PSHUFLW:
21148       // Check that the low words (being shuffled) are the identity in the
21149       // dword shuffle, and the high words are self-contained.
21150       if (Mask[0] != 0 || Mask[1] != 1 ||
21151           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21152         return SDValue();
21153
21154       Chain.push_back(V);
21155       continue;
21156
21157     case X86ISD::PSHUFHW:
21158       // Check that the high words (being shuffled) are the identity in the
21159       // dword shuffle, and the low words are self-contained.
21160       if (Mask[2] != 2 || Mask[3] != 3 ||
21161           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21162         return SDValue();
21163
21164       Chain.push_back(V);
21165       continue;
21166
21167     case X86ISD::UNPCKL:
21168     case X86ISD::UNPCKH:
21169       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21170       // shuffle into a preceding word shuffle.
21171       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21172           V.getSimpleValueType().getScalarType() != MVT::i16)
21173         return SDValue();
21174
21175       // Search for a half-shuffle which we can combine with.
21176       unsigned CombineOp =
21177           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21178       if (V.getOperand(0) != V.getOperand(1) ||
21179           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21180         return SDValue();
21181       Chain.push_back(V);
21182       V = V.getOperand(0);
21183       do {
21184         switch (V.getOpcode()) {
21185         default:
21186           return SDValue(); // Nothing to combine.
21187
21188         case X86ISD::PSHUFLW:
21189         case X86ISD::PSHUFHW:
21190           if (V.getOpcode() == CombineOp)
21191             break;
21192
21193           Chain.push_back(V);
21194
21195           // Fallthrough!
21196         case ISD::BITCAST:
21197           V = V.getOperand(0);
21198           continue;
21199         }
21200         break;
21201       } while (V.hasOneUse());
21202       break;
21203     }
21204     // Break out of the loop if we break out of the switch.
21205     break;
21206   }
21207
21208   if (!V.hasOneUse())
21209     // We fell out of the loop without finding a viable combining instruction.
21210     return SDValue();
21211
21212   // Merge this node's mask and our incoming mask.
21213   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21214   for (int &M : Mask)
21215     M = VMask[M];
21216   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21217                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21218
21219   // Rebuild the chain around this new shuffle.
21220   while (!Chain.empty()) {
21221     SDValue W = Chain.pop_back_val();
21222
21223     if (V.getValueType() != W.getOperand(0).getValueType())
21224       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21225
21226     switch (W.getOpcode()) {
21227     default:
21228       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21229
21230     case X86ISD::UNPCKL:
21231     case X86ISD::UNPCKH:
21232       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21233       break;
21234
21235     case X86ISD::PSHUFD:
21236     case X86ISD::PSHUFLW:
21237     case X86ISD::PSHUFHW:
21238       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21239       break;
21240     }
21241   }
21242   if (V.getValueType() != N.getValueType())
21243     V = DAG.getBitcast(N.getValueType(), V);
21244
21245   // Return the new chain to replace N.
21246   return V;
21247 }
21248
21249 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21250 ///
21251 /// We walk up the chain, skipping shuffles of the other half and looking
21252 /// through shuffles which switch halves trying to find a shuffle of the same
21253 /// pair of dwords.
21254 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21255                                         SelectionDAG &DAG,
21256                                         TargetLowering::DAGCombinerInfo &DCI) {
21257   assert(
21258       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21259       "Called with something other than an x86 128-bit half shuffle!");
21260   SDLoc DL(N);
21261   unsigned CombineOpcode = N.getOpcode();
21262
21263   // Walk up a single-use chain looking for a combinable shuffle.
21264   SDValue V = N.getOperand(0);
21265   for (; V.hasOneUse(); V = V.getOperand(0)) {
21266     switch (V.getOpcode()) {
21267     default:
21268       return false; // Nothing combined!
21269
21270     case ISD::BITCAST:
21271       // Skip bitcasts as we always know the type for the target specific
21272       // instructions.
21273       continue;
21274
21275     case X86ISD::PSHUFLW:
21276     case X86ISD::PSHUFHW:
21277       if (V.getOpcode() == CombineOpcode)
21278         break;
21279
21280       // Other-half shuffles are no-ops.
21281       continue;
21282     }
21283     // Break out of the loop if we break out of the switch.
21284     break;
21285   }
21286
21287   if (!V.hasOneUse())
21288     // We fell out of the loop without finding a viable combining instruction.
21289     return false;
21290
21291   // Combine away the bottom node as its shuffle will be accumulated into
21292   // a preceding shuffle.
21293   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21294
21295   // Record the old value.
21296   SDValue Old = V;
21297
21298   // Merge this node's mask and our incoming mask (adjusted to account for all
21299   // the pshufd instructions encountered).
21300   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21301   for (int &M : Mask)
21302     M = VMask[M];
21303   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21304                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21305
21306   // Check that the shuffles didn't cancel each other out. If not, we need to
21307   // combine to the new one.
21308   if (Old != V)
21309     // Replace the combinable shuffle with the combined one, updating all users
21310     // so that we re-evaluate the chain here.
21311     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21312
21313   return true;
21314 }
21315
21316 /// \brief Try to combine x86 target specific shuffles.
21317 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21318                                            TargetLowering::DAGCombinerInfo &DCI,
21319                                            const X86Subtarget *Subtarget) {
21320   SDLoc DL(N);
21321   MVT VT = N.getSimpleValueType();
21322   SmallVector<int, 4> Mask;
21323
21324   switch (N.getOpcode()) {
21325   case X86ISD::PSHUFD:
21326   case X86ISD::PSHUFLW:
21327   case X86ISD::PSHUFHW:
21328     Mask = getPSHUFShuffleMask(N);
21329     assert(Mask.size() == 4);
21330     break;
21331   default:
21332     return SDValue();
21333   }
21334
21335   // Nuke no-op shuffles that show up after combining.
21336   if (isNoopShuffleMask(Mask))
21337     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21338
21339   // Look for simplifications involving one or two shuffle instructions.
21340   SDValue V = N.getOperand(0);
21341   switch (N.getOpcode()) {
21342   default:
21343     break;
21344   case X86ISD::PSHUFLW:
21345   case X86ISD::PSHUFHW:
21346     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21347
21348     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21349       return SDValue(); // We combined away this shuffle, so we're done.
21350
21351     // See if this reduces to a PSHUFD which is no more expensive and can
21352     // combine with more operations. Note that it has to at least flip the
21353     // dwords as otherwise it would have been removed as a no-op.
21354     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21355       int DMask[] = {0, 1, 2, 3};
21356       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21357       DMask[DOffset + 0] = DOffset + 1;
21358       DMask[DOffset + 1] = DOffset + 0;
21359       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21360       V = DAG.getBitcast(DVT, V);
21361       DCI.AddToWorklist(V.getNode());
21362       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21363                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21364       DCI.AddToWorklist(V.getNode());
21365       return DAG.getBitcast(VT, V);
21366     }
21367
21368     // Look for shuffle patterns which can be implemented as a single unpack.
21369     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21370     // only works when we have a PSHUFD followed by two half-shuffles.
21371     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21372         (V.getOpcode() == X86ISD::PSHUFLW ||
21373          V.getOpcode() == X86ISD::PSHUFHW) &&
21374         V.getOpcode() != N.getOpcode() &&
21375         V.hasOneUse()) {
21376       SDValue D = V.getOperand(0);
21377       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21378         D = D.getOperand(0);
21379       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21380         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21381         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21382         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21383         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21384         int WordMask[8];
21385         for (int i = 0; i < 4; ++i) {
21386           WordMask[i + NOffset] = Mask[i] + NOffset;
21387           WordMask[i + VOffset] = VMask[i] + VOffset;
21388         }
21389         // Map the word mask through the DWord mask.
21390         int MappedMask[8];
21391         for (int i = 0; i < 8; ++i)
21392           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21393         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21394             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21395           // We can replace all three shuffles with an unpack.
21396           V = DAG.getBitcast(VT, D.getOperand(0));
21397           DCI.AddToWorklist(V.getNode());
21398           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21399                                                 : X86ISD::UNPCKH,
21400                              DL, VT, V, V);
21401         }
21402       }
21403     }
21404
21405     break;
21406
21407   case X86ISD::PSHUFD:
21408     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21409       return NewN;
21410
21411     break;
21412   }
21413
21414   return SDValue();
21415 }
21416
21417 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21418 ///
21419 /// We combine this directly on the abstract vector shuffle nodes so it is
21420 /// easier to generically match. We also insert dummy vector shuffle nodes for
21421 /// the operands which explicitly discard the lanes which are unused by this
21422 /// operation to try to flow through the rest of the combiner the fact that
21423 /// they're unused.
21424 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21425   SDLoc DL(N);
21426   EVT VT = N->getValueType(0);
21427
21428   // We only handle target-independent shuffles.
21429   // FIXME: It would be easy and harmless to use the target shuffle mask
21430   // extraction tool to support more.
21431   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21432     return SDValue();
21433
21434   auto *SVN = cast<ShuffleVectorSDNode>(N);
21435   ArrayRef<int> Mask = SVN->getMask();
21436   SDValue V1 = N->getOperand(0);
21437   SDValue V2 = N->getOperand(1);
21438
21439   // We require the first shuffle operand to be the SUB node, and the second to
21440   // be the ADD node.
21441   // FIXME: We should support the commuted patterns.
21442   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21443     return SDValue();
21444
21445   // If there are other uses of these operations we can't fold them.
21446   if (!V1->hasOneUse() || !V2->hasOneUse())
21447     return SDValue();
21448
21449   // Ensure that both operations have the same operands. Note that we can
21450   // commute the FADD operands.
21451   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21452   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21453       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21454     return SDValue();
21455
21456   // We're looking for blends between FADD and FSUB nodes. We insist on these
21457   // nodes being lined up in a specific expected pattern.
21458   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21459         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21460         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21461     return SDValue();
21462
21463   // Only specific types are legal at this point, assert so we notice if and
21464   // when these change.
21465   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21466           VT == MVT::v4f64) &&
21467          "Unknown vector type encountered!");
21468
21469   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21470 }
21471
21472 /// PerformShuffleCombine - Performs several different shuffle combines.
21473 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21474                                      TargetLowering::DAGCombinerInfo &DCI,
21475                                      const X86Subtarget *Subtarget) {
21476   SDLoc dl(N);
21477   SDValue N0 = N->getOperand(0);
21478   SDValue N1 = N->getOperand(1);
21479   EVT VT = N->getValueType(0);
21480
21481   // Don't create instructions with illegal types after legalize types has run.
21482   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21483   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21484     return SDValue();
21485
21486   // If we have legalized the vector types, look for blends of FADD and FSUB
21487   // nodes that we can fuse into an ADDSUB node.
21488   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21489     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21490       return AddSub;
21491
21492   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21493   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21494       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21495     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21496
21497   // During Type Legalization, when promoting illegal vector types,
21498   // the backend might introduce new shuffle dag nodes and bitcasts.
21499   //
21500   // This code performs the following transformation:
21501   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21502   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21503   //
21504   // We do this only if both the bitcast and the BINOP dag nodes have
21505   // one use. Also, perform this transformation only if the new binary
21506   // operation is legal. This is to avoid introducing dag nodes that
21507   // potentially need to be further expanded (or custom lowered) into a
21508   // less optimal sequence of dag nodes.
21509   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21510       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21511       N0.getOpcode() == ISD::BITCAST) {
21512     SDValue BC0 = N0.getOperand(0);
21513     EVT SVT = BC0.getValueType();
21514     unsigned Opcode = BC0.getOpcode();
21515     unsigned NumElts = VT.getVectorNumElements();
21516
21517     if (BC0.hasOneUse() && SVT.isVector() &&
21518         SVT.getVectorNumElements() * 2 == NumElts &&
21519         TLI.isOperationLegal(Opcode, VT)) {
21520       bool CanFold = false;
21521       switch (Opcode) {
21522       default : break;
21523       case ISD::ADD :
21524       case ISD::FADD :
21525       case ISD::SUB :
21526       case ISD::FSUB :
21527       case ISD::MUL :
21528       case ISD::FMUL :
21529         CanFold = true;
21530       }
21531
21532       unsigned SVTNumElts = SVT.getVectorNumElements();
21533       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21534       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21535         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21536       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21537         CanFold = SVOp->getMaskElt(i) < 0;
21538
21539       if (CanFold) {
21540         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21541         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21542         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21543         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21544       }
21545     }
21546   }
21547
21548   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21549   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21550   // consecutive, non-overlapping, and in the right order.
21551   SmallVector<SDValue, 16> Elts;
21552   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21553     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21554
21555   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21556     return LD;
21557
21558   if (isTargetShuffle(N->getOpcode())) {
21559     SDValue Shuffle =
21560         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21561     if (Shuffle.getNode())
21562       return Shuffle;
21563
21564     // Try recursively combining arbitrary sequences of x86 shuffle
21565     // instructions into higher-order shuffles. We do this after combining
21566     // specific PSHUF instruction sequences into their minimal form so that we
21567     // can evaluate how many specialized shuffle instructions are involved in
21568     // a particular chain.
21569     SmallVector<int, 1> NonceMask; // Just a placeholder.
21570     NonceMask.push_back(0);
21571     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21572                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21573                                       DCI, Subtarget))
21574       return SDValue(); // This routine will use CombineTo to replace N.
21575   }
21576
21577   return SDValue();
21578 }
21579
21580 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21581 /// specific shuffle of a load can be folded into a single element load.
21582 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21583 /// shuffles have been custom lowered so we need to handle those here.
21584 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21585                                          TargetLowering::DAGCombinerInfo &DCI) {
21586   if (DCI.isBeforeLegalizeOps())
21587     return SDValue();
21588
21589   SDValue InVec = N->getOperand(0);
21590   SDValue EltNo = N->getOperand(1);
21591
21592   if (!isa<ConstantSDNode>(EltNo))
21593     return SDValue();
21594
21595   EVT OriginalVT = InVec.getValueType();
21596
21597   if (InVec.getOpcode() == ISD::BITCAST) {
21598     // Don't duplicate a load with other uses.
21599     if (!InVec.hasOneUse())
21600       return SDValue();
21601     EVT BCVT = InVec.getOperand(0).getValueType();
21602     if (!BCVT.isVector() ||
21603         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21604       return SDValue();
21605     InVec = InVec.getOperand(0);
21606   }
21607
21608   EVT CurrentVT = InVec.getValueType();
21609
21610   if (!isTargetShuffle(InVec.getOpcode()))
21611     return SDValue();
21612
21613   // Don't duplicate a load with other uses.
21614   if (!InVec.hasOneUse())
21615     return SDValue();
21616
21617   SmallVector<int, 16> ShuffleMask;
21618   bool UnaryShuffle;
21619   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21620                             ShuffleMask, UnaryShuffle))
21621     return SDValue();
21622
21623   // Select the input vector, guarding against out of range extract vector.
21624   unsigned NumElems = CurrentVT.getVectorNumElements();
21625   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21626   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21627   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21628                                          : InVec.getOperand(1);
21629
21630   // If inputs to shuffle are the same for both ops, then allow 2 uses
21631   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21632                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21633
21634   if (LdNode.getOpcode() == ISD::BITCAST) {
21635     // Don't duplicate a load with other uses.
21636     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21637       return SDValue();
21638
21639     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21640     LdNode = LdNode.getOperand(0);
21641   }
21642
21643   if (!ISD::isNormalLoad(LdNode.getNode()))
21644     return SDValue();
21645
21646   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21647
21648   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21649     return SDValue();
21650
21651   EVT EltVT = N->getValueType(0);
21652   // If there's a bitcast before the shuffle, check if the load type and
21653   // alignment is valid.
21654   unsigned Align = LN0->getAlignment();
21655   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21656   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21657       EltVT.getTypeForEVT(*DAG.getContext()));
21658
21659   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21660     return SDValue();
21661
21662   // All checks match so transform back to vector_shuffle so that DAG combiner
21663   // can finish the job
21664   SDLoc dl(N);
21665
21666   // Create shuffle node taking into account the case that its a unary shuffle
21667   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21668                                    : InVec.getOperand(1);
21669   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21670                                  InVec.getOperand(0), Shuffle,
21671                                  &ShuffleMask[0]);
21672   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21673   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21674                      EltNo);
21675 }
21676
21677 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21678 /// special and don't usually play with other vector types, it's better to
21679 /// handle them early to be sure we emit efficient code by avoiding
21680 /// store-load conversions.
21681 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21682   if (N->getValueType(0) != MVT::x86mmx ||
21683       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21684       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21685     return SDValue();
21686
21687   SDValue V = N->getOperand(0);
21688   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21689   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21690     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21691                        N->getValueType(0), V.getOperand(0));
21692
21693   return SDValue();
21694 }
21695
21696 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21697 /// generation and convert it from being a bunch of shuffles and extracts
21698 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21699 /// storing the value and loading scalars back, while for x64 we should
21700 /// use 64-bit extracts and shifts.
21701 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21702                                          TargetLowering::DAGCombinerInfo &DCI) {
21703   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21704     return NewOp;
21705
21706   SDValue InputVector = N->getOperand(0);
21707   SDLoc dl(InputVector);
21708   // Detect mmx to i32 conversion through a v2i32 elt extract.
21709   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21710       N->getValueType(0) == MVT::i32 &&
21711       InputVector.getValueType() == MVT::v2i32) {
21712
21713     // The bitcast source is a direct mmx result.
21714     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21715     if (MMXSrc.getValueType() == MVT::x86mmx)
21716       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21717                          N->getValueType(0),
21718                          InputVector.getNode()->getOperand(0));
21719
21720     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21721     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21722     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21723         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21724         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21725         MMXSrcOp.getValueType() == MVT::v1i64 &&
21726         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21727       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21728                          N->getValueType(0),
21729                          MMXSrcOp.getOperand(0));
21730   }
21731
21732   EVT VT = N->getValueType(0);
21733
21734   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21735       InputVector.getOpcode() == ISD::BITCAST &&
21736       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21737     uint64_t ExtractedElt =
21738           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21739     uint64_t InputValue =
21740           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21741     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21742     return DAG.getConstant(Res, dl, MVT::i1);
21743   }
21744   // Only operate on vectors of 4 elements, where the alternative shuffling
21745   // gets to be more expensive.
21746   if (InputVector.getValueType() != MVT::v4i32)
21747     return SDValue();
21748
21749   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21750   // single use which is a sign-extend or zero-extend, and all elements are
21751   // used.
21752   SmallVector<SDNode *, 4> Uses;
21753   unsigned ExtractedElements = 0;
21754   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21755        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21756     if (UI.getUse().getResNo() != InputVector.getResNo())
21757       return SDValue();
21758
21759     SDNode *Extract = *UI;
21760     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21761       return SDValue();
21762
21763     if (Extract->getValueType(0) != MVT::i32)
21764       return SDValue();
21765     if (!Extract->hasOneUse())
21766       return SDValue();
21767     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21768         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21769       return SDValue();
21770     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21771       return SDValue();
21772
21773     // Record which element was extracted.
21774     ExtractedElements |=
21775       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21776
21777     Uses.push_back(Extract);
21778   }
21779
21780   // If not all the elements were used, this may not be worthwhile.
21781   if (ExtractedElements != 15)
21782     return SDValue();
21783
21784   // Ok, we've now decided to do the transformation.
21785   // If 64-bit shifts are legal, use the extract-shift sequence,
21786   // otherwise bounce the vector off the cache.
21787   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21788   SDValue Vals[4];
21789
21790   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21791     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21792     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21793     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21794       DAG.getConstant(0, dl, VecIdxTy));
21795     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21796       DAG.getConstant(1, dl, VecIdxTy));
21797
21798     SDValue ShAmt = DAG.getConstant(32, dl,
21799       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21800     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21801     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21802       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21803     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21804     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21805       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21806   } else {
21807     // Store the value to a temporary stack slot.
21808     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21809     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21810       MachinePointerInfo(), false, false, 0);
21811
21812     EVT ElementType = InputVector.getValueType().getVectorElementType();
21813     unsigned EltSize = ElementType.getSizeInBits() / 8;
21814
21815     // Replace each use (extract) with a load of the appropriate element.
21816     for (unsigned i = 0; i < 4; ++i) {
21817       uint64_t Offset = EltSize * i;
21818       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21819
21820       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21821                                        StackPtr, OffsetVal);
21822
21823       // Load the scalar.
21824       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21825                             ScalarAddr, MachinePointerInfo(),
21826                             false, false, false, 0);
21827
21828     }
21829   }
21830
21831   // Replace the extracts
21832   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21833     UE = Uses.end(); UI != UE; ++UI) {
21834     SDNode *Extract = *UI;
21835
21836     SDValue Idx = Extract->getOperand(1);
21837     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21838     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21839   }
21840
21841   // The replacement was made in place; don't return anything.
21842   return SDValue();
21843 }
21844
21845 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21846 static std::pair<unsigned, bool>
21847 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21848                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21849   if (!VT.isVector())
21850     return std::make_pair(0, false);
21851
21852   bool NeedSplit = false;
21853   switch (VT.getSimpleVT().SimpleTy) {
21854   default: return std::make_pair(0, false);
21855   case MVT::v4i64:
21856   case MVT::v2i64:
21857     if (!Subtarget->hasVLX())
21858       return std::make_pair(0, false);
21859     break;
21860   case MVT::v64i8:
21861   case MVT::v32i16:
21862     if (!Subtarget->hasBWI())
21863       return std::make_pair(0, false);
21864     break;
21865   case MVT::v16i32:
21866   case MVT::v8i64:
21867     if (!Subtarget->hasAVX512())
21868       return std::make_pair(0, false);
21869     break;
21870   case MVT::v32i8:
21871   case MVT::v16i16:
21872   case MVT::v8i32:
21873     if (!Subtarget->hasAVX2())
21874       NeedSplit = true;
21875     if (!Subtarget->hasAVX())
21876       return std::make_pair(0, false);
21877     break;
21878   case MVT::v16i8:
21879   case MVT::v8i16:
21880   case MVT::v4i32:
21881     if (!Subtarget->hasSSE2())
21882       return std::make_pair(0, false);
21883   }
21884
21885   // SSE2 has only a small subset of the operations.
21886   bool hasUnsigned = Subtarget->hasSSE41() ||
21887                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21888   bool hasSigned = Subtarget->hasSSE41() ||
21889                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21890
21891   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21892
21893   unsigned Opc = 0;
21894   // Check for x CC y ? x : y.
21895   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21896       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21897     switch (CC) {
21898     default: break;
21899     case ISD::SETULT:
21900     case ISD::SETULE:
21901       Opc = hasUnsigned ? ISD::UMIN : 0u; break;
21902     case ISD::SETUGT:
21903     case ISD::SETUGE:
21904       Opc = hasUnsigned ? ISD::UMAX : 0u; break;
21905     case ISD::SETLT:
21906     case ISD::SETLE:
21907       Opc = hasSigned ? ISD::SMIN : 0u; break;
21908     case ISD::SETGT:
21909     case ISD::SETGE:
21910       Opc = hasSigned ? ISD::SMAX : 0u; break;
21911     }
21912   // Check for x CC y ? y : x -- a min/max with reversed arms.
21913   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21914              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21915     switch (CC) {
21916     default: break;
21917     case ISD::SETULT:
21918     case ISD::SETULE:
21919       Opc = hasUnsigned ? ISD::UMAX : 0u; break;
21920     case ISD::SETUGT:
21921     case ISD::SETUGE:
21922       Opc = hasUnsigned ? ISD::UMIN : 0u; break;
21923     case ISD::SETLT:
21924     case ISD::SETLE:
21925       Opc = hasSigned ? ISD::SMAX : 0u; break;
21926     case ISD::SETGT:
21927     case ISD::SETGE:
21928       Opc = hasSigned ? ISD::SMIN : 0u; break;
21929     }
21930   }
21931
21932   return std::make_pair(Opc, NeedSplit);
21933 }
21934
21935 static SDValue
21936 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21937                                       const X86Subtarget *Subtarget) {
21938   SDLoc dl(N);
21939   SDValue Cond = N->getOperand(0);
21940   SDValue LHS = N->getOperand(1);
21941   SDValue RHS = N->getOperand(2);
21942
21943   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21944     SDValue CondSrc = Cond->getOperand(0);
21945     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21946       Cond = CondSrc->getOperand(0);
21947   }
21948
21949   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21950     return SDValue();
21951
21952   // A vselect where all conditions and data are constants can be optimized into
21953   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21954   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21955       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21956     return SDValue();
21957
21958   unsigned MaskValue = 0;
21959   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21960     return SDValue();
21961
21962   MVT VT = N->getSimpleValueType(0);
21963   unsigned NumElems = VT.getVectorNumElements();
21964   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21965   for (unsigned i = 0; i < NumElems; ++i) {
21966     // Be sure we emit undef where we can.
21967     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21968       ShuffleMask[i] = -1;
21969     else
21970       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21971   }
21972
21973   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21974   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21975     return SDValue();
21976   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21977 }
21978
21979 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21980 /// nodes.
21981 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21982                                     TargetLowering::DAGCombinerInfo &DCI,
21983                                     const X86Subtarget *Subtarget) {
21984   SDLoc DL(N);
21985   SDValue Cond = N->getOperand(0);
21986   // Get the LHS/RHS of the select.
21987   SDValue LHS = N->getOperand(1);
21988   SDValue RHS = N->getOperand(2);
21989   EVT VT = LHS.getValueType();
21990   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21991
21992   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21993   // instructions match the semantics of the common C idiom x<y?x:y but not
21994   // x<=y?x:y, because of how they handle negative zero (which can be
21995   // ignored in unsafe-math mode).
21996   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21997   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21998       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21999       (Subtarget->hasSSE2() ||
22000        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22001     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22002
22003     unsigned Opcode = 0;
22004     // Check for x CC y ? x : y.
22005     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22006         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22007       switch (CC) {
22008       default: break;
22009       case ISD::SETULT:
22010         // Converting this to a min would handle NaNs incorrectly, and swapping
22011         // the operands would cause it to handle comparisons between positive
22012         // and negative zero incorrectly.
22013         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22014           if (!DAG.getTarget().Options.UnsafeFPMath &&
22015               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22016             break;
22017           std::swap(LHS, RHS);
22018         }
22019         Opcode = X86ISD::FMIN;
22020         break;
22021       case ISD::SETOLE:
22022         // Converting this to a min would handle comparisons between positive
22023         // and negative zero incorrectly.
22024         if (!DAG.getTarget().Options.UnsafeFPMath &&
22025             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22026           break;
22027         Opcode = X86ISD::FMIN;
22028         break;
22029       case ISD::SETULE:
22030         // Converting this to a min would handle both negative zeros and NaNs
22031         // incorrectly, but we can swap the operands to fix both.
22032         std::swap(LHS, RHS);
22033       case ISD::SETOLT:
22034       case ISD::SETLT:
22035       case ISD::SETLE:
22036         Opcode = X86ISD::FMIN;
22037         break;
22038
22039       case ISD::SETOGE:
22040         // Converting this to a max would handle comparisons between positive
22041         // and negative zero incorrectly.
22042         if (!DAG.getTarget().Options.UnsafeFPMath &&
22043             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22044           break;
22045         Opcode = X86ISD::FMAX;
22046         break;
22047       case ISD::SETUGT:
22048         // Converting this to a max would handle NaNs incorrectly, and swapping
22049         // the operands would cause it to handle comparisons between positive
22050         // and negative zero incorrectly.
22051         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22052           if (!DAG.getTarget().Options.UnsafeFPMath &&
22053               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22054             break;
22055           std::swap(LHS, RHS);
22056         }
22057         Opcode = X86ISD::FMAX;
22058         break;
22059       case ISD::SETUGE:
22060         // Converting this to a max would handle both negative zeros and NaNs
22061         // incorrectly, but we can swap the operands to fix both.
22062         std::swap(LHS, RHS);
22063       case ISD::SETOGT:
22064       case ISD::SETGT:
22065       case ISD::SETGE:
22066         Opcode = X86ISD::FMAX;
22067         break;
22068       }
22069     // Check for x CC y ? y : x -- a min/max with reversed arms.
22070     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22071                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22072       switch (CC) {
22073       default: break;
22074       case ISD::SETOGE:
22075         // Converting this to a min would handle comparisons between positive
22076         // and negative zero incorrectly, and swapping the operands would
22077         // cause it to handle NaNs incorrectly.
22078         if (!DAG.getTarget().Options.UnsafeFPMath &&
22079             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22080           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22081             break;
22082           std::swap(LHS, RHS);
22083         }
22084         Opcode = X86ISD::FMIN;
22085         break;
22086       case ISD::SETUGT:
22087         // Converting this to a min would handle NaNs incorrectly.
22088         if (!DAG.getTarget().Options.UnsafeFPMath &&
22089             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22090           break;
22091         Opcode = X86ISD::FMIN;
22092         break;
22093       case ISD::SETUGE:
22094         // Converting this to a min would handle both negative zeros and NaNs
22095         // incorrectly, but we can swap the operands to fix both.
22096         std::swap(LHS, RHS);
22097       case ISD::SETOGT:
22098       case ISD::SETGT:
22099       case ISD::SETGE:
22100         Opcode = X86ISD::FMIN;
22101         break;
22102
22103       case ISD::SETULT:
22104         // Converting this to a max would handle NaNs incorrectly.
22105         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22106           break;
22107         Opcode = X86ISD::FMAX;
22108         break;
22109       case ISD::SETOLE:
22110         // Converting this to a max would handle comparisons between positive
22111         // and negative zero incorrectly, and swapping the operands would
22112         // cause it to handle NaNs incorrectly.
22113         if (!DAG.getTarget().Options.UnsafeFPMath &&
22114             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22115           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22116             break;
22117           std::swap(LHS, RHS);
22118         }
22119         Opcode = X86ISD::FMAX;
22120         break;
22121       case ISD::SETULE:
22122         // Converting this to a max would handle both negative zeros and NaNs
22123         // incorrectly, but we can swap the operands to fix both.
22124         std::swap(LHS, RHS);
22125       case ISD::SETOLT:
22126       case ISD::SETLT:
22127       case ISD::SETLE:
22128         Opcode = X86ISD::FMAX;
22129         break;
22130       }
22131     }
22132
22133     if (Opcode)
22134       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22135   }
22136
22137   EVT CondVT = Cond.getValueType();
22138   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22139       CondVT.getVectorElementType() == MVT::i1) {
22140     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22141     // lowering on KNL. In this case we convert it to
22142     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22143     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22144     // Since SKX these selects have a proper lowering.
22145     EVT OpVT = LHS.getValueType();
22146     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22147         (OpVT.getVectorElementType() == MVT::i8 ||
22148          OpVT.getVectorElementType() == MVT::i16) &&
22149         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22150       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22151       DCI.AddToWorklist(Cond.getNode());
22152       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22153     }
22154   }
22155   // If this is a select between two integer constants, try to do some
22156   // optimizations.
22157   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22158     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22159       // Don't do this for crazy integer types.
22160       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22161         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22162         // so that TrueC (the true value) is larger than FalseC.
22163         bool NeedsCondInvert = false;
22164
22165         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22166             // Efficiently invertible.
22167             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22168              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22169               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22170           NeedsCondInvert = true;
22171           std::swap(TrueC, FalseC);
22172         }
22173
22174         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22175         if (FalseC->getAPIntValue() == 0 &&
22176             TrueC->getAPIntValue().isPowerOf2()) {
22177           if (NeedsCondInvert) // Invert the condition if needed.
22178             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22179                                DAG.getConstant(1, DL, Cond.getValueType()));
22180
22181           // Zero extend the condition if needed.
22182           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22183
22184           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22185           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22186                              DAG.getConstant(ShAmt, DL, MVT::i8));
22187         }
22188
22189         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22190         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22191           if (NeedsCondInvert) // Invert the condition if needed.
22192             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22193                                DAG.getConstant(1, DL, Cond.getValueType()));
22194
22195           // Zero extend the condition if needed.
22196           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22197                              FalseC->getValueType(0), Cond);
22198           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22199                              SDValue(FalseC, 0));
22200         }
22201
22202         // Optimize cases that will turn into an LEA instruction.  This requires
22203         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22204         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22205           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22206           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22207
22208           bool isFastMultiplier = false;
22209           if (Diff < 10) {
22210             switch ((unsigned char)Diff) {
22211               default: break;
22212               case 1:  // result = add base, cond
22213               case 2:  // result = lea base(    , cond*2)
22214               case 3:  // result = lea base(cond, cond*2)
22215               case 4:  // result = lea base(    , cond*4)
22216               case 5:  // result = lea base(cond, cond*4)
22217               case 8:  // result = lea base(    , cond*8)
22218               case 9:  // result = lea base(cond, cond*8)
22219                 isFastMultiplier = true;
22220                 break;
22221             }
22222           }
22223
22224           if (isFastMultiplier) {
22225             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22226             if (NeedsCondInvert) // Invert the condition if needed.
22227               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22228                                  DAG.getConstant(1, DL, Cond.getValueType()));
22229
22230             // Zero extend the condition if needed.
22231             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22232                                Cond);
22233             // Scale the condition by the difference.
22234             if (Diff != 1)
22235               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22236                                  DAG.getConstant(Diff, DL,
22237                                                  Cond.getValueType()));
22238
22239             // Add the base if non-zero.
22240             if (FalseC->getAPIntValue() != 0)
22241               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22242                                  SDValue(FalseC, 0));
22243             return Cond;
22244           }
22245         }
22246       }
22247   }
22248
22249   // Canonicalize max and min:
22250   // (x > y) ? x : y -> (x >= y) ? x : y
22251   // (x < y) ? x : y -> (x <= y) ? x : y
22252   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22253   // the need for an extra compare
22254   // against zero. e.g.
22255   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22256   // subl   %esi, %edi
22257   // testl  %edi, %edi
22258   // movl   $0, %eax
22259   // cmovgl %edi, %eax
22260   // =>
22261   // xorl   %eax, %eax
22262   // subl   %esi, $edi
22263   // cmovsl %eax, %edi
22264   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22265       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22266       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22267     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22268     switch (CC) {
22269     default: break;
22270     case ISD::SETLT:
22271     case ISD::SETGT: {
22272       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22273       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22274                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22275       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22276     }
22277     }
22278   }
22279
22280   // Early exit check
22281   if (!TLI.isTypeLegal(VT))
22282     return SDValue();
22283
22284   // Match VSELECTs into subs with unsigned saturation.
22285   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22286       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22287       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22288        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22289     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22290
22291     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22292     // left side invert the predicate to simplify logic below.
22293     SDValue Other;
22294     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22295       Other = RHS;
22296       CC = ISD::getSetCCInverse(CC, true);
22297     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22298       Other = LHS;
22299     }
22300
22301     if (Other.getNode() && Other->getNumOperands() == 2 &&
22302         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22303       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22304       SDValue CondRHS = Cond->getOperand(1);
22305
22306       // Look for a general sub with unsigned saturation first.
22307       // x >= y ? x-y : 0 --> subus x, y
22308       // x >  y ? x-y : 0 --> subus x, y
22309       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22310           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22311         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22312
22313       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22314         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22315           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22316             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22317               // If the RHS is a constant we have to reverse the const
22318               // canonicalization.
22319               // x > C-1 ? x+-C : 0 --> subus x, C
22320               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22321                   CondRHSConst->getAPIntValue() ==
22322                       (-OpRHSConst->getAPIntValue() - 1))
22323                 return DAG.getNode(
22324                     X86ISD::SUBUS, DL, VT, OpLHS,
22325                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22326
22327           // Another special case: If C was a sign bit, the sub has been
22328           // canonicalized into a xor.
22329           // FIXME: Would it be better to use computeKnownBits to determine
22330           //        whether it's safe to decanonicalize the xor?
22331           // x s< 0 ? x^C : 0 --> subus x, C
22332           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22333               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22334               OpRHSConst->getAPIntValue().isSignBit())
22335             // Note that we have to rebuild the RHS constant here to ensure we
22336             // don't rely on particular values of undef lanes.
22337             return DAG.getNode(
22338                 X86ISD::SUBUS, DL, VT, OpLHS,
22339                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22340         }
22341     }
22342   }
22343
22344   // Try to match a min/max vector operation.
22345   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22346     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22347     unsigned Opc = ret.first;
22348     bool NeedSplit = ret.second;
22349
22350     if (Opc && NeedSplit) {
22351       unsigned NumElems = VT.getVectorNumElements();
22352       // Extract the LHS vectors
22353       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22354       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22355
22356       // Extract the RHS vectors
22357       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22358       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22359
22360       // Create min/max for each subvector
22361       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22362       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22363
22364       // Merge the result
22365       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22366     } else if (Opc)
22367       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22368   }
22369
22370   // Simplify vector selection if condition value type matches vselect
22371   // operand type
22372   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22373     assert(Cond.getValueType().isVector() &&
22374            "vector select expects a vector selector!");
22375
22376     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22377     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22378
22379     // Try invert the condition if true value is not all 1s and false value
22380     // is not all 0s.
22381     if (!TValIsAllOnes && !FValIsAllZeros &&
22382         // Check if the selector will be produced by CMPP*/PCMP*
22383         Cond.getOpcode() == ISD::SETCC &&
22384         // Check if SETCC has already been promoted
22385         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22386       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22387       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22388
22389       if (TValIsAllZeros || FValIsAllOnes) {
22390         SDValue CC = Cond.getOperand(2);
22391         ISD::CondCode NewCC =
22392           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22393                                Cond.getOperand(0).getValueType().isInteger());
22394         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22395         std::swap(LHS, RHS);
22396         TValIsAllOnes = FValIsAllOnes;
22397         FValIsAllZeros = TValIsAllZeros;
22398       }
22399     }
22400
22401     if (TValIsAllOnes || FValIsAllZeros) {
22402       SDValue Ret;
22403
22404       if (TValIsAllOnes && FValIsAllZeros)
22405         Ret = Cond;
22406       else if (TValIsAllOnes)
22407         Ret =
22408             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22409       else if (FValIsAllZeros)
22410         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22411                           DAG.getBitcast(CondVT, LHS));
22412
22413       return DAG.getBitcast(VT, Ret);
22414     }
22415   }
22416
22417   // We should generate an X86ISD::BLENDI from a vselect if its argument
22418   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22419   // constants. This specific pattern gets generated when we split a
22420   // selector for a 512 bit vector in a machine without AVX512 (but with
22421   // 256-bit vectors), during legalization:
22422   //
22423   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22424   //
22425   // Iff we find this pattern and the build_vectors are built from
22426   // constants, we translate the vselect into a shuffle_vector that we
22427   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22428   if ((N->getOpcode() == ISD::VSELECT ||
22429        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22430       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22431     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22432     if (Shuffle.getNode())
22433       return Shuffle;
22434   }
22435
22436   // If this is a *dynamic* select (non-constant condition) and we can match
22437   // this node with one of the variable blend instructions, restructure the
22438   // condition so that the blends can use the high bit of each element and use
22439   // SimplifyDemandedBits to simplify the condition operand.
22440   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22441       !DCI.isBeforeLegalize() &&
22442       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22443     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22444
22445     // Don't optimize vector selects that map to mask-registers.
22446     if (BitWidth == 1)
22447       return SDValue();
22448
22449     // We can only handle the cases where VSELECT is directly legal on the
22450     // subtarget. We custom lower VSELECT nodes with constant conditions and
22451     // this makes it hard to see whether a dynamic VSELECT will correctly
22452     // lower, so we both check the operation's status and explicitly handle the
22453     // cases where a *dynamic* blend will fail even though a constant-condition
22454     // blend could be custom lowered.
22455     // FIXME: We should find a better way to handle this class of problems.
22456     // Potentially, we should combine constant-condition vselect nodes
22457     // pre-legalization into shuffles and not mark as many types as custom
22458     // lowered.
22459     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22460       return SDValue();
22461     // FIXME: We don't support i16-element blends currently. We could and
22462     // should support them by making *all* the bits in the condition be set
22463     // rather than just the high bit and using an i8-element blend.
22464     if (VT.getScalarType() == MVT::i16)
22465       return SDValue();
22466     // Dynamic blending was only available from SSE4.1 onward.
22467     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22468       return SDValue();
22469     // Byte blends are only available in AVX2
22470     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22471         !Subtarget->hasAVX2())
22472       return SDValue();
22473
22474     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22475     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22476
22477     APInt KnownZero, KnownOne;
22478     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22479                                           DCI.isBeforeLegalizeOps());
22480     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22481         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22482                                  TLO)) {
22483       // If we changed the computation somewhere in the DAG, this change
22484       // will affect all users of Cond.
22485       // Make sure it is fine and update all the nodes so that we do not
22486       // use the generic VSELECT anymore. Otherwise, we may perform
22487       // wrong optimizations as we messed up with the actual expectation
22488       // for the vector boolean values.
22489       if (Cond != TLO.Old) {
22490         // Check all uses of that condition operand to check whether it will be
22491         // consumed by non-BLEND instructions, which may depend on all bits are
22492         // set properly.
22493         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22494              I != E; ++I)
22495           if (I->getOpcode() != ISD::VSELECT)
22496             // TODO: Add other opcodes eventually lowered into BLEND.
22497             return SDValue();
22498
22499         // Update all the users of the condition, before committing the change,
22500         // so that the VSELECT optimizations that expect the correct vector
22501         // boolean value will not be triggered.
22502         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22503              I != E; ++I)
22504           DAG.ReplaceAllUsesOfValueWith(
22505               SDValue(*I, 0),
22506               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22507                           Cond, I->getOperand(1), I->getOperand(2)));
22508         DCI.CommitTargetLoweringOpt(TLO);
22509         return SDValue();
22510       }
22511       // At this point, only Cond is changed. Change the condition
22512       // just for N to keep the opportunity to optimize all other
22513       // users their own way.
22514       DAG.ReplaceAllUsesOfValueWith(
22515           SDValue(N, 0),
22516           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22517                       TLO.New, N->getOperand(1), N->getOperand(2)));
22518       return SDValue();
22519     }
22520   }
22521
22522   return SDValue();
22523 }
22524
22525 // Check whether a boolean test is testing a boolean value generated by
22526 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22527 // code.
22528 //
22529 // Simplify the following patterns:
22530 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22531 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22532 // to (Op EFLAGS Cond)
22533 //
22534 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22535 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22536 // to (Op EFLAGS !Cond)
22537 //
22538 // where Op could be BRCOND or CMOV.
22539 //
22540 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22541   // Quit if not CMP and SUB with its value result used.
22542   if (Cmp.getOpcode() != X86ISD::CMP &&
22543       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22544       return SDValue();
22545
22546   // Quit if not used as a boolean value.
22547   if (CC != X86::COND_E && CC != X86::COND_NE)
22548     return SDValue();
22549
22550   // Check CMP operands. One of them should be 0 or 1 and the other should be
22551   // an SetCC or extended from it.
22552   SDValue Op1 = Cmp.getOperand(0);
22553   SDValue Op2 = Cmp.getOperand(1);
22554
22555   SDValue SetCC;
22556   const ConstantSDNode* C = nullptr;
22557   bool needOppositeCond = (CC == X86::COND_E);
22558   bool checkAgainstTrue = false; // Is it a comparison against 1?
22559
22560   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22561     SetCC = Op2;
22562   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22563     SetCC = Op1;
22564   else // Quit if all operands are not constants.
22565     return SDValue();
22566
22567   if (C->getZExtValue() == 1) {
22568     needOppositeCond = !needOppositeCond;
22569     checkAgainstTrue = true;
22570   } else if (C->getZExtValue() != 0)
22571     // Quit if the constant is neither 0 or 1.
22572     return SDValue();
22573
22574   bool truncatedToBoolWithAnd = false;
22575   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22576   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22577          SetCC.getOpcode() == ISD::TRUNCATE ||
22578          SetCC.getOpcode() == ISD::AND) {
22579     if (SetCC.getOpcode() == ISD::AND) {
22580       int OpIdx = -1;
22581       ConstantSDNode *CS;
22582       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22583           CS->getZExtValue() == 1)
22584         OpIdx = 1;
22585       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22586           CS->getZExtValue() == 1)
22587         OpIdx = 0;
22588       if (OpIdx == -1)
22589         break;
22590       SetCC = SetCC.getOperand(OpIdx);
22591       truncatedToBoolWithAnd = true;
22592     } else
22593       SetCC = SetCC.getOperand(0);
22594   }
22595
22596   switch (SetCC.getOpcode()) {
22597   case X86ISD::SETCC_CARRY:
22598     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22599     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22600     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22601     // truncated to i1 using 'and'.
22602     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22603       break;
22604     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22605            "Invalid use of SETCC_CARRY!");
22606     // FALL THROUGH
22607   case X86ISD::SETCC:
22608     // Set the condition code or opposite one if necessary.
22609     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22610     if (needOppositeCond)
22611       CC = X86::GetOppositeBranchCondition(CC);
22612     return SetCC.getOperand(1);
22613   case X86ISD::CMOV: {
22614     // Check whether false/true value has canonical one, i.e. 0 or 1.
22615     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22616     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22617     // Quit if true value is not a constant.
22618     if (!TVal)
22619       return SDValue();
22620     // Quit if false value is not a constant.
22621     if (!FVal) {
22622       SDValue Op = SetCC.getOperand(0);
22623       // Skip 'zext' or 'trunc' node.
22624       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22625           Op.getOpcode() == ISD::TRUNCATE)
22626         Op = Op.getOperand(0);
22627       // A special case for rdrand/rdseed, where 0 is set if false cond is
22628       // found.
22629       if ((Op.getOpcode() != X86ISD::RDRAND &&
22630            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22631         return SDValue();
22632     }
22633     // Quit if false value is not the constant 0 or 1.
22634     bool FValIsFalse = true;
22635     if (FVal && FVal->getZExtValue() != 0) {
22636       if (FVal->getZExtValue() != 1)
22637         return SDValue();
22638       // If FVal is 1, opposite cond is needed.
22639       needOppositeCond = !needOppositeCond;
22640       FValIsFalse = false;
22641     }
22642     // Quit if TVal is not the constant opposite of FVal.
22643     if (FValIsFalse && TVal->getZExtValue() != 1)
22644       return SDValue();
22645     if (!FValIsFalse && TVal->getZExtValue() != 0)
22646       return SDValue();
22647     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22648     if (needOppositeCond)
22649       CC = X86::GetOppositeBranchCondition(CC);
22650     return SetCC.getOperand(3);
22651   }
22652   }
22653
22654   return SDValue();
22655 }
22656
22657 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22658 /// Match:
22659 ///   (X86or (X86setcc) (X86setcc))
22660 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22661 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22662                                            X86::CondCode &CC1, SDValue &Flags,
22663                                            bool &isAnd) {
22664   if (Cond->getOpcode() == X86ISD::CMP) {
22665     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22666     if (!CondOp1C || !CondOp1C->isNullValue())
22667       return false;
22668
22669     Cond = Cond->getOperand(0);
22670   }
22671
22672   isAnd = false;
22673
22674   SDValue SetCC0, SetCC1;
22675   switch (Cond->getOpcode()) {
22676   default: return false;
22677   case ISD::AND:
22678   case X86ISD::AND:
22679     isAnd = true;
22680     // fallthru
22681   case ISD::OR:
22682   case X86ISD::OR:
22683     SetCC0 = Cond->getOperand(0);
22684     SetCC1 = Cond->getOperand(1);
22685     break;
22686   };
22687
22688   // Make sure we have SETCC nodes, using the same flags value.
22689   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22690       SetCC1.getOpcode() != X86ISD::SETCC ||
22691       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22692     return false;
22693
22694   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22695   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22696   Flags = SetCC0->getOperand(1);
22697   return true;
22698 }
22699
22700 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22701 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22702                                   TargetLowering::DAGCombinerInfo &DCI,
22703                                   const X86Subtarget *Subtarget) {
22704   SDLoc DL(N);
22705
22706   // If the flag operand isn't dead, don't touch this CMOV.
22707   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22708     return SDValue();
22709
22710   SDValue FalseOp = N->getOperand(0);
22711   SDValue TrueOp = N->getOperand(1);
22712   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22713   SDValue Cond = N->getOperand(3);
22714
22715   if (CC == X86::COND_E || CC == X86::COND_NE) {
22716     switch (Cond.getOpcode()) {
22717     default: break;
22718     case X86ISD::BSR:
22719     case X86ISD::BSF:
22720       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22721       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22722         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22723     }
22724   }
22725
22726   SDValue Flags;
22727
22728   Flags = checkBoolTestSetCCCombine(Cond, CC);
22729   if (Flags.getNode() &&
22730       // Extra check as FCMOV only supports a subset of X86 cond.
22731       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22732     SDValue Ops[] = { FalseOp, TrueOp,
22733                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22734     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22735   }
22736
22737   // If this is a select between two integer constants, try to do some
22738   // optimizations.  Note that the operands are ordered the opposite of SELECT
22739   // operands.
22740   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22741     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22742       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22743       // larger than FalseC (the false value).
22744       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22745         CC = X86::GetOppositeBranchCondition(CC);
22746         std::swap(TrueC, FalseC);
22747         std::swap(TrueOp, FalseOp);
22748       }
22749
22750       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22751       // This is efficient for any integer data type (including i8/i16) and
22752       // shift amount.
22753       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22754         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22755                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22756
22757         // Zero extend the condition if needed.
22758         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22759
22760         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22761         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22762                            DAG.getConstant(ShAmt, DL, MVT::i8));
22763         if (N->getNumValues() == 2)  // Dead flag value?
22764           return DCI.CombineTo(N, Cond, SDValue());
22765         return Cond;
22766       }
22767
22768       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22769       // for any integer data type, including i8/i16.
22770       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22771         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22772                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22773
22774         // Zero extend the condition if needed.
22775         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22776                            FalseC->getValueType(0), Cond);
22777         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22778                            SDValue(FalseC, 0));
22779
22780         if (N->getNumValues() == 2)  // Dead flag value?
22781           return DCI.CombineTo(N, Cond, SDValue());
22782         return Cond;
22783       }
22784
22785       // Optimize cases that will turn into an LEA instruction.  This requires
22786       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22787       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22788         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22789         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22790
22791         bool isFastMultiplier = false;
22792         if (Diff < 10) {
22793           switch ((unsigned char)Diff) {
22794           default: break;
22795           case 1:  // result = add base, cond
22796           case 2:  // result = lea base(    , cond*2)
22797           case 3:  // result = lea base(cond, cond*2)
22798           case 4:  // result = lea base(    , cond*4)
22799           case 5:  // result = lea base(cond, cond*4)
22800           case 8:  // result = lea base(    , cond*8)
22801           case 9:  // result = lea base(cond, cond*8)
22802             isFastMultiplier = true;
22803             break;
22804           }
22805         }
22806
22807         if (isFastMultiplier) {
22808           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22809           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22810                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22811           // Zero extend the condition if needed.
22812           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22813                              Cond);
22814           // Scale the condition by the difference.
22815           if (Diff != 1)
22816             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22817                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22818
22819           // Add the base if non-zero.
22820           if (FalseC->getAPIntValue() != 0)
22821             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22822                                SDValue(FalseC, 0));
22823           if (N->getNumValues() == 2)  // Dead flag value?
22824             return DCI.CombineTo(N, Cond, SDValue());
22825           return Cond;
22826         }
22827       }
22828     }
22829   }
22830
22831   // Handle these cases:
22832   //   (select (x != c), e, c) -> select (x != c), e, x),
22833   //   (select (x == c), c, e) -> select (x == c), x, e)
22834   // where the c is an integer constant, and the "select" is the combination
22835   // of CMOV and CMP.
22836   //
22837   // The rationale for this change is that the conditional-move from a constant
22838   // needs two instructions, however, conditional-move from a register needs
22839   // only one instruction.
22840   //
22841   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22842   //  some instruction-combining opportunities. This opt needs to be
22843   //  postponed as late as possible.
22844   //
22845   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22846     // the DCI.xxxx conditions are provided to postpone the optimization as
22847     // late as possible.
22848
22849     ConstantSDNode *CmpAgainst = nullptr;
22850     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22851         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22852         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22853
22854       if (CC == X86::COND_NE &&
22855           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22856         CC = X86::GetOppositeBranchCondition(CC);
22857         std::swap(TrueOp, FalseOp);
22858       }
22859
22860       if (CC == X86::COND_E &&
22861           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22862         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22863                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22864         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22865       }
22866     }
22867   }
22868
22869   // Fold and/or of setcc's to double CMOV:
22870   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22871   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22872   //
22873   // This combine lets us generate:
22874   //   cmovcc1 (jcc1 if we don't have CMOV)
22875   //   cmovcc2 (same)
22876   // instead of:
22877   //   setcc1
22878   //   setcc2
22879   //   and/or
22880   //   cmovne (jne if we don't have CMOV)
22881   // When we can't use the CMOV instruction, it might increase branch
22882   // mispredicts.
22883   // When we can use CMOV, or when there is no mispredict, this improves
22884   // throughput and reduces register pressure.
22885   //
22886   if (CC == X86::COND_NE) {
22887     SDValue Flags;
22888     X86::CondCode CC0, CC1;
22889     bool isAndSetCC;
22890     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22891       if (isAndSetCC) {
22892         std::swap(FalseOp, TrueOp);
22893         CC0 = X86::GetOppositeBranchCondition(CC0);
22894         CC1 = X86::GetOppositeBranchCondition(CC1);
22895       }
22896
22897       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22898         Flags};
22899       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22900       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22901       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22902       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22903       return CMOV;
22904     }
22905   }
22906
22907   return SDValue();
22908 }
22909
22910 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22911                                                 const X86Subtarget *Subtarget) {
22912   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22913   switch (IntNo) {
22914   default: return SDValue();
22915   // SSE/AVX/AVX2 blend intrinsics.
22916   case Intrinsic::x86_avx2_pblendvb:
22917     // Don't try to simplify this intrinsic if we don't have AVX2.
22918     if (!Subtarget->hasAVX2())
22919       return SDValue();
22920     // FALL-THROUGH
22921   case Intrinsic::x86_avx_blendv_pd_256:
22922   case Intrinsic::x86_avx_blendv_ps_256:
22923     // Don't try to simplify this intrinsic if we don't have AVX.
22924     if (!Subtarget->hasAVX())
22925       return SDValue();
22926     // FALL-THROUGH
22927   case Intrinsic::x86_sse41_blendvps:
22928   case Intrinsic::x86_sse41_blendvpd:
22929   case Intrinsic::x86_sse41_pblendvb: {
22930     SDValue Op0 = N->getOperand(1);
22931     SDValue Op1 = N->getOperand(2);
22932     SDValue Mask = N->getOperand(3);
22933
22934     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22935     if (!Subtarget->hasSSE41())
22936       return SDValue();
22937
22938     // fold (blend A, A, Mask) -> A
22939     if (Op0 == Op1)
22940       return Op0;
22941     // fold (blend A, B, allZeros) -> A
22942     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22943       return Op0;
22944     // fold (blend A, B, allOnes) -> B
22945     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22946       return Op1;
22947
22948     // Simplify the case where the mask is a constant i32 value.
22949     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22950       if (C->isNullValue())
22951         return Op0;
22952       if (C->isAllOnesValue())
22953         return Op1;
22954     }
22955
22956     return SDValue();
22957   }
22958
22959   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22960   case Intrinsic::x86_sse2_psrai_w:
22961   case Intrinsic::x86_sse2_psrai_d:
22962   case Intrinsic::x86_avx2_psrai_w:
22963   case Intrinsic::x86_avx2_psrai_d:
22964   case Intrinsic::x86_sse2_psra_w:
22965   case Intrinsic::x86_sse2_psra_d:
22966   case Intrinsic::x86_avx2_psra_w:
22967   case Intrinsic::x86_avx2_psra_d: {
22968     SDValue Op0 = N->getOperand(1);
22969     SDValue Op1 = N->getOperand(2);
22970     EVT VT = Op0.getValueType();
22971     assert(VT.isVector() && "Expected a vector type!");
22972
22973     if (isa<BuildVectorSDNode>(Op1))
22974       Op1 = Op1.getOperand(0);
22975
22976     if (!isa<ConstantSDNode>(Op1))
22977       return SDValue();
22978
22979     EVT SVT = VT.getVectorElementType();
22980     unsigned SVTBits = SVT.getSizeInBits();
22981
22982     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22983     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22984     uint64_t ShAmt = C.getZExtValue();
22985
22986     // Don't try to convert this shift into a ISD::SRA if the shift
22987     // count is bigger than or equal to the element size.
22988     if (ShAmt >= SVTBits)
22989       return SDValue();
22990
22991     // Trivial case: if the shift count is zero, then fold this
22992     // into the first operand.
22993     if (ShAmt == 0)
22994       return Op0;
22995
22996     // Replace this packed shift intrinsic with a target independent
22997     // shift dag node.
22998     SDLoc DL(N);
22999     SDValue Splat = DAG.getConstant(C, DL, VT);
23000     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23001   }
23002   }
23003 }
23004
23005 /// PerformMulCombine - Optimize a single multiply with constant into two
23006 /// in order to implement it with two cheaper instructions, e.g.
23007 /// LEA + SHL, LEA + LEA.
23008 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23009                                  TargetLowering::DAGCombinerInfo &DCI) {
23010   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23011     return SDValue();
23012
23013   EVT VT = N->getValueType(0);
23014   if (VT != MVT::i64 && VT != MVT::i32)
23015     return SDValue();
23016
23017   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23018   if (!C)
23019     return SDValue();
23020   uint64_t MulAmt = C->getZExtValue();
23021   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23022     return SDValue();
23023
23024   uint64_t MulAmt1 = 0;
23025   uint64_t MulAmt2 = 0;
23026   if ((MulAmt % 9) == 0) {
23027     MulAmt1 = 9;
23028     MulAmt2 = MulAmt / 9;
23029   } else if ((MulAmt % 5) == 0) {
23030     MulAmt1 = 5;
23031     MulAmt2 = MulAmt / 5;
23032   } else if ((MulAmt % 3) == 0) {
23033     MulAmt1 = 3;
23034     MulAmt2 = MulAmt / 3;
23035   }
23036   if (MulAmt2 &&
23037       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23038     SDLoc DL(N);
23039
23040     if (isPowerOf2_64(MulAmt2) &&
23041         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23042       // If second multiplifer is pow2, issue it first. We want the multiply by
23043       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23044       // is an add.
23045       std::swap(MulAmt1, MulAmt2);
23046
23047     SDValue NewMul;
23048     if (isPowerOf2_64(MulAmt1))
23049       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23050                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23051     else
23052       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23053                            DAG.getConstant(MulAmt1, DL, VT));
23054
23055     if (isPowerOf2_64(MulAmt2))
23056       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23057                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23058     else
23059       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23060                            DAG.getConstant(MulAmt2, DL, VT));
23061
23062     // Do not add new nodes to DAG combiner worklist.
23063     DCI.CombineTo(N, NewMul, false);
23064   }
23065   return SDValue();
23066 }
23067
23068 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23069   SDValue N0 = N->getOperand(0);
23070   SDValue N1 = N->getOperand(1);
23071   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23072   EVT VT = N0.getValueType();
23073
23074   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23075   // since the result of setcc_c is all zero's or all ones.
23076   if (VT.isInteger() && !VT.isVector() &&
23077       N1C && N0.getOpcode() == ISD::AND &&
23078       N0.getOperand(1).getOpcode() == ISD::Constant) {
23079     SDValue N00 = N0.getOperand(0);
23080     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23081         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23082           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23083          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23084       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23085       APInt ShAmt = N1C->getAPIntValue();
23086       Mask = Mask.shl(ShAmt);
23087       if (Mask != 0) {
23088         SDLoc DL(N);
23089         return DAG.getNode(ISD::AND, DL, VT,
23090                            N00, DAG.getConstant(Mask, DL, VT));
23091       }
23092     }
23093   }
23094
23095   // Hardware support for vector shifts is sparse which makes us scalarize the
23096   // vector operations in many cases. Also, on sandybridge ADD is faster than
23097   // shl.
23098   // (shl V, 1) -> add V,V
23099   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23100     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23101       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23102       // We shift all of the values by one. In many cases we do not have
23103       // hardware support for this operation. This is better expressed as an ADD
23104       // of two values.
23105       if (N1SplatC->getZExtValue() == 1)
23106         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23107     }
23108
23109   return SDValue();
23110 }
23111
23112 /// \brief Returns a vector of 0s if the node in input is a vector logical
23113 /// shift by a constant amount which is known to be bigger than or equal
23114 /// to the vector element size in bits.
23115 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23116                                       const X86Subtarget *Subtarget) {
23117   EVT VT = N->getValueType(0);
23118
23119   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23120       (!Subtarget->hasInt256() ||
23121        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23122     return SDValue();
23123
23124   SDValue Amt = N->getOperand(1);
23125   SDLoc DL(N);
23126   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23127     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23128       APInt ShiftAmt = AmtSplat->getAPIntValue();
23129       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23130
23131       // SSE2/AVX2 logical shifts always return a vector of 0s
23132       // if the shift amount is bigger than or equal to
23133       // the element size. The constant shift amount will be
23134       // encoded as a 8-bit immediate.
23135       if (ShiftAmt.trunc(8).uge(MaxAmount))
23136         return getZeroVector(VT, Subtarget, DAG, DL);
23137     }
23138
23139   return SDValue();
23140 }
23141
23142 /// PerformShiftCombine - Combine shifts.
23143 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23144                                    TargetLowering::DAGCombinerInfo &DCI,
23145                                    const X86Subtarget *Subtarget) {
23146   if (N->getOpcode() == ISD::SHL)
23147     if (SDValue V = PerformSHLCombine(N, DAG))
23148       return V;
23149
23150   // Try to fold this logical shift into a zero vector.
23151   if (N->getOpcode() != ISD::SRA)
23152     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23153       return V;
23154
23155   return SDValue();
23156 }
23157
23158 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23159 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23160 // and friends.  Likewise for OR -> CMPNEQSS.
23161 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23162                             TargetLowering::DAGCombinerInfo &DCI,
23163                             const X86Subtarget *Subtarget) {
23164   unsigned opcode;
23165
23166   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23167   // we're requiring SSE2 for both.
23168   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23169     SDValue N0 = N->getOperand(0);
23170     SDValue N1 = N->getOperand(1);
23171     SDValue CMP0 = N0->getOperand(1);
23172     SDValue CMP1 = N1->getOperand(1);
23173     SDLoc DL(N);
23174
23175     // The SETCCs should both refer to the same CMP.
23176     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23177       return SDValue();
23178
23179     SDValue CMP00 = CMP0->getOperand(0);
23180     SDValue CMP01 = CMP0->getOperand(1);
23181     EVT     VT    = CMP00.getValueType();
23182
23183     if (VT == MVT::f32 || VT == MVT::f64) {
23184       bool ExpectingFlags = false;
23185       // Check for any users that want flags:
23186       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23187            !ExpectingFlags && UI != UE; ++UI)
23188         switch (UI->getOpcode()) {
23189         default:
23190         case ISD::BR_CC:
23191         case ISD::BRCOND:
23192         case ISD::SELECT:
23193           ExpectingFlags = true;
23194           break;
23195         case ISD::CopyToReg:
23196         case ISD::SIGN_EXTEND:
23197         case ISD::ZERO_EXTEND:
23198         case ISD::ANY_EXTEND:
23199           break;
23200         }
23201
23202       if (!ExpectingFlags) {
23203         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23204         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23205
23206         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23207           X86::CondCode tmp = cc0;
23208           cc0 = cc1;
23209           cc1 = tmp;
23210         }
23211
23212         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23213             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23214           // FIXME: need symbolic constants for these magic numbers.
23215           // See X86ATTInstPrinter.cpp:printSSECC().
23216           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23217           if (Subtarget->hasAVX512()) {
23218             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23219                                          CMP01,
23220                                          DAG.getConstant(x86cc, DL, MVT::i8));
23221             if (N->getValueType(0) != MVT::i1)
23222               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23223                                  FSetCC);
23224             return FSetCC;
23225           }
23226           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23227                                               CMP00.getValueType(), CMP00, CMP01,
23228                                               DAG.getConstant(x86cc, DL,
23229                                                               MVT::i8));
23230
23231           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23232           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23233
23234           if (is64BitFP && !Subtarget->is64Bit()) {
23235             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23236             // 64-bit integer, since that's not a legal type. Since
23237             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23238             // bits, but can do this little dance to extract the lowest 32 bits
23239             // and work with those going forward.
23240             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23241                                            OnesOrZeroesF);
23242             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23243             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23244                                         Vector32, DAG.getIntPtrConstant(0, DL));
23245             IntVT = MVT::i32;
23246           }
23247
23248           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23249           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23250                                       DAG.getConstant(1, DL, IntVT));
23251           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23252                                               ANDed);
23253           return OneBitOfTruth;
23254         }
23255       }
23256     }
23257   }
23258   return SDValue();
23259 }
23260
23261 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23262 /// so it can be folded inside ANDNP.
23263 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23264   EVT VT = N->getValueType(0);
23265
23266   // Match direct AllOnes for 128 and 256-bit vectors
23267   if (ISD::isBuildVectorAllOnes(N))
23268     return true;
23269
23270   // Look through a bit convert.
23271   if (N->getOpcode() == ISD::BITCAST)
23272     N = N->getOperand(0).getNode();
23273
23274   // Sometimes the operand may come from a insert_subvector building a 256-bit
23275   // allones vector
23276   if (VT.is256BitVector() &&
23277       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23278     SDValue V1 = N->getOperand(0);
23279     SDValue V2 = N->getOperand(1);
23280
23281     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23282         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23283         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23284         ISD::isBuildVectorAllOnes(V2.getNode()))
23285       return true;
23286   }
23287
23288   return false;
23289 }
23290
23291 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23292 // register. In most cases we actually compare or select YMM-sized registers
23293 // and mixing the two types creates horrible code. This method optimizes
23294 // some of the transition sequences.
23295 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23296                                  TargetLowering::DAGCombinerInfo &DCI,
23297                                  const X86Subtarget *Subtarget) {
23298   EVT VT = N->getValueType(0);
23299   if (!VT.is256BitVector())
23300     return SDValue();
23301
23302   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23303           N->getOpcode() == ISD::ZERO_EXTEND ||
23304           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23305
23306   SDValue Narrow = N->getOperand(0);
23307   EVT NarrowVT = Narrow->getValueType(0);
23308   if (!NarrowVT.is128BitVector())
23309     return SDValue();
23310
23311   if (Narrow->getOpcode() != ISD::XOR &&
23312       Narrow->getOpcode() != ISD::AND &&
23313       Narrow->getOpcode() != ISD::OR)
23314     return SDValue();
23315
23316   SDValue N0  = Narrow->getOperand(0);
23317   SDValue N1  = Narrow->getOperand(1);
23318   SDLoc DL(Narrow);
23319
23320   // The Left side has to be a trunc.
23321   if (N0.getOpcode() != ISD::TRUNCATE)
23322     return SDValue();
23323
23324   // The type of the truncated inputs.
23325   EVT WideVT = N0->getOperand(0)->getValueType(0);
23326   if (WideVT != VT)
23327     return SDValue();
23328
23329   // The right side has to be a 'trunc' or a constant vector.
23330   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23331   ConstantSDNode *RHSConstSplat = nullptr;
23332   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23333     RHSConstSplat = RHSBV->getConstantSplatNode();
23334   if (!RHSTrunc && !RHSConstSplat)
23335     return SDValue();
23336
23337   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23338
23339   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23340     return SDValue();
23341
23342   // Set N0 and N1 to hold the inputs to the new wide operation.
23343   N0 = N0->getOperand(0);
23344   if (RHSConstSplat) {
23345     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23346                      SDValue(RHSConstSplat, 0));
23347     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23348     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23349   } else if (RHSTrunc) {
23350     N1 = N1->getOperand(0);
23351   }
23352
23353   // Generate the wide operation.
23354   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23355   unsigned Opcode = N->getOpcode();
23356   switch (Opcode) {
23357   case ISD::ANY_EXTEND:
23358     return Op;
23359   case ISD::ZERO_EXTEND: {
23360     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23361     APInt Mask = APInt::getAllOnesValue(InBits);
23362     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23363     return DAG.getNode(ISD::AND, DL, VT,
23364                        Op, DAG.getConstant(Mask, DL, VT));
23365   }
23366   case ISD::SIGN_EXTEND:
23367     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23368                        Op, DAG.getValueType(NarrowVT));
23369   default:
23370     llvm_unreachable("Unexpected opcode");
23371   }
23372 }
23373
23374 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23375                                  TargetLowering::DAGCombinerInfo &DCI,
23376                                  const X86Subtarget *Subtarget) {
23377   SDValue N0 = N->getOperand(0);
23378   SDValue N1 = N->getOperand(1);
23379   SDLoc DL(N);
23380
23381   // A vector zext_in_reg may be represented as a shuffle,
23382   // feeding into a bitcast (this represents anyext) feeding into
23383   // an and with a mask.
23384   // We'd like to try to combine that into a shuffle with zero
23385   // plus a bitcast, removing the and.
23386   if (N0.getOpcode() != ISD::BITCAST ||
23387       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23388     return SDValue();
23389
23390   // The other side of the AND should be a splat of 2^C, where C
23391   // is the number of bits in the source type.
23392   if (N1.getOpcode() == ISD::BITCAST)
23393     N1 = N1.getOperand(0);
23394   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23395     return SDValue();
23396   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23397
23398   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23399   EVT SrcType = Shuffle->getValueType(0);
23400
23401   // We expect a single-source shuffle
23402   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23403     return SDValue();
23404
23405   unsigned SrcSize = SrcType.getScalarSizeInBits();
23406
23407   APInt SplatValue, SplatUndef;
23408   unsigned SplatBitSize;
23409   bool HasAnyUndefs;
23410   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23411                                 SplatBitSize, HasAnyUndefs))
23412     return SDValue();
23413
23414   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23415   // Make sure the splat matches the mask we expect
23416   if (SplatBitSize > ResSize ||
23417       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23418     return SDValue();
23419
23420   // Make sure the input and output size make sense
23421   if (SrcSize >= ResSize || ResSize % SrcSize)
23422     return SDValue();
23423
23424   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23425   // The number of u's between each two values depends on the ratio between
23426   // the source and dest type.
23427   unsigned ZextRatio = ResSize / SrcSize;
23428   bool IsZext = true;
23429   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23430     if (i % ZextRatio) {
23431       if (Shuffle->getMaskElt(i) > 0) {
23432         // Expected undef
23433         IsZext = false;
23434         break;
23435       }
23436     } else {
23437       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23438         // Expected element number
23439         IsZext = false;
23440         break;
23441       }
23442     }
23443   }
23444
23445   if (!IsZext)
23446     return SDValue();
23447
23448   // Ok, perform the transformation - replace the shuffle with
23449   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23450   // (instead of undef) where the k elements come from the zero vector.
23451   SmallVector<int, 8> Mask;
23452   unsigned NumElems = SrcType.getVectorNumElements();
23453   for (unsigned i = 0; i < NumElems; ++i)
23454     if (i % ZextRatio)
23455       Mask.push_back(NumElems);
23456     else
23457       Mask.push_back(i / ZextRatio);
23458
23459   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23460     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23461   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23462 }
23463
23464 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23465                                  TargetLowering::DAGCombinerInfo &DCI,
23466                                  const X86Subtarget *Subtarget) {
23467   if (DCI.isBeforeLegalizeOps())
23468     return SDValue();
23469
23470   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23471     return Zext;
23472
23473   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23474     return R;
23475
23476   EVT VT = N->getValueType(0);
23477   SDValue N0 = N->getOperand(0);
23478   SDValue N1 = N->getOperand(1);
23479   SDLoc DL(N);
23480
23481   // Create BEXTR instructions
23482   // BEXTR is ((X >> imm) & (2**size-1))
23483   if (VT == MVT::i32 || VT == MVT::i64) {
23484     // Check for BEXTR.
23485     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23486         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23487       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23488       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23489       if (MaskNode && ShiftNode) {
23490         uint64_t Mask = MaskNode->getZExtValue();
23491         uint64_t Shift = ShiftNode->getZExtValue();
23492         if (isMask_64(Mask)) {
23493           uint64_t MaskSize = countPopulation(Mask);
23494           if (Shift + MaskSize <= VT.getSizeInBits())
23495             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23496                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23497                                                VT));
23498         }
23499       }
23500     } // BEXTR
23501
23502     return SDValue();
23503   }
23504
23505   // Want to form ANDNP nodes:
23506   // 1) In the hopes of then easily combining them with OR and AND nodes
23507   //    to form PBLEND/PSIGN.
23508   // 2) To match ANDN packed intrinsics
23509   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23510     return SDValue();
23511
23512   // Check LHS for vnot
23513   if (N0.getOpcode() == ISD::XOR &&
23514       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23515       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23516     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23517
23518   // Check RHS for vnot
23519   if (N1.getOpcode() == ISD::XOR &&
23520       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23521       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23522     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23523
23524   return SDValue();
23525 }
23526
23527 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23528                                 TargetLowering::DAGCombinerInfo &DCI,
23529                                 const X86Subtarget *Subtarget) {
23530   if (DCI.isBeforeLegalizeOps())
23531     return SDValue();
23532
23533   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23534     return R;
23535
23536   SDValue N0 = N->getOperand(0);
23537   SDValue N1 = N->getOperand(1);
23538   EVT VT = N->getValueType(0);
23539
23540   // look for psign/blend
23541   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23542     if (!Subtarget->hasSSSE3() ||
23543         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23544       return SDValue();
23545
23546     // Canonicalize pandn to RHS
23547     if (N0.getOpcode() == X86ISD::ANDNP)
23548       std::swap(N0, N1);
23549     // or (and (m, y), (pandn m, x))
23550     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23551       SDValue Mask = N1.getOperand(0);
23552       SDValue X    = N1.getOperand(1);
23553       SDValue Y;
23554       if (N0.getOperand(0) == Mask)
23555         Y = N0.getOperand(1);
23556       if (N0.getOperand(1) == Mask)
23557         Y = N0.getOperand(0);
23558
23559       // Check to see if the mask appeared in both the AND and ANDNP and
23560       if (!Y.getNode())
23561         return SDValue();
23562
23563       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23564       // Look through mask bitcast.
23565       if (Mask.getOpcode() == ISD::BITCAST)
23566         Mask = Mask.getOperand(0);
23567       if (X.getOpcode() == ISD::BITCAST)
23568         X = X.getOperand(0);
23569       if (Y.getOpcode() == ISD::BITCAST)
23570         Y = Y.getOperand(0);
23571
23572       EVT MaskVT = Mask.getValueType();
23573
23574       // Validate that the Mask operand is a vector sra node.
23575       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23576       // there is no psrai.b
23577       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23578       unsigned SraAmt = ~0;
23579       if (Mask.getOpcode() == ISD::SRA) {
23580         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23581           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23582             SraAmt = AmtConst->getZExtValue();
23583       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23584         SDValue SraC = Mask.getOperand(1);
23585         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23586       }
23587       if ((SraAmt + 1) != EltBits)
23588         return SDValue();
23589
23590       SDLoc DL(N);
23591
23592       // Now we know we at least have a plendvb with the mask val.  See if
23593       // we can form a psignb/w/d.
23594       // psign = x.type == y.type == mask.type && y = sub(0, x);
23595       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23596           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23597           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23598         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23599                "Unsupported VT for PSIGN");
23600         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23601         return DAG.getBitcast(VT, Mask);
23602       }
23603       // PBLENDVB only available on SSE 4.1
23604       if (!Subtarget->hasSSE41())
23605         return SDValue();
23606
23607       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23608
23609       X = DAG.getBitcast(BlendVT, X);
23610       Y = DAG.getBitcast(BlendVT, Y);
23611       Mask = DAG.getBitcast(BlendVT, Mask);
23612       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23613       return DAG.getBitcast(VT, Mask);
23614     }
23615   }
23616
23617   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23618     return SDValue();
23619
23620   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23621   MachineFunction &MF = DAG.getMachineFunction();
23622   bool OptForSize =
23623       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23624
23625   // SHLD/SHRD instructions have lower register pressure, but on some
23626   // platforms they have higher latency than the equivalent
23627   // series of shifts/or that would otherwise be generated.
23628   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23629   // have higher latencies and we are not optimizing for size.
23630   if (!OptForSize && Subtarget->isSHLDSlow())
23631     return SDValue();
23632
23633   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23634     std::swap(N0, N1);
23635   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23636     return SDValue();
23637   if (!N0.hasOneUse() || !N1.hasOneUse())
23638     return SDValue();
23639
23640   SDValue ShAmt0 = N0.getOperand(1);
23641   if (ShAmt0.getValueType() != MVT::i8)
23642     return SDValue();
23643   SDValue ShAmt1 = N1.getOperand(1);
23644   if (ShAmt1.getValueType() != MVT::i8)
23645     return SDValue();
23646   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23647     ShAmt0 = ShAmt0.getOperand(0);
23648   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23649     ShAmt1 = ShAmt1.getOperand(0);
23650
23651   SDLoc DL(N);
23652   unsigned Opc = X86ISD::SHLD;
23653   SDValue Op0 = N0.getOperand(0);
23654   SDValue Op1 = N1.getOperand(0);
23655   if (ShAmt0.getOpcode() == ISD::SUB) {
23656     Opc = X86ISD::SHRD;
23657     std::swap(Op0, Op1);
23658     std::swap(ShAmt0, ShAmt1);
23659   }
23660
23661   unsigned Bits = VT.getSizeInBits();
23662   if (ShAmt1.getOpcode() == ISD::SUB) {
23663     SDValue Sum = ShAmt1.getOperand(0);
23664     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23665       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23666       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23667         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23668       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23669         return DAG.getNode(Opc, DL, VT,
23670                            Op0, Op1,
23671                            DAG.getNode(ISD::TRUNCATE, DL,
23672                                        MVT::i8, ShAmt0));
23673     }
23674   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23675     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23676     if (ShAmt0C &&
23677         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23678       return DAG.getNode(Opc, DL, VT,
23679                          N0.getOperand(0), N1.getOperand(0),
23680                          DAG.getNode(ISD::TRUNCATE, DL,
23681                                        MVT::i8, ShAmt0));
23682   }
23683
23684   return SDValue();
23685 }
23686
23687 // Generate NEG and CMOV for integer abs.
23688 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23689   EVT VT = N->getValueType(0);
23690
23691   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23692   // 8-bit integer abs to NEG and CMOV.
23693   if (VT.isInteger() && VT.getSizeInBits() == 8)
23694     return SDValue();
23695
23696   SDValue N0 = N->getOperand(0);
23697   SDValue N1 = N->getOperand(1);
23698   SDLoc DL(N);
23699
23700   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23701   // and change it to SUB and CMOV.
23702   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23703       N0.getOpcode() == ISD::ADD &&
23704       N0.getOperand(1) == N1 &&
23705       N1.getOpcode() == ISD::SRA &&
23706       N1.getOperand(0) == N0.getOperand(0))
23707     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23708       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23709         // Generate SUB & CMOV.
23710         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23711                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23712
23713         SDValue Ops[] = { N0.getOperand(0), Neg,
23714                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23715                           SDValue(Neg.getNode(), 1) };
23716         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23717       }
23718   return SDValue();
23719 }
23720
23721 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23722 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23723                                  TargetLowering::DAGCombinerInfo &DCI,
23724                                  const X86Subtarget *Subtarget) {
23725   if (DCI.isBeforeLegalizeOps())
23726     return SDValue();
23727
23728   if (Subtarget->hasCMov())
23729     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23730       return RV;
23731
23732   return SDValue();
23733 }
23734
23735 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23736 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23737                                   TargetLowering::DAGCombinerInfo &DCI,
23738                                   const X86Subtarget *Subtarget) {
23739   LoadSDNode *Ld = cast<LoadSDNode>(N);
23740   EVT RegVT = Ld->getValueType(0);
23741   EVT MemVT = Ld->getMemoryVT();
23742   SDLoc dl(Ld);
23743   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23744
23745   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23746   // into two 16-byte operations.
23747   ISD::LoadExtType Ext = Ld->getExtensionType();
23748   unsigned Alignment = Ld->getAlignment();
23749   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23750   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23751       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23752     unsigned NumElems = RegVT.getVectorNumElements();
23753     if (NumElems < 2)
23754       return SDValue();
23755
23756     SDValue Ptr = Ld->getBasePtr();
23757     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23758
23759     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23760                                   NumElems/2);
23761     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23762                                 Ld->getPointerInfo(), Ld->isVolatile(),
23763                                 Ld->isNonTemporal(), Ld->isInvariant(),
23764                                 Alignment);
23765     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23766     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23767                                 Ld->getPointerInfo(), Ld->isVolatile(),
23768                                 Ld->isNonTemporal(), Ld->isInvariant(),
23769                                 std::min(16U, Alignment));
23770     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23771                              Load1.getValue(1),
23772                              Load2.getValue(1));
23773
23774     SDValue NewVec = DAG.getUNDEF(RegVT);
23775     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23776     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23777     return DCI.CombineTo(N, NewVec, TF, true);
23778   }
23779
23780   return SDValue();
23781 }
23782
23783 /// PerformMLOADCombine - Resolve extending loads
23784 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23785                                    TargetLowering::DAGCombinerInfo &DCI,
23786                                    const X86Subtarget *Subtarget) {
23787   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23788   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23789     return SDValue();
23790
23791   EVT VT = Mld->getValueType(0);
23792   unsigned NumElems = VT.getVectorNumElements();
23793   EVT LdVT = Mld->getMemoryVT();
23794   SDLoc dl(Mld);
23795
23796   assert(LdVT != VT && "Cannot extend to the same type");
23797   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23798   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23799   // From, To sizes and ElemCount must be pow of two
23800   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23801     "Unexpected size for extending masked load");
23802
23803   unsigned SizeRatio  = ToSz / FromSz;
23804   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23805
23806   // Create a type on which we perform the shuffle
23807   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23808           LdVT.getScalarType(), NumElems*SizeRatio);
23809   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23810
23811   // Convert Src0 value
23812   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23813   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23814     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23815     for (unsigned i = 0; i != NumElems; ++i)
23816       ShuffleVec[i] = i * SizeRatio;
23817
23818     // Can't shuffle using an illegal type.
23819     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23820             && "WideVecVT should be legal");
23821     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23822                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23823   }
23824   // Prepare the new mask
23825   SDValue NewMask;
23826   SDValue Mask = Mld->getMask();
23827   if (Mask.getValueType() == VT) {
23828     // Mask and original value have the same type
23829     NewMask = DAG.getBitcast(WideVecVT, Mask);
23830     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23831     for (unsigned i = 0; i != NumElems; ++i)
23832       ShuffleVec[i] = i * SizeRatio;
23833     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23834       ShuffleVec[i] = NumElems*SizeRatio;
23835     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23836                                    DAG.getConstant(0, dl, WideVecVT),
23837                                    &ShuffleVec[0]);
23838   }
23839   else {
23840     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23841     unsigned WidenNumElts = NumElems*SizeRatio;
23842     unsigned MaskNumElts = VT.getVectorNumElements();
23843     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23844                                      WidenNumElts);
23845
23846     unsigned NumConcat = WidenNumElts / MaskNumElts;
23847     SmallVector<SDValue, 16> Ops(NumConcat);
23848     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23849     Ops[0] = Mask;
23850     for (unsigned i = 1; i != NumConcat; ++i)
23851       Ops[i] = ZeroVal;
23852
23853     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23854   }
23855
23856   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23857                                      Mld->getBasePtr(), NewMask, WideSrc0,
23858                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23859                                      ISD::NON_EXTLOAD);
23860   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23861   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23862
23863 }
23864 /// PerformMSTORECombine - Resolve truncating stores
23865 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23866                                     const X86Subtarget *Subtarget) {
23867   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23868   if (!Mst->isTruncatingStore())
23869     return SDValue();
23870
23871   EVT VT = Mst->getValue().getValueType();
23872   unsigned NumElems = VT.getVectorNumElements();
23873   EVT StVT = Mst->getMemoryVT();
23874   SDLoc dl(Mst);
23875
23876   assert(StVT != VT && "Cannot truncate to the same type");
23877   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23878   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23879
23880   // From, To sizes and ElemCount must be pow of two
23881   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23882     "Unexpected size for truncating masked store");
23883   // We are going to use the original vector elt for storing.
23884   // Accumulated smaller vector elements must be a multiple of the store size.
23885   assert (((NumElems * FromSz) % ToSz) == 0 &&
23886           "Unexpected ratio for truncating masked store");
23887
23888   unsigned SizeRatio  = FromSz / ToSz;
23889   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23890
23891   // Create a type on which we perform the shuffle
23892   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23893           StVT.getScalarType(), NumElems*SizeRatio);
23894
23895   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23896
23897   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
23898   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23899   for (unsigned i = 0; i != NumElems; ++i)
23900     ShuffleVec[i] = i * SizeRatio;
23901
23902   // Can't shuffle using an illegal type.
23903   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23904           && "WideVecVT should be legal");
23905
23906   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23907                                         DAG.getUNDEF(WideVecVT),
23908                                         &ShuffleVec[0]);
23909
23910   SDValue NewMask;
23911   SDValue Mask = Mst->getMask();
23912   if (Mask.getValueType() == VT) {
23913     // Mask and original value have the same type
23914     NewMask = DAG.getBitcast(WideVecVT, Mask);
23915     for (unsigned i = 0; i != NumElems; ++i)
23916       ShuffleVec[i] = i * SizeRatio;
23917     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23918       ShuffleVec[i] = NumElems*SizeRatio;
23919     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23920                                    DAG.getConstant(0, dl, WideVecVT),
23921                                    &ShuffleVec[0]);
23922   }
23923   else {
23924     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23925     unsigned WidenNumElts = NumElems*SizeRatio;
23926     unsigned MaskNumElts = VT.getVectorNumElements();
23927     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23928                                      WidenNumElts);
23929
23930     unsigned NumConcat = WidenNumElts / MaskNumElts;
23931     SmallVector<SDValue, 16> Ops(NumConcat);
23932     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23933     Ops[0] = Mask;
23934     for (unsigned i = 1; i != NumConcat; ++i)
23935       Ops[i] = ZeroVal;
23936
23937     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23938   }
23939
23940   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23941                             NewMask, StVT, Mst->getMemOperand(), false);
23942 }
23943 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23944 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23945                                    const X86Subtarget *Subtarget) {
23946   StoreSDNode *St = cast<StoreSDNode>(N);
23947   EVT VT = St->getValue().getValueType();
23948   EVT StVT = St->getMemoryVT();
23949   SDLoc dl(St);
23950   SDValue StoredVal = St->getOperand(1);
23951   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23952
23953   // If we are saving a concatenation of two XMM registers and 32-byte stores
23954   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23955   unsigned Alignment = St->getAlignment();
23956   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23957   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23958       StVT == VT && !IsAligned) {
23959     unsigned NumElems = VT.getVectorNumElements();
23960     if (NumElems < 2)
23961       return SDValue();
23962
23963     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23964     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23965
23966     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23967     SDValue Ptr0 = St->getBasePtr();
23968     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23969
23970     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23971                                 St->getPointerInfo(), St->isVolatile(),
23972                                 St->isNonTemporal(), Alignment);
23973     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23974                                 St->getPointerInfo(), St->isVolatile(),
23975                                 St->isNonTemporal(),
23976                                 std::min(16U, Alignment));
23977     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23978   }
23979
23980   // Optimize trunc store (of multiple scalars) to shuffle and store.
23981   // First, pack all of the elements in one place. Next, store to memory
23982   // in fewer chunks.
23983   if (St->isTruncatingStore() && VT.isVector()) {
23984     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23985     unsigned NumElems = VT.getVectorNumElements();
23986     assert(StVT != VT && "Cannot truncate to the same type");
23987     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23988     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23989
23990     // From, To sizes and ElemCount must be pow of two
23991     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23992     // We are going to use the original vector elt for storing.
23993     // Accumulated smaller vector elements must be a multiple of the store size.
23994     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23995
23996     unsigned SizeRatio  = FromSz / ToSz;
23997
23998     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23999
24000     // Create a type on which we perform the shuffle
24001     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24002             StVT.getScalarType(), NumElems*SizeRatio);
24003
24004     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24005
24006     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24007     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24008     for (unsigned i = 0; i != NumElems; ++i)
24009       ShuffleVec[i] = i * SizeRatio;
24010
24011     // Can't shuffle using an illegal type.
24012     if (!TLI.isTypeLegal(WideVecVT))
24013       return SDValue();
24014
24015     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24016                                          DAG.getUNDEF(WideVecVT),
24017                                          &ShuffleVec[0]);
24018     // At this point all of the data is stored at the bottom of the
24019     // register. We now need to save it to mem.
24020
24021     // Find the largest store unit
24022     MVT StoreType = MVT::i8;
24023     for (MVT Tp : MVT::integer_valuetypes()) {
24024       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24025         StoreType = Tp;
24026     }
24027
24028     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24029     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24030         (64 <= NumElems * ToSz))
24031       StoreType = MVT::f64;
24032
24033     // Bitcast the original vector into a vector of store-size units
24034     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24035             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24036     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24037     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24038     SmallVector<SDValue, 8> Chains;
24039     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
24040                                         TLI.getPointerTy());
24041     SDValue Ptr = St->getBasePtr();
24042
24043     // Perform one or more big stores into memory.
24044     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24045       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24046                                    StoreType, ShuffWide,
24047                                    DAG.getIntPtrConstant(i, dl));
24048       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24049                                 St->getPointerInfo(), St->isVolatile(),
24050                                 St->isNonTemporal(), St->getAlignment());
24051       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24052       Chains.push_back(Ch);
24053     }
24054
24055     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24056   }
24057
24058   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24059   // the FP state in cases where an emms may be missing.
24060   // A preferable solution to the general problem is to figure out the right
24061   // places to insert EMMS.  This qualifies as a quick hack.
24062
24063   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24064   if (VT.getSizeInBits() != 64)
24065     return SDValue();
24066
24067   const Function *F = DAG.getMachineFunction().getFunction();
24068   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24069   bool F64IsLegal =
24070       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24071   if ((VT.isVector() ||
24072        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24073       isa<LoadSDNode>(St->getValue()) &&
24074       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24075       St->getChain().hasOneUse() && !St->isVolatile()) {
24076     SDNode* LdVal = St->getValue().getNode();
24077     LoadSDNode *Ld = nullptr;
24078     int TokenFactorIndex = -1;
24079     SmallVector<SDValue, 8> Ops;
24080     SDNode* ChainVal = St->getChain().getNode();
24081     // Must be a store of a load.  We currently handle two cases:  the load
24082     // is a direct child, and it's under an intervening TokenFactor.  It is
24083     // possible to dig deeper under nested TokenFactors.
24084     if (ChainVal == LdVal)
24085       Ld = cast<LoadSDNode>(St->getChain());
24086     else if (St->getValue().hasOneUse() &&
24087              ChainVal->getOpcode() == ISD::TokenFactor) {
24088       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24089         if (ChainVal->getOperand(i).getNode() == LdVal) {
24090           TokenFactorIndex = i;
24091           Ld = cast<LoadSDNode>(St->getValue());
24092         } else
24093           Ops.push_back(ChainVal->getOperand(i));
24094       }
24095     }
24096
24097     if (!Ld || !ISD::isNormalLoad(Ld))
24098       return SDValue();
24099
24100     // If this is not the MMX case, i.e. we are just turning i64 load/store
24101     // into f64 load/store, avoid the transformation if there are multiple
24102     // uses of the loaded value.
24103     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24104       return SDValue();
24105
24106     SDLoc LdDL(Ld);
24107     SDLoc StDL(N);
24108     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24109     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24110     // pair instead.
24111     if (Subtarget->is64Bit() || F64IsLegal) {
24112       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24113       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24114                                   Ld->getPointerInfo(), Ld->isVolatile(),
24115                                   Ld->isNonTemporal(), Ld->isInvariant(),
24116                                   Ld->getAlignment());
24117       SDValue NewChain = NewLd.getValue(1);
24118       if (TokenFactorIndex != -1) {
24119         Ops.push_back(NewChain);
24120         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24121       }
24122       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24123                           St->getPointerInfo(),
24124                           St->isVolatile(), St->isNonTemporal(),
24125                           St->getAlignment());
24126     }
24127
24128     // Otherwise, lower to two pairs of 32-bit loads / stores.
24129     SDValue LoAddr = Ld->getBasePtr();
24130     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24131                                  DAG.getConstant(4, LdDL, MVT::i32));
24132
24133     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24134                                Ld->getPointerInfo(),
24135                                Ld->isVolatile(), Ld->isNonTemporal(),
24136                                Ld->isInvariant(), Ld->getAlignment());
24137     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24138                                Ld->getPointerInfo().getWithOffset(4),
24139                                Ld->isVolatile(), Ld->isNonTemporal(),
24140                                Ld->isInvariant(),
24141                                MinAlign(Ld->getAlignment(), 4));
24142
24143     SDValue NewChain = LoLd.getValue(1);
24144     if (TokenFactorIndex != -1) {
24145       Ops.push_back(LoLd);
24146       Ops.push_back(HiLd);
24147       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24148     }
24149
24150     LoAddr = St->getBasePtr();
24151     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24152                          DAG.getConstant(4, StDL, MVT::i32));
24153
24154     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24155                                 St->getPointerInfo(),
24156                                 St->isVolatile(), St->isNonTemporal(),
24157                                 St->getAlignment());
24158     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24159                                 St->getPointerInfo().getWithOffset(4),
24160                                 St->isVolatile(),
24161                                 St->isNonTemporal(),
24162                                 MinAlign(St->getAlignment(), 4));
24163     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24164   }
24165
24166   // This is similar to the above case, but here we handle a scalar 64-bit
24167   // integer store that is extracted from a vector on a 32-bit target.
24168   // If we have SSE2, then we can treat it like a floating-point double
24169   // to get past legalization. The execution dependencies fixup pass will
24170   // choose the optimal machine instruction for the store if this really is
24171   // an integer or v2f32 rather than an f64.
24172   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24173       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24174     SDValue OldExtract = St->getOperand(1);
24175     SDValue ExtOp0 = OldExtract.getOperand(0);
24176     unsigned VecSize = ExtOp0.getValueSizeInBits();
24177     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24178     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24179     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24180                                      BitCast, OldExtract.getOperand(1));
24181     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24182                         St->getPointerInfo(), St->isVolatile(),
24183                         St->isNonTemporal(), St->getAlignment());
24184   }
24185
24186   return SDValue();
24187 }
24188
24189 /// Return 'true' if this vector operation is "horizontal"
24190 /// and return the operands for the horizontal operation in LHS and RHS.  A
24191 /// horizontal operation performs the binary operation on successive elements
24192 /// of its first operand, then on successive elements of its second operand,
24193 /// returning the resulting values in a vector.  For example, if
24194 ///   A = < float a0, float a1, float a2, float a3 >
24195 /// and
24196 ///   B = < float b0, float b1, float b2, float b3 >
24197 /// then the result of doing a horizontal operation on A and B is
24198 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24199 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24200 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24201 /// set to A, RHS to B, and the routine returns 'true'.
24202 /// Note that the binary operation should have the property that if one of the
24203 /// operands is UNDEF then the result is UNDEF.
24204 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24205   // Look for the following pattern: if
24206   //   A = < float a0, float a1, float a2, float a3 >
24207   //   B = < float b0, float b1, float b2, float b3 >
24208   // and
24209   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24210   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24211   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24212   // which is A horizontal-op B.
24213
24214   // At least one of the operands should be a vector shuffle.
24215   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24216       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24217     return false;
24218
24219   MVT VT = LHS.getSimpleValueType();
24220
24221   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24222          "Unsupported vector type for horizontal add/sub");
24223
24224   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24225   // operate independently on 128-bit lanes.
24226   unsigned NumElts = VT.getVectorNumElements();
24227   unsigned NumLanes = VT.getSizeInBits()/128;
24228   unsigned NumLaneElts = NumElts / NumLanes;
24229   assert((NumLaneElts % 2 == 0) &&
24230          "Vector type should have an even number of elements in each lane");
24231   unsigned HalfLaneElts = NumLaneElts/2;
24232
24233   // View LHS in the form
24234   //   LHS = VECTOR_SHUFFLE A, B, LMask
24235   // If LHS is not a shuffle then pretend it is the shuffle
24236   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24237   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24238   // type VT.
24239   SDValue A, B;
24240   SmallVector<int, 16> LMask(NumElts);
24241   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24242     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24243       A = LHS.getOperand(0);
24244     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24245       B = LHS.getOperand(1);
24246     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24247     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24248   } else {
24249     if (LHS.getOpcode() != ISD::UNDEF)
24250       A = LHS;
24251     for (unsigned i = 0; i != NumElts; ++i)
24252       LMask[i] = i;
24253   }
24254
24255   // Likewise, view RHS in the form
24256   //   RHS = VECTOR_SHUFFLE C, D, RMask
24257   SDValue C, D;
24258   SmallVector<int, 16> RMask(NumElts);
24259   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24260     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24261       C = RHS.getOperand(0);
24262     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24263       D = RHS.getOperand(1);
24264     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24265     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24266   } else {
24267     if (RHS.getOpcode() != ISD::UNDEF)
24268       C = RHS;
24269     for (unsigned i = 0; i != NumElts; ++i)
24270       RMask[i] = i;
24271   }
24272
24273   // Check that the shuffles are both shuffling the same vectors.
24274   if (!(A == C && B == D) && !(A == D && B == C))
24275     return false;
24276
24277   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24278   if (!A.getNode() && !B.getNode())
24279     return false;
24280
24281   // If A and B occur in reverse order in RHS, then "swap" them (which means
24282   // rewriting the mask).
24283   if (A != C)
24284     ShuffleVectorSDNode::commuteMask(RMask);
24285
24286   // At this point LHS and RHS are equivalent to
24287   //   LHS = VECTOR_SHUFFLE A, B, LMask
24288   //   RHS = VECTOR_SHUFFLE A, B, RMask
24289   // Check that the masks correspond to performing a horizontal operation.
24290   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24291     for (unsigned i = 0; i != NumLaneElts; ++i) {
24292       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24293
24294       // Ignore any UNDEF components.
24295       if (LIdx < 0 || RIdx < 0 ||
24296           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24297           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24298         continue;
24299
24300       // Check that successive elements are being operated on.  If not, this is
24301       // not a horizontal operation.
24302       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24303       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24304       if (!(LIdx == Index && RIdx == Index + 1) &&
24305           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24306         return false;
24307     }
24308   }
24309
24310   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24311   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24312   return true;
24313 }
24314
24315 /// Do target-specific dag combines on floating point adds.
24316 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24317                                   const X86Subtarget *Subtarget) {
24318   EVT VT = N->getValueType(0);
24319   SDValue LHS = N->getOperand(0);
24320   SDValue RHS = N->getOperand(1);
24321
24322   // Try to synthesize horizontal adds from adds of shuffles.
24323   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24324        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24325       isHorizontalBinOp(LHS, RHS, true))
24326     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24327   return SDValue();
24328 }
24329
24330 /// Do target-specific dag combines on floating point subs.
24331 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24332                                   const X86Subtarget *Subtarget) {
24333   EVT VT = N->getValueType(0);
24334   SDValue LHS = N->getOperand(0);
24335   SDValue RHS = N->getOperand(1);
24336
24337   // Try to synthesize horizontal subs from subs of shuffles.
24338   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24339        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24340       isHorizontalBinOp(LHS, RHS, false))
24341     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24342   return SDValue();
24343 }
24344
24345 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24346 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24347   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24348
24349   // F[X]OR(0.0, x) -> x
24350   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24351     if (C->getValueAPF().isPosZero())
24352       return N->getOperand(1);
24353
24354   // F[X]OR(x, 0.0) -> x
24355   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24356     if (C->getValueAPF().isPosZero())
24357       return N->getOperand(0);
24358   return SDValue();
24359 }
24360
24361 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24362 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24363   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24364
24365   // Only perform optimizations if UnsafeMath is used.
24366   if (!DAG.getTarget().Options.UnsafeFPMath)
24367     return SDValue();
24368
24369   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24370   // into FMINC and FMAXC, which are Commutative operations.
24371   unsigned NewOp = 0;
24372   switch (N->getOpcode()) {
24373     default: llvm_unreachable("unknown opcode");
24374     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24375     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24376   }
24377
24378   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24379                      N->getOperand(0), N->getOperand(1));
24380 }
24381
24382 /// Do target-specific dag combines on X86ISD::FAND nodes.
24383 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24384   // FAND(0.0, x) -> 0.0
24385   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24386     if (C->getValueAPF().isPosZero())
24387       return N->getOperand(0);
24388
24389   // FAND(x, 0.0) -> 0.0
24390   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24391     if (C->getValueAPF().isPosZero())
24392       return N->getOperand(1);
24393
24394   return SDValue();
24395 }
24396
24397 /// Do target-specific dag combines on X86ISD::FANDN nodes
24398 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24399   // FANDN(0.0, x) -> x
24400   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24401     if (C->getValueAPF().isPosZero())
24402       return N->getOperand(1);
24403
24404   // FANDN(x, 0.0) -> 0.0
24405   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24406     if (C->getValueAPF().isPosZero())
24407       return N->getOperand(1);
24408
24409   return SDValue();
24410 }
24411
24412 static SDValue PerformBTCombine(SDNode *N,
24413                                 SelectionDAG &DAG,
24414                                 TargetLowering::DAGCombinerInfo &DCI) {
24415   // BT ignores high bits in the bit index operand.
24416   SDValue Op1 = N->getOperand(1);
24417   if (Op1.hasOneUse()) {
24418     unsigned BitWidth = Op1.getValueSizeInBits();
24419     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24420     APInt KnownZero, KnownOne;
24421     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24422                                           !DCI.isBeforeLegalizeOps());
24423     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24424     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24425         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24426       DCI.CommitTargetLoweringOpt(TLO);
24427   }
24428   return SDValue();
24429 }
24430
24431 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24432   SDValue Op = N->getOperand(0);
24433   if (Op.getOpcode() == ISD::BITCAST)
24434     Op = Op.getOperand(0);
24435   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24436   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24437       VT.getVectorElementType().getSizeInBits() ==
24438       OpVT.getVectorElementType().getSizeInBits()) {
24439     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24440   }
24441   return SDValue();
24442 }
24443
24444 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24445                                                const X86Subtarget *Subtarget) {
24446   EVT VT = N->getValueType(0);
24447   if (!VT.isVector())
24448     return SDValue();
24449
24450   SDValue N0 = N->getOperand(0);
24451   SDValue N1 = N->getOperand(1);
24452   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24453   SDLoc dl(N);
24454
24455   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24456   // both SSE and AVX2 since there is no sign-extended shift right
24457   // operation on a vector with 64-bit elements.
24458   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24459   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24460   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24461       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24462     SDValue N00 = N0.getOperand(0);
24463
24464     // EXTLOAD has a better solution on AVX2,
24465     // it may be replaced with X86ISD::VSEXT node.
24466     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24467       if (!ISD::isNormalLoad(N00.getNode()))
24468         return SDValue();
24469
24470     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24471         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24472                                   N00, N1);
24473       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24474     }
24475   }
24476   return SDValue();
24477 }
24478
24479 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24480                                   TargetLowering::DAGCombinerInfo &DCI,
24481                                   const X86Subtarget *Subtarget) {
24482   SDValue N0 = N->getOperand(0);
24483   EVT VT = N->getValueType(0);
24484   EVT SVT = VT.getScalarType();
24485   EVT InVT = N0.getValueType();
24486   EVT InSVT = InVT.getScalarType();
24487   SDLoc DL(N);
24488
24489   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24490   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24491   // This exposes the sext to the sdivrem lowering, so that it directly extends
24492   // from AH (which we otherwise need to do contortions to access).
24493   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24494       InVT == MVT::i8 && VT == MVT::i32) {
24495     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24496     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24497                             N0.getOperand(0), N0.getOperand(1));
24498     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24499     return R.getValue(1);
24500   }
24501
24502   if (!DCI.isBeforeLegalizeOps()) {
24503     if (InVT == MVT::i1) {
24504       SDValue Zero = DAG.getConstant(0, DL, VT);
24505       SDValue AllOnes =
24506         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24507       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24508     }
24509     return SDValue();
24510   }
24511
24512   if (VT.isVector() && Subtarget->hasSSE2()) {
24513     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24514       EVT InVT = N.getValueType();
24515       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24516                                    Size / InVT.getScalarSizeInBits());
24517       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24518                                     DAG.getUNDEF(InVT));
24519       Opnds[0] = N;
24520       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24521     };
24522
24523     // If target-size is less than 128-bits, extend to a type that would extend
24524     // to 128 bits, extend that and extract the original target vector.
24525     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24526         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24527         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24528       unsigned Scale = 128 / VT.getSizeInBits();
24529       EVT ExVT =
24530           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24531       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24532       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24533       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24534                          DAG.getIntPtrConstant(0, DL));
24535     }
24536
24537     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24538     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24539     if (VT.getSizeInBits() == 128 &&
24540         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24541         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24542       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24543       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24544     }
24545
24546     // On pre-AVX2 targets, split into 128-bit nodes of
24547     // ISD::SIGN_EXTEND_VECTOR_INREG.
24548     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24549         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24550         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24551       unsigned NumVecs = VT.getSizeInBits() / 128;
24552       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24553       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24554       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24555
24556       SmallVector<SDValue, 8> Opnds;
24557       for (unsigned i = 0, Offset = 0; i != NumVecs;
24558            ++i, Offset += NumSubElts) {
24559         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24560                                      DAG.getIntPtrConstant(Offset, DL));
24561         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24562         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24563         Opnds.push_back(SrcVec);
24564       }
24565       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24566     }
24567   }
24568
24569   if (!Subtarget->hasFp256())
24570     return SDValue();
24571
24572   if (VT.isVector() && VT.getSizeInBits() == 256)
24573     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24574       return R;
24575
24576   return SDValue();
24577 }
24578
24579 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24580                                  const X86Subtarget* Subtarget) {
24581   SDLoc dl(N);
24582   EVT VT = N->getValueType(0);
24583
24584   // Let legalize expand this if it isn't a legal type yet.
24585   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24586     return SDValue();
24587
24588   EVT ScalarVT = VT.getScalarType();
24589   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24590       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24591        !Subtarget->hasAVX512()))
24592     return SDValue();
24593
24594   SDValue A = N->getOperand(0);
24595   SDValue B = N->getOperand(1);
24596   SDValue C = N->getOperand(2);
24597
24598   bool NegA = (A.getOpcode() == ISD::FNEG);
24599   bool NegB = (B.getOpcode() == ISD::FNEG);
24600   bool NegC = (C.getOpcode() == ISD::FNEG);
24601
24602   // Negative multiplication when NegA xor NegB
24603   bool NegMul = (NegA != NegB);
24604   if (NegA)
24605     A = A.getOperand(0);
24606   if (NegB)
24607     B = B.getOperand(0);
24608   if (NegC)
24609     C = C.getOperand(0);
24610
24611   unsigned Opcode;
24612   if (!NegMul)
24613     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24614   else
24615     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24616
24617   return DAG.getNode(Opcode, dl, VT, A, B, C);
24618 }
24619
24620 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24621                                   TargetLowering::DAGCombinerInfo &DCI,
24622                                   const X86Subtarget *Subtarget) {
24623   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24624   //           (and (i32 x86isd::setcc_carry), 1)
24625   // This eliminates the zext. This transformation is necessary because
24626   // ISD::SETCC is always legalized to i8.
24627   SDLoc dl(N);
24628   SDValue N0 = N->getOperand(0);
24629   EVT VT = N->getValueType(0);
24630
24631   if (N0.getOpcode() == ISD::AND &&
24632       N0.hasOneUse() &&
24633       N0.getOperand(0).hasOneUse()) {
24634     SDValue N00 = N0.getOperand(0);
24635     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24636       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24637       if (!C || C->getZExtValue() != 1)
24638         return SDValue();
24639       return DAG.getNode(ISD::AND, dl, VT,
24640                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24641                                      N00.getOperand(0), N00.getOperand(1)),
24642                          DAG.getConstant(1, dl, VT));
24643     }
24644   }
24645
24646   if (N0.getOpcode() == ISD::TRUNCATE &&
24647       N0.hasOneUse() &&
24648       N0.getOperand(0).hasOneUse()) {
24649     SDValue N00 = N0.getOperand(0);
24650     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24651       return DAG.getNode(ISD::AND, dl, VT,
24652                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24653                                      N00.getOperand(0), N00.getOperand(1)),
24654                          DAG.getConstant(1, dl, VT));
24655     }
24656   }
24657
24658   if (VT.is256BitVector())
24659     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24660       return R;
24661
24662   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24663   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24664   // This exposes the zext to the udivrem lowering, so that it directly extends
24665   // from AH (which we otherwise need to do contortions to access).
24666   if (N0.getOpcode() == ISD::UDIVREM &&
24667       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24668       (VT == MVT::i32 || VT == MVT::i64)) {
24669     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24670     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24671                             N0.getOperand(0), N0.getOperand(1));
24672     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24673     return R.getValue(1);
24674   }
24675
24676   return SDValue();
24677 }
24678
24679 // Optimize x == -y --> x+y == 0
24680 //          x != -y --> x+y != 0
24681 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24682                                       const X86Subtarget* Subtarget) {
24683   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24684   SDValue LHS = N->getOperand(0);
24685   SDValue RHS = N->getOperand(1);
24686   EVT VT = N->getValueType(0);
24687   SDLoc DL(N);
24688
24689   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24690     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24691       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24692         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24693                                    LHS.getOperand(1));
24694         return DAG.getSetCC(DL, N->getValueType(0), addV,
24695                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24696       }
24697   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24698     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24699       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24700         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24701                                    RHS.getOperand(1));
24702         return DAG.getSetCC(DL, N->getValueType(0), addV,
24703                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24704       }
24705
24706   if (VT.getScalarType() == MVT::i1 &&
24707       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24708     bool IsSEXT0 =
24709         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24710         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24711     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24712
24713     if (!IsSEXT0 || !IsVZero1) {
24714       // Swap the operands and update the condition code.
24715       std::swap(LHS, RHS);
24716       CC = ISD::getSetCCSwappedOperands(CC);
24717
24718       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24719                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24720       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24721     }
24722
24723     if (IsSEXT0 && IsVZero1) {
24724       assert(VT == LHS.getOperand(0).getValueType() &&
24725              "Uexpected operand type");
24726       if (CC == ISD::SETGT)
24727         return DAG.getConstant(0, DL, VT);
24728       if (CC == ISD::SETLE)
24729         return DAG.getConstant(1, DL, VT);
24730       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24731         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24732
24733       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24734              "Unexpected condition code!");
24735       return LHS.getOperand(0);
24736     }
24737   }
24738
24739   return SDValue();
24740 }
24741
24742 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24743                                          SelectionDAG &DAG) {
24744   SDLoc dl(Load);
24745   MVT VT = Load->getSimpleValueType(0);
24746   MVT EVT = VT.getVectorElementType();
24747   SDValue Addr = Load->getOperand(1);
24748   SDValue NewAddr = DAG.getNode(
24749       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24750       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24751                       Addr.getSimpleValueType()));
24752
24753   SDValue NewLoad =
24754       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24755                   DAG.getMachineFunction().getMachineMemOperand(
24756                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24757   return NewLoad;
24758 }
24759
24760 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24761                                       const X86Subtarget *Subtarget) {
24762   SDLoc dl(N);
24763   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24764   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24765          "X86insertps is only defined for v4x32");
24766
24767   SDValue Ld = N->getOperand(1);
24768   if (MayFoldLoad(Ld)) {
24769     // Extract the countS bits from the immediate so we can get the proper
24770     // address when narrowing the vector load to a specific element.
24771     // When the second source op is a memory address, insertps doesn't use
24772     // countS and just gets an f32 from that address.
24773     unsigned DestIndex =
24774         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24775
24776     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24777
24778     // Create this as a scalar to vector to match the instruction pattern.
24779     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24780     // countS bits are ignored when loading from memory on insertps, which
24781     // means we don't need to explicitly set them to 0.
24782     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24783                        LoadScalarToVector, N->getOperand(2));
24784   }
24785   return SDValue();
24786 }
24787
24788 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24789   SDValue V0 = N->getOperand(0);
24790   SDValue V1 = N->getOperand(1);
24791   SDLoc DL(N);
24792   EVT VT = N->getValueType(0);
24793
24794   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24795   // operands and changing the mask to 1. This saves us a bunch of
24796   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24797   // x86InstrInfo knows how to commute this back after instruction selection
24798   // if it would help register allocation.
24799
24800   // TODO: If optimizing for size or a processor that doesn't suffer from
24801   // partial register update stalls, this should be transformed into a MOVSD
24802   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24803
24804   if (VT == MVT::v2f64)
24805     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24806       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24807         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24808         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24809       }
24810
24811   return SDValue();
24812 }
24813
24814 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24815 // as "sbb reg,reg", since it can be extended without zext and produces
24816 // an all-ones bit which is more useful than 0/1 in some cases.
24817 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24818                                MVT VT) {
24819   if (VT == MVT::i8)
24820     return DAG.getNode(ISD::AND, DL, VT,
24821                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24822                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24823                                    EFLAGS),
24824                        DAG.getConstant(1, DL, VT));
24825   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24826   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24827                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24828                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24829                                  EFLAGS));
24830 }
24831
24832 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24833 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24834                                    TargetLowering::DAGCombinerInfo &DCI,
24835                                    const X86Subtarget *Subtarget) {
24836   SDLoc DL(N);
24837   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24838   SDValue EFLAGS = N->getOperand(1);
24839
24840   if (CC == X86::COND_A) {
24841     // Try to convert COND_A into COND_B in an attempt to facilitate
24842     // materializing "setb reg".
24843     //
24844     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24845     // cannot take an immediate as its first operand.
24846     //
24847     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24848         EFLAGS.getValueType().isInteger() &&
24849         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24850       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24851                                    EFLAGS.getNode()->getVTList(),
24852                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24853       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24854       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24855     }
24856   }
24857
24858   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24859   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24860   // cases.
24861   if (CC == X86::COND_B)
24862     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24863
24864   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24865     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24866     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24867   }
24868
24869   return SDValue();
24870 }
24871
24872 // Optimize branch condition evaluation.
24873 //
24874 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24875                                     TargetLowering::DAGCombinerInfo &DCI,
24876                                     const X86Subtarget *Subtarget) {
24877   SDLoc DL(N);
24878   SDValue Chain = N->getOperand(0);
24879   SDValue Dest = N->getOperand(1);
24880   SDValue EFLAGS = N->getOperand(3);
24881   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24882
24883   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24884     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24885     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24886                        Flags);
24887   }
24888
24889   return SDValue();
24890 }
24891
24892 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24893                                                          SelectionDAG &DAG) {
24894   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24895   // optimize away operation when it's from a constant.
24896   //
24897   // The general transformation is:
24898   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24899   //       AND(VECTOR_CMP(x,y), constant2)
24900   //    constant2 = UNARYOP(constant)
24901
24902   // Early exit if this isn't a vector operation, the operand of the
24903   // unary operation isn't a bitwise AND, or if the sizes of the operations
24904   // aren't the same.
24905   EVT VT = N->getValueType(0);
24906   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24907       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24908       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24909     return SDValue();
24910
24911   // Now check that the other operand of the AND is a constant. We could
24912   // make the transformation for non-constant splats as well, but it's unclear
24913   // that would be a benefit as it would not eliminate any operations, just
24914   // perform one more step in scalar code before moving to the vector unit.
24915   if (BuildVectorSDNode *BV =
24916           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24917     // Bail out if the vector isn't a constant.
24918     if (!BV->isConstant())
24919       return SDValue();
24920
24921     // Everything checks out. Build up the new and improved node.
24922     SDLoc DL(N);
24923     EVT IntVT = BV->getValueType(0);
24924     // Create a new constant of the appropriate type for the transformed
24925     // DAG.
24926     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24927     // The AND node needs bitcasts to/from an integer vector type around it.
24928     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
24929     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24930                                  N->getOperand(0)->getOperand(0), MaskConst);
24931     SDValue Res = DAG.getBitcast(VT, NewAnd);
24932     return Res;
24933   }
24934
24935   return SDValue();
24936 }
24937
24938 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24939                                         const X86Subtarget *Subtarget) {
24940   SDValue Op0 = N->getOperand(0);
24941   EVT VT = N->getValueType(0);
24942   EVT InVT = Op0.getValueType();
24943   EVT InSVT = InVT.getScalarType();
24944   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24945
24946   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
24947   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
24948   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24949     SDLoc dl(N);
24950     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24951                                  InVT.getVectorNumElements());
24952     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
24953
24954     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
24955       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
24956
24957     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24958   }
24959
24960   return SDValue();
24961 }
24962
24963 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24964                                         const X86Subtarget *Subtarget) {
24965   // First try to optimize away the conversion entirely when it's
24966   // conditionally from a constant. Vectors only.
24967   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
24968     return Res;
24969
24970   // Now move on to more general possibilities.
24971   SDValue Op0 = N->getOperand(0);
24972   EVT VT = N->getValueType(0);
24973   EVT InVT = Op0.getValueType();
24974   EVT InSVT = InVT.getScalarType();
24975
24976   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
24977   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
24978   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24979     SDLoc dl(N);
24980     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24981                                  InVT.getVectorNumElements());
24982     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24983     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24984   }
24985
24986   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24987   // a 32-bit target where SSE doesn't support i64->FP operations.
24988   if (Op0.getOpcode() == ISD::LOAD) {
24989     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24990     EVT LdVT = Ld->getValueType(0);
24991
24992     // This transformation is not supported if the result type is f16
24993     if (VT == MVT::f16)
24994       return SDValue();
24995
24996     if (!Ld->isVolatile() && !VT.isVector() &&
24997         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24998         !Subtarget->is64Bit() && LdVT == MVT::i64) {
24999       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25000           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25001       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25002       return FILDChain;
25003     }
25004   }
25005   return SDValue();
25006 }
25007
25008 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25009 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25010                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25011   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25012   // the result is either zero or one (depending on the input carry bit).
25013   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25014   if (X86::isZeroNode(N->getOperand(0)) &&
25015       X86::isZeroNode(N->getOperand(1)) &&
25016       // We don't have a good way to replace an EFLAGS use, so only do this when
25017       // dead right now.
25018       SDValue(N, 1).use_empty()) {
25019     SDLoc DL(N);
25020     EVT VT = N->getValueType(0);
25021     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25022     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25023                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25024                                            DAG.getConstant(X86::COND_B, DL,
25025                                                            MVT::i8),
25026                                            N->getOperand(2)),
25027                                DAG.getConstant(1, DL, VT));
25028     return DCI.CombineTo(N, Res1, CarryOut);
25029   }
25030
25031   return SDValue();
25032 }
25033
25034 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25035 //      (add Y, (setne X, 0)) -> sbb -1, Y
25036 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25037 //      (sub (setne X, 0), Y) -> adc -1, Y
25038 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25039   SDLoc DL(N);
25040
25041   // Look through ZExts.
25042   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25043   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25044     return SDValue();
25045
25046   SDValue SetCC = Ext.getOperand(0);
25047   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25048     return SDValue();
25049
25050   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25051   if (CC != X86::COND_E && CC != X86::COND_NE)
25052     return SDValue();
25053
25054   SDValue Cmp = SetCC.getOperand(1);
25055   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25056       !X86::isZeroNode(Cmp.getOperand(1)) ||
25057       !Cmp.getOperand(0).getValueType().isInteger())
25058     return SDValue();
25059
25060   SDValue CmpOp0 = Cmp.getOperand(0);
25061   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25062                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25063
25064   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25065   if (CC == X86::COND_NE)
25066     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25067                        DL, OtherVal.getValueType(), OtherVal,
25068                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25069                        NewCmp);
25070   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25071                      DL, OtherVal.getValueType(), OtherVal,
25072                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25073 }
25074
25075 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25076 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25077                                  const X86Subtarget *Subtarget) {
25078   EVT VT = N->getValueType(0);
25079   SDValue Op0 = N->getOperand(0);
25080   SDValue Op1 = N->getOperand(1);
25081
25082   // Try to synthesize horizontal adds from adds of shuffles.
25083   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25084        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25085       isHorizontalBinOp(Op0, Op1, true))
25086     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25087
25088   return OptimizeConditionalInDecrement(N, DAG);
25089 }
25090
25091 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25092                                  const X86Subtarget *Subtarget) {
25093   SDValue Op0 = N->getOperand(0);
25094   SDValue Op1 = N->getOperand(1);
25095
25096   // X86 can't encode an immediate LHS of a sub. See if we can push the
25097   // negation into a preceding instruction.
25098   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25099     // If the RHS of the sub is a XOR with one use and a constant, invert the
25100     // immediate. Then add one to the LHS of the sub so we can turn
25101     // X-Y -> X+~Y+1, saving one register.
25102     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25103         isa<ConstantSDNode>(Op1.getOperand(1))) {
25104       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25105       EVT VT = Op0.getValueType();
25106       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25107                                    Op1.getOperand(0),
25108                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25109       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25110                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25111     }
25112   }
25113
25114   // Try to synthesize horizontal adds from adds of shuffles.
25115   EVT VT = N->getValueType(0);
25116   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25117        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25118       isHorizontalBinOp(Op0, Op1, true))
25119     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25120
25121   return OptimizeConditionalInDecrement(N, DAG);
25122 }
25123
25124 /// performVZEXTCombine - Performs build vector combines
25125 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25126                                    TargetLowering::DAGCombinerInfo &DCI,
25127                                    const X86Subtarget *Subtarget) {
25128   SDLoc DL(N);
25129   MVT VT = N->getSimpleValueType(0);
25130   SDValue Op = N->getOperand(0);
25131   MVT OpVT = Op.getSimpleValueType();
25132   MVT OpEltVT = OpVT.getVectorElementType();
25133   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25134
25135   // (vzext (bitcast (vzext (x)) -> (vzext x)
25136   SDValue V = Op;
25137   while (V.getOpcode() == ISD::BITCAST)
25138     V = V.getOperand(0);
25139
25140   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25141     MVT InnerVT = V.getSimpleValueType();
25142     MVT InnerEltVT = InnerVT.getVectorElementType();
25143
25144     // If the element sizes match exactly, we can just do one larger vzext. This
25145     // is always an exact type match as vzext operates on integer types.
25146     if (OpEltVT == InnerEltVT) {
25147       assert(OpVT == InnerVT && "Types must match for vzext!");
25148       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25149     }
25150
25151     // The only other way we can combine them is if only a single element of the
25152     // inner vzext is used in the input to the outer vzext.
25153     if (InnerEltVT.getSizeInBits() < InputBits)
25154       return SDValue();
25155
25156     // In this case, the inner vzext is completely dead because we're going to
25157     // only look at bits inside of the low element. Just do the outer vzext on
25158     // a bitcast of the input to the inner.
25159     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25160   }
25161
25162   // Check if we can bypass extracting and re-inserting an element of an input
25163   // vector. Essentialy:
25164   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25165   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25166       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25167       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25168     SDValue ExtractedV = V.getOperand(0);
25169     SDValue OrigV = ExtractedV.getOperand(0);
25170     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25171       if (ExtractIdx->getZExtValue() == 0) {
25172         MVT OrigVT = OrigV.getSimpleValueType();
25173         // Extract a subvector if necessary...
25174         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25175           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25176           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25177                                     OrigVT.getVectorNumElements() / Ratio);
25178           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25179                               DAG.getIntPtrConstant(0, DL));
25180         }
25181         Op = DAG.getBitcast(OpVT, OrigV);
25182         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25183       }
25184   }
25185
25186   return SDValue();
25187 }
25188
25189 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25190                                              DAGCombinerInfo &DCI) const {
25191   SelectionDAG &DAG = DCI.DAG;
25192   switch (N->getOpcode()) {
25193   default: break;
25194   case ISD::EXTRACT_VECTOR_ELT:
25195     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25196   case ISD::VSELECT:
25197   case ISD::SELECT:
25198   case X86ISD::SHRUNKBLEND:
25199     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25200   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25201   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25202   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25203   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25204   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25205   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25206   case ISD::SHL:
25207   case ISD::SRA:
25208   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25209   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25210   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25211   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25212   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25213   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25214   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25215   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25216   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25217   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25218   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25219   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25220   case X86ISD::FXOR:
25221   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25222   case X86ISD::FMIN:
25223   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25224   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25225   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25226   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25227   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25228   case ISD::ANY_EXTEND:
25229   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25230   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25231   case ISD::SIGN_EXTEND_INREG:
25232     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25233   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25234   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25235   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25236   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25237   case X86ISD::SHUFP:       // Handle all target specific shuffles
25238   case X86ISD::PALIGNR:
25239   case X86ISD::UNPCKH:
25240   case X86ISD::UNPCKL:
25241   case X86ISD::MOVHLPS:
25242   case X86ISD::MOVLHPS:
25243   case X86ISD::PSHUFB:
25244   case X86ISD::PSHUFD:
25245   case X86ISD::PSHUFHW:
25246   case X86ISD::PSHUFLW:
25247   case X86ISD::MOVSS:
25248   case X86ISD::MOVSD:
25249   case X86ISD::VPERMILPI:
25250   case X86ISD::VPERM2X128:
25251   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25252   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25253   case ISD::INTRINSIC_WO_CHAIN:
25254     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25255   case X86ISD::INSERTPS: {
25256     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25257       return PerformINSERTPSCombine(N, DAG, Subtarget);
25258     break;
25259   }
25260   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25261   }
25262
25263   return SDValue();
25264 }
25265
25266 /// isTypeDesirableForOp - Return true if the target has native support for
25267 /// the specified value type and it is 'desirable' to use the type for the
25268 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25269 /// instruction encodings are longer and some i16 instructions are slow.
25270 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25271   if (!isTypeLegal(VT))
25272     return false;
25273   if (VT != MVT::i16)
25274     return true;
25275
25276   switch (Opc) {
25277   default:
25278     return true;
25279   case ISD::LOAD:
25280   case ISD::SIGN_EXTEND:
25281   case ISD::ZERO_EXTEND:
25282   case ISD::ANY_EXTEND:
25283   case ISD::SHL:
25284   case ISD::SRL:
25285   case ISD::SUB:
25286   case ISD::ADD:
25287   case ISD::MUL:
25288   case ISD::AND:
25289   case ISD::OR:
25290   case ISD::XOR:
25291     return false;
25292   }
25293 }
25294
25295 /// IsDesirableToPromoteOp - This method query the target whether it is
25296 /// beneficial for dag combiner to promote the specified node. If true, it
25297 /// should return the desired promotion type by reference.
25298 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25299   EVT VT = Op.getValueType();
25300   if (VT != MVT::i16)
25301     return false;
25302
25303   bool Promote = false;
25304   bool Commute = false;
25305   switch (Op.getOpcode()) {
25306   default: break;
25307   case ISD::LOAD: {
25308     LoadSDNode *LD = cast<LoadSDNode>(Op);
25309     // If the non-extending load has a single use and it's not live out, then it
25310     // might be folded.
25311     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25312                                                      Op.hasOneUse()*/) {
25313       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25314              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25315         // The only case where we'd want to promote LOAD (rather then it being
25316         // promoted as an operand is when it's only use is liveout.
25317         if (UI->getOpcode() != ISD::CopyToReg)
25318           return false;
25319       }
25320     }
25321     Promote = true;
25322     break;
25323   }
25324   case ISD::SIGN_EXTEND:
25325   case ISD::ZERO_EXTEND:
25326   case ISD::ANY_EXTEND:
25327     Promote = true;
25328     break;
25329   case ISD::SHL:
25330   case ISD::SRL: {
25331     SDValue N0 = Op.getOperand(0);
25332     // Look out for (store (shl (load), x)).
25333     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25334       return false;
25335     Promote = true;
25336     break;
25337   }
25338   case ISD::ADD:
25339   case ISD::MUL:
25340   case ISD::AND:
25341   case ISD::OR:
25342   case ISD::XOR:
25343     Commute = true;
25344     // fallthrough
25345   case ISD::SUB: {
25346     SDValue N0 = Op.getOperand(0);
25347     SDValue N1 = Op.getOperand(1);
25348     if (!Commute && MayFoldLoad(N1))
25349       return false;
25350     // Avoid disabling potential load folding opportunities.
25351     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25352       return false;
25353     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25354       return false;
25355     Promote = true;
25356   }
25357   }
25358
25359   PVT = MVT::i32;
25360   return Promote;
25361 }
25362
25363 //===----------------------------------------------------------------------===//
25364 //                           X86 Inline Assembly Support
25365 //===----------------------------------------------------------------------===//
25366
25367 // Helper to match a string separated by whitespace.
25368 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25369   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25370
25371   for (StringRef Piece : Pieces) {
25372     if (!S.startswith(Piece)) // Check if the piece matches.
25373       return false;
25374
25375     S = S.substr(Piece.size());
25376     StringRef::size_type Pos = S.find_first_not_of(" \t");
25377     if (Pos == 0) // We matched a prefix.
25378       return false;
25379
25380     S = S.substr(Pos);
25381   }
25382
25383   return S.empty();
25384 }
25385
25386 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25387
25388   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25389     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25390         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25391         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25392
25393       if (AsmPieces.size() == 3)
25394         return true;
25395       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25396         return true;
25397     }
25398   }
25399   return false;
25400 }
25401
25402 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25403   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25404
25405   std::string AsmStr = IA->getAsmString();
25406
25407   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25408   if (!Ty || Ty->getBitWidth() % 16 != 0)
25409     return false;
25410
25411   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25412   SmallVector<StringRef, 4> AsmPieces;
25413   SplitString(AsmStr, AsmPieces, ";\n");
25414
25415   switch (AsmPieces.size()) {
25416   default: return false;
25417   case 1:
25418     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25419     // we will turn this bswap into something that will be lowered to logical
25420     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25421     // lower so don't worry about this.
25422     // bswap $0
25423     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25424         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25425         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25426         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25427         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25428         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25429       // No need to check constraints, nothing other than the equivalent of
25430       // "=r,0" would be valid here.
25431       return IntrinsicLowering::LowerToByteSwap(CI);
25432     }
25433
25434     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25435     if (CI->getType()->isIntegerTy(16) &&
25436         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25437         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25438          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25439       AsmPieces.clear();
25440       StringRef ConstraintsStr = IA->getConstraintString();
25441       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25442       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25443       if (clobbersFlagRegisters(AsmPieces))
25444         return IntrinsicLowering::LowerToByteSwap(CI);
25445     }
25446     break;
25447   case 3:
25448     if (CI->getType()->isIntegerTy(32) &&
25449         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25450         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25451         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25452         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25453       AsmPieces.clear();
25454       StringRef ConstraintsStr = IA->getConstraintString();
25455       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25456       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25457       if (clobbersFlagRegisters(AsmPieces))
25458         return IntrinsicLowering::LowerToByteSwap(CI);
25459     }
25460
25461     if (CI->getType()->isIntegerTy(64)) {
25462       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25463       if (Constraints.size() >= 2 &&
25464           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25465           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25466         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25467         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25468             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25469             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25470           return IntrinsicLowering::LowerToByteSwap(CI);
25471       }
25472     }
25473     break;
25474   }
25475   return false;
25476 }
25477
25478 /// getConstraintType - Given a constraint letter, return the type of
25479 /// constraint it is for this target.
25480 X86TargetLowering::ConstraintType
25481 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25482   if (Constraint.size() == 1) {
25483     switch (Constraint[0]) {
25484     case 'R':
25485     case 'q':
25486     case 'Q':
25487     case 'f':
25488     case 't':
25489     case 'u':
25490     case 'y':
25491     case 'x':
25492     case 'Y':
25493     case 'l':
25494       return C_RegisterClass;
25495     case 'a':
25496     case 'b':
25497     case 'c':
25498     case 'd':
25499     case 'S':
25500     case 'D':
25501     case 'A':
25502       return C_Register;
25503     case 'I':
25504     case 'J':
25505     case 'K':
25506     case 'L':
25507     case 'M':
25508     case 'N':
25509     case 'G':
25510     case 'C':
25511     case 'e':
25512     case 'Z':
25513       return C_Other;
25514     default:
25515       break;
25516     }
25517   }
25518   return TargetLowering::getConstraintType(Constraint);
25519 }
25520
25521 /// Examine constraint type and operand type and determine a weight value.
25522 /// This object must already have been set up with the operand type
25523 /// and the current alternative constraint selected.
25524 TargetLowering::ConstraintWeight
25525   X86TargetLowering::getSingleConstraintMatchWeight(
25526     AsmOperandInfo &info, const char *constraint) const {
25527   ConstraintWeight weight = CW_Invalid;
25528   Value *CallOperandVal = info.CallOperandVal;
25529     // If we don't have a value, we can't do a match,
25530     // but allow it at the lowest weight.
25531   if (!CallOperandVal)
25532     return CW_Default;
25533   Type *type = CallOperandVal->getType();
25534   // Look at the constraint type.
25535   switch (*constraint) {
25536   default:
25537     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25538   case 'R':
25539   case 'q':
25540   case 'Q':
25541   case 'a':
25542   case 'b':
25543   case 'c':
25544   case 'd':
25545   case 'S':
25546   case 'D':
25547   case 'A':
25548     if (CallOperandVal->getType()->isIntegerTy())
25549       weight = CW_SpecificReg;
25550     break;
25551   case 'f':
25552   case 't':
25553   case 'u':
25554     if (type->isFloatingPointTy())
25555       weight = CW_SpecificReg;
25556     break;
25557   case 'y':
25558     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25559       weight = CW_SpecificReg;
25560     break;
25561   case 'x':
25562   case 'Y':
25563     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25564         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25565       weight = CW_Register;
25566     break;
25567   case 'I':
25568     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25569       if (C->getZExtValue() <= 31)
25570         weight = CW_Constant;
25571     }
25572     break;
25573   case 'J':
25574     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25575       if (C->getZExtValue() <= 63)
25576         weight = CW_Constant;
25577     }
25578     break;
25579   case 'K':
25580     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25581       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25582         weight = CW_Constant;
25583     }
25584     break;
25585   case 'L':
25586     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25587       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25588         weight = CW_Constant;
25589     }
25590     break;
25591   case 'M':
25592     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25593       if (C->getZExtValue() <= 3)
25594         weight = CW_Constant;
25595     }
25596     break;
25597   case 'N':
25598     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25599       if (C->getZExtValue() <= 0xff)
25600         weight = CW_Constant;
25601     }
25602     break;
25603   case 'G':
25604   case 'C':
25605     if (isa<ConstantFP>(CallOperandVal)) {
25606       weight = CW_Constant;
25607     }
25608     break;
25609   case 'e':
25610     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25611       if ((C->getSExtValue() >= -0x80000000LL) &&
25612           (C->getSExtValue() <= 0x7fffffffLL))
25613         weight = CW_Constant;
25614     }
25615     break;
25616   case 'Z':
25617     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25618       if (C->getZExtValue() <= 0xffffffff)
25619         weight = CW_Constant;
25620     }
25621     break;
25622   }
25623   return weight;
25624 }
25625
25626 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25627 /// with another that has more specific requirements based on the type of the
25628 /// corresponding operand.
25629 const char *X86TargetLowering::
25630 LowerXConstraint(EVT ConstraintVT) const {
25631   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25632   // 'f' like normal targets.
25633   if (ConstraintVT.isFloatingPoint()) {
25634     if (Subtarget->hasSSE2())
25635       return "Y";
25636     if (Subtarget->hasSSE1())
25637       return "x";
25638   }
25639
25640   return TargetLowering::LowerXConstraint(ConstraintVT);
25641 }
25642
25643 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25644 /// vector.  If it is invalid, don't add anything to Ops.
25645 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25646                                                      std::string &Constraint,
25647                                                      std::vector<SDValue>&Ops,
25648                                                      SelectionDAG &DAG) const {
25649   SDValue Result;
25650
25651   // Only support length 1 constraints for now.
25652   if (Constraint.length() > 1) return;
25653
25654   char ConstraintLetter = Constraint[0];
25655   switch (ConstraintLetter) {
25656   default: break;
25657   case 'I':
25658     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25659       if (C->getZExtValue() <= 31) {
25660         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25661                                        Op.getValueType());
25662         break;
25663       }
25664     }
25665     return;
25666   case 'J':
25667     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25668       if (C->getZExtValue() <= 63) {
25669         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25670                                        Op.getValueType());
25671         break;
25672       }
25673     }
25674     return;
25675   case 'K':
25676     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25677       if (isInt<8>(C->getSExtValue())) {
25678         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25679                                        Op.getValueType());
25680         break;
25681       }
25682     }
25683     return;
25684   case 'L':
25685     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25686       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25687           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25688         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25689                                        Op.getValueType());
25690         break;
25691       }
25692     }
25693     return;
25694   case 'M':
25695     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25696       if (C->getZExtValue() <= 3) {
25697         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25698                                        Op.getValueType());
25699         break;
25700       }
25701     }
25702     return;
25703   case 'N':
25704     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25705       if (C->getZExtValue() <= 255) {
25706         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25707                                        Op.getValueType());
25708         break;
25709       }
25710     }
25711     return;
25712   case 'O':
25713     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25714       if (C->getZExtValue() <= 127) {
25715         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25716                                        Op.getValueType());
25717         break;
25718       }
25719     }
25720     return;
25721   case 'e': {
25722     // 32-bit signed value
25723     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25724       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25725                                            C->getSExtValue())) {
25726         // Widen to 64 bits here to get it sign extended.
25727         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25728         break;
25729       }
25730     // FIXME gcc accepts some relocatable values here too, but only in certain
25731     // memory models; it's complicated.
25732     }
25733     return;
25734   }
25735   case 'Z': {
25736     // 32-bit unsigned value
25737     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25738       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25739                                            C->getZExtValue())) {
25740         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25741                                        Op.getValueType());
25742         break;
25743       }
25744     }
25745     // FIXME gcc accepts some relocatable values here too, but only in certain
25746     // memory models; it's complicated.
25747     return;
25748   }
25749   case 'i': {
25750     // Literal immediates are always ok.
25751     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25752       // Widen to 64 bits here to get it sign extended.
25753       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25754       break;
25755     }
25756
25757     // In any sort of PIC mode addresses need to be computed at runtime by
25758     // adding in a register or some sort of table lookup.  These can't
25759     // be used as immediates.
25760     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25761       return;
25762
25763     // If we are in non-pic codegen mode, we allow the address of a global (with
25764     // an optional displacement) to be used with 'i'.
25765     GlobalAddressSDNode *GA = nullptr;
25766     int64_t Offset = 0;
25767
25768     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25769     while (1) {
25770       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25771         Offset += GA->getOffset();
25772         break;
25773       } else if (Op.getOpcode() == ISD::ADD) {
25774         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25775           Offset += C->getZExtValue();
25776           Op = Op.getOperand(0);
25777           continue;
25778         }
25779       } else if (Op.getOpcode() == ISD::SUB) {
25780         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25781           Offset += -C->getZExtValue();
25782           Op = Op.getOperand(0);
25783           continue;
25784         }
25785       }
25786
25787       // Otherwise, this isn't something we can handle, reject it.
25788       return;
25789     }
25790
25791     const GlobalValue *GV = GA->getGlobal();
25792     // If we require an extra load to get this address, as in PIC mode, we
25793     // can't accept it.
25794     if (isGlobalStubReference(
25795             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25796       return;
25797
25798     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25799                                         GA->getValueType(0), Offset);
25800     break;
25801   }
25802   }
25803
25804   if (Result.getNode()) {
25805     Ops.push_back(Result);
25806     return;
25807   }
25808   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25809 }
25810
25811 std::pair<unsigned, const TargetRegisterClass *>
25812 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25813                                                 StringRef Constraint,
25814                                                 MVT VT) const {
25815   // First, see if this is a constraint that directly corresponds to an LLVM
25816   // register class.
25817   if (Constraint.size() == 1) {
25818     // GCC Constraint Letters
25819     switch (Constraint[0]) {
25820     default: break;
25821       // TODO: Slight differences here in allocation order and leaving
25822       // RIP in the class. Do they matter any more here than they do
25823       // in the normal allocation?
25824     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25825       if (Subtarget->is64Bit()) {
25826         if (VT == MVT::i32 || VT == MVT::f32)
25827           return std::make_pair(0U, &X86::GR32RegClass);
25828         if (VT == MVT::i16)
25829           return std::make_pair(0U, &X86::GR16RegClass);
25830         if (VT == MVT::i8 || VT == MVT::i1)
25831           return std::make_pair(0U, &X86::GR8RegClass);
25832         if (VT == MVT::i64 || VT == MVT::f64)
25833           return std::make_pair(0U, &X86::GR64RegClass);
25834         break;
25835       }
25836       // 32-bit fallthrough
25837     case 'Q':   // Q_REGS
25838       if (VT == MVT::i32 || VT == MVT::f32)
25839         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25840       if (VT == MVT::i16)
25841         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25842       if (VT == MVT::i8 || VT == MVT::i1)
25843         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25844       if (VT == MVT::i64)
25845         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25846       break;
25847     case 'r':   // GENERAL_REGS
25848     case 'l':   // INDEX_REGS
25849       if (VT == MVT::i8 || VT == MVT::i1)
25850         return std::make_pair(0U, &X86::GR8RegClass);
25851       if (VT == MVT::i16)
25852         return std::make_pair(0U, &X86::GR16RegClass);
25853       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25854         return std::make_pair(0U, &X86::GR32RegClass);
25855       return std::make_pair(0U, &X86::GR64RegClass);
25856     case 'R':   // LEGACY_REGS
25857       if (VT == MVT::i8 || VT == MVT::i1)
25858         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25859       if (VT == MVT::i16)
25860         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25861       if (VT == MVT::i32 || !Subtarget->is64Bit())
25862         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25863       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25864     case 'f':  // FP Stack registers.
25865       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25866       // value to the correct fpstack register class.
25867       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25868         return std::make_pair(0U, &X86::RFP32RegClass);
25869       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25870         return std::make_pair(0U, &X86::RFP64RegClass);
25871       return std::make_pair(0U, &X86::RFP80RegClass);
25872     case 'y':   // MMX_REGS if MMX allowed.
25873       if (!Subtarget->hasMMX()) break;
25874       return std::make_pair(0U, &X86::VR64RegClass);
25875     case 'Y':   // SSE_REGS if SSE2 allowed
25876       if (!Subtarget->hasSSE2()) break;
25877       // FALL THROUGH.
25878     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25879       if (!Subtarget->hasSSE1()) break;
25880
25881       switch (VT.SimpleTy) {
25882       default: break;
25883       // Scalar SSE types.
25884       case MVT::f32:
25885       case MVT::i32:
25886         return std::make_pair(0U, &X86::FR32RegClass);
25887       case MVT::f64:
25888       case MVT::i64:
25889         return std::make_pair(0U, &X86::FR64RegClass);
25890       // Vector types.
25891       case MVT::v16i8:
25892       case MVT::v8i16:
25893       case MVT::v4i32:
25894       case MVT::v2i64:
25895       case MVT::v4f32:
25896       case MVT::v2f64:
25897         return std::make_pair(0U, &X86::VR128RegClass);
25898       // AVX types.
25899       case MVT::v32i8:
25900       case MVT::v16i16:
25901       case MVT::v8i32:
25902       case MVT::v4i64:
25903       case MVT::v8f32:
25904       case MVT::v4f64:
25905         return std::make_pair(0U, &X86::VR256RegClass);
25906       case MVT::v8f64:
25907       case MVT::v16f32:
25908       case MVT::v16i32:
25909       case MVT::v8i64:
25910         return std::make_pair(0U, &X86::VR512RegClass);
25911       }
25912       break;
25913     }
25914   }
25915
25916   // Use the default implementation in TargetLowering to convert the register
25917   // constraint into a member of a register class.
25918   std::pair<unsigned, const TargetRegisterClass*> Res;
25919   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25920
25921   // Not found as a standard register?
25922   if (!Res.second) {
25923     // Map st(0) -> st(7) -> ST0
25924     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25925         tolower(Constraint[1]) == 's' &&
25926         tolower(Constraint[2]) == 't' &&
25927         Constraint[3] == '(' &&
25928         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25929         Constraint[5] == ')' &&
25930         Constraint[6] == '}') {
25931
25932       Res.first = X86::FP0+Constraint[4]-'0';
25933       Res.second = &X86::RFP80RegClass;
25934       return Res;
25935     }
25936
25937     // GCC allows "st(0)" to be called just plain "st".
25938     if (StringRef("{st}").equals_lower(Constraint)) {
25939       Res.first = X86::FP0;
25940       Res.second = &X86::RFP80RegClass;
25941       return Res;
25942     }
25943
25944     // flags -> EFLAGS
25945     if (StringRef("{flags}").equals_lower(Constraint)) {
25946       Res.first = X86::EFLAGS;
25947       Res.second = &X86::CCRRegClass;
25948       return Res;
25949     }
25950
25951     // 'A' means EAX + EDX.
25952     if (Constraint == "A") {
25953       Res.first = X86::EAX;
25954       Res.second = &X86::GR32_ADRegClass;
25955       return Res;
25956     }
25957     return Res;
25958   }
25959
25960   // Otherwise, check to see if this is a register class of the wrong value
25961   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25962   // turn into {ax},{dx}.
25963   // MVT::Other is used to specify clobber names.
25964   if (Res.second->hasType(VT) || VT == MVT::Other)
25965     return Res;   // Correct type already, nothing to do.
25966
25967   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
25968   // return "eax". This should even work for things like getting 64bit integer
25969   // registers when given an f64 type.
25970   const TargetRegisterClass *Class = Res.second;
25971   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
25972       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
25973     unsigned Size = VT.getSizeInBits();
25974     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
25975                                   : Size == 16 ? MVT::i16
25976                                   : Size == 32 ? MVT::i32
25977                                   : Size == 64 ? MVT::i64
25978                                   : MVT::Other;
25979     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
25980     if (DestReg > 0) {
25981       Res.first = DestReg;
25982       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
25983                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
25984                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
25985                  : &X86::GR64RegClass;
25986       assert(Res.second->contains(Res.first) && "Register in register class");
25987     } else {
25988       // No register found/type mismatch.
25989       Res.first = 0;
25990       Res.second = nullptr;
25991     }
25992   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
25993              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
25994              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
25995              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
25996              Class == &X86::VR512RegClass) {
25997     // Handle references to XMM physical registers that got mapped into the
25998     // wrong class.  This can happen with constraints like {xmm0} where the
25999     // target independent register mapper will just pick the first match it can
26000     // find, ignoring the required type.
26001
26002     if (VT == MVT::f32 || VT == MVT::i32)
26003       Res.second = &X86::FR32RegClass;
26004     else if (VT == MVT::f64 || VT == MVT::i64)
26005       Res.second = &X86::FR64RegClass;
26006     else if (X86::VR128RegClass.hasType(VT))
26007       Res.second = &X86::VR128RegClass;
26008     else if (X86::VR256RegClass.hasType(VT))
26009       Res.second = &X86::VR256RegClass;
26010     else if (X86::VR512RegClass.hasType(VT))
26011       Res.second = &X86::VR512RegClass;
26012     else {
26013       // Type mismatch and not a clobber: Return an error;
26014       Res.first = 0;
26015       Res.second = nullptr;
26016     }
26017   }
26018
26019   return Res;
26020 }
26021
26022 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
26023                                             Type *Ty,
26024                                             unsigned AS) const {
26025   // Scaling factors are not free at all.
26026   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26027   // will take 2 allocations in the out of order engine instead of 1
26028   // for plain addressing mode, i.e. inst (reg1).
26029   // E.g.,
26030   // vaddps (%rsi,%drx), %ymm0, %ymm1
26031   // Requires two allocations (one for the load, one for the computation)
26032   // whereas:
26033   // vaddps (%rsi), %ymm0, %ymm1
26034   // Requires just 1 allocation, i.e., freeing allocations for other operations
26035   // and having less micro operations to execute.
26036   //
26037   // For some X86 architectures, this is even worse because for instance for
26038   // stores, the complex addressing mode forces the instruction to use the
26039   // "load" ports instead of the dedicated "store" port.
26040   // E.g., on Haswell:
26041   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26042   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26043   if (isLegalAddressingMode(AM, Ty, AS))
26044     // Scale represents reg2 * scale, thus account for 1
26045     // as soon as we use a second register.
26046     return AM.Scale != 0;
26047   return -1;
26048 }
26049
26050 bool X86TargetLowering::isTargetFTOL() const {
26051   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26052 }