AVX-512: Floating point conversions for SKX - DAG Lowering.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = TM.getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,         MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,         MVT::v4i1, Custom);
1357
1358       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i64, Legal);
1359       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i64, Legal);
1360       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i64, Legal);
1361       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i64, Legal);
1362       if (Subtarget->hasVLX()) {
1363         setOperationAction(ISD::SINT_TO_FP,    MVT::v4i64, Legal);
1364         setOperationAction(ISD::SINT_TO_FP,    MVT::v2i64, Legal);
1365         setOperationAction(ISD::UINT_TO_FP,    MVT::v4i64, Legal);
1366         setOperationAction(ISD::UINT_TO_FP,    MVT::v2i64, Legal);
1367         setOperationAction(ISD::FP_TO_SINT,    MVT::v4i64, Legal);
1368         setOperationAction(ISD::FP_TO_SINT,    MVT::v2i64, Legal);
1369         setOperationAction(ISD::FP_TO_UINT,    MVT::v4i64, Legal);
1370         setOperationAction(ISD::FP_TO_UINT,    MVT::v2i64, Legal);
1371       }
1372     }
1373     if (Subtarget->hasVLX()) {
1374       setOperationAction(ISD::SINT_TO_FP,       MVT::v8i32, Legal);
1375       setOperationAction(ISD::UINT_TO_FP,       MVT::v8i32, Legal);
1376       setOperationAction(ISD::FP_TO_SINT,       MVT::v8i32, Legal);
1377       setOperationAction(ISD::FP_TO_UINT,       MVT::v8i32, Legal);
1378       setOperationAction(ISD::SINT_TO_FP,       MVT::v4i32, Legal);
1379       setOperationAction(ISD::UINT_TO_FP,       MVT::v4i32, Legal);
1380       setOperationAction(ISD::FP_TO_SINT,       MVT::v4i32, Legal);
1381       setOperationAction(ISD::FP_TO_UINT,       MVT::v4i32, Legal);
1382     }
1383     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1384     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1385     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1386     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1387     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1388     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1389     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1390     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1391     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1392     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1393     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1394     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1395     if (Subtarget->hasDQI()) {
1396       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1397       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1398     }
1399     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1400     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1401     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1402     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1403     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1404     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1405     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1406     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1407     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1408     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1409
1410     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1411     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1412     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1413     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1414     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1415
1416     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1417     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1418
1419     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1420
1421     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1422     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1423     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1424     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1425     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1426     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1427     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1428     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1429     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1430     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1431     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1432
1433     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1434     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1435     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1436     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1437     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1438     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1439     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1440     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1441
1442     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1443     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1444
1445     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1446     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1447
1448     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1449
1450     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1451     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1452
1453     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1454     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1455
1456     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1457     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1458
1459     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1460     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1461     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1462     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1463     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1464     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1465
1466     if (Subtarget->hasCDI()) {
1467       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1468       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1469     }
1470     if (Subtarget->hasDQI()) {
1471       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1472       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1473       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1474     }
1475     // Custom lower several nodes.
1476     for (MVT VT : MVT::vector_valuetypes()) {
1477       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1478       if (EltSize == 1) {
1479         setOperationAction(ISD::AND, VT, Legal);
1480         setOperationAction(ISD::OR,  VT, Legal);
1481         setOperationAction(ISD::XOR,  VT, Legal);
1482       }
1483       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1484         setOperationAction(ISD::MGATHER,  VT, Custom);
1485         setOperationAction(ISD::MSCATTER, VT, Custom);
1486       }
1487       // Extract subvector is special because the value type
1488       // (result) is 256/128-bit but the source is 512-bit wide.
1489       if (VT.is128BitVector() || VT.is256BitVector()) {
1490         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1491       }
1492       if (VT.getVectorElementType() == MVT::i1)
1493         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1494
1495       // Do not attempt to custom lower other non-512-bit vectors
1496       if (!VT.is512BitVector())
1497         continue;
1498
1499       if (EltSize >= 32) {
1500         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1501         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1502         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1503         setOperationAction(ISD::VSELECT,             VT, Legal);
1504         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1505         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1506         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1507         setOperationAction(ISD::MLOAD,               VT, Legal);
1508         setOperationAction(ISD::MSTORE,              VT, Legal);
1509       }
1510     }
1511     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1512       MVT VT = (MVT::SimpleValueType)i;
1513
1514       // Do not attempt to promote non-512-bit vectors.
1515       if (!VT.is512BitVector())
1516         continue;
1517
1518       setOperationAction(ISD::SELECT, VT, Promote);
1519       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1520     }
1521   }// has  AVX-512
1522
1523   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1524     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1525     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1526
1527     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1528     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1529
1530     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1531     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1532     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1533     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1534     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1535     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1536     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1537     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1538     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1539     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1540     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1541     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1542     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1543     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1544     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1545     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1546     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1547     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1548     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1549     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1550     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1551     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1552     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1553     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1554     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1555     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1556     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1557     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1558     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1559
1560     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1561     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1562     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1563     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1564     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1565     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1566     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1567     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1568
1569     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1570       const MVT VT = (MVT::SimpleValueType)i;
1571
1572       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1573
1574       // Do not attempt to promote non-512-bit vectors.
1575       if (!VT.is512BitVector())
1576         continue;
1577
1578       if (EltSize < 32) {
1579         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1580         setOperationAction(ISD::VSELECT,             VT, Legal);
1581       }
1582     }
1583   }
1584
1585   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1586     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1587     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1588
1589     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1590     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1591     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1592     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1593     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1594     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1595     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1596     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1597     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1598     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1599
1600     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1601     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1602     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1603     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1604     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1605     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1606     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1607     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1608
1609     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1610     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1611     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1612     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1613     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1614     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1615     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1616     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1617   }
1618
1619   // We want to custom lower some of our intrinsics.
1620   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1621   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1622   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1623   if (!Subtarget->is64Bit())
1624     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1625
1626   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1627   // handle type legalization for these operations here.
1628   //
1629   // FIXME: We really should do custom legalization for addition and
1630   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1631   // than generic legalization for 64-bit multiplication-with-overflow, though.
1632   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1633     // Add/Sub/Mul with overflow operations are custom lowered.
1634     MVT VT = IntVTs[i];
1635     setOperationAction(ISD::SADDO, VT, Custom);
1636     setOperationAction(ISD::UADDO, VT, Custom);
1637     setOperationAction(ISD::SSUBO, VT, Custom);
1638     setOperationAction(ISD::USUBO, VT, Custom);
1639     setOperationAction(ISD::SMULO, VT, Custom);
1640     setOperationAction(ISD::UMULO, VT, Custom);
1641   }
1642
1643
1644   if (!Subtarget->is64Bit()) {
1645     // These libcalls are not available in 32-bit.
1646     setLibcallName(RTLIB::SHL_I128, nullptr);
1647     setLibcallName(RTLIB::SRL_I128, nullptr);
1648     setLibcallName(RTLIB::SRA_I128, nullptr);
1649   }
1650
1651   // Combine sin / cos into one node or libcall if possible.
1652   if (Subtarget->hasSinCos()) {
1653     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1654     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1655     if (Subtarget->isTargetDarwin()) {
1656       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1657       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1658       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1659       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1660     }
1661   }
1662
1663   if (Subtarget->isTargetWin64()) {
1664     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1665     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1666     setOperationAction(ISD::SREM, MVT::i128, Custom);
1667     setOperationAction(ISD::UREM, MVT::i128, Custom);
1668     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1669     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1670   }
1671
1672   // We have target-specific dag combine patterns for the following nodes:
1673   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1674   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1675   setTargetDAGCombine(ISD::BITCAST);
1676   setTargetDAGCombine(ISD::VSELECT);
1677   setTargetDAGCombine(ISD::SELECT);
1678   setTargetDAGCombine(ISD::SHL);
1679   setTargetDAGCombine(ISD::SRA);
1680   setTargetDAGCombine(ISD::SRL);
1681   setTargetDAGCombine(ISD::OR);
1682   setTargetDAGCombine(ISD::AND);
1683   setTargetDAGCombine(ISD::ADD);
1684   setTargetDAGCombine(ISD::FADD);
1685   setTargetDAGCombine(ISD::FSUB);
1686   setTargetDAGCombine(ISD::FMA);
1687   setTargetDAGCombine(ISD::SUB);
1688   setTargetDAGCombine(ISD::LOAD);
1689   setTargetDAGCombine(ISD::MLOAD);
1690   setTargetDAGCombine(ISD::STORE);
1691   setTargetDAGCombine(ISD::MSTORE);
1692   setTargetDAGCombine(ISD::ZERO_EXTEND);
1693   setTargetDAGCombine(ISD::ANY_EXTEND);
1694   setTargetDAGCombine(ISD::SIGN_EXTEND);
1695   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1696   setTargetDAGCombine(ISD::SINT_TO_FP);
1697   setTargetDAGCombine(ISD::UINT_TO_FP);
1698   setTargetDAGCombine(ISD::SETCC);
1699   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1700   setTargetDAGCombine(ISD::BUILD_VECTOR);
1701   setTargetDAGCombine(ISD::MUL);
1702   setTargetDAGCombine(ISD::XOR);
1703
1704   computeRegisterProperties(Subtarget->getRegisterInfo());
1705
1706   // On Darwin, -Os means optimize for size without hurting performance,
1707   // do not reduce the limit.
1708   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1709   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1710   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1711   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1712   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1713   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1714   setPrefLoopAlignment(4); // 2^4 bytes.
1715
1716   // Predictable cmov don't hurt on atom because it's in-order.
1717   PredictableSelectIsExpensive = !Subtarget->isAtom();
1718   EnableExtLdPromotion = true;
1719   setPrefFunctionAlignment(4); // 2^4 bytes.
1720
1721   verifyIntrinsicTables();
1722 }
1723
1724 // This has so far only been implemented for 64-bit MachO.
1725 bool X86TargetLowering::useLoadStackGuardNode() const {
1726   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1727 }
1728
1729 TargetLoweringBase::LegalizeTypeAction
1730 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1731   if (ExperimentalVectorWideningLegalization &&
1732       VT.getVectorNumElements() != 1 &&
1733       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1734     return TypeWidenVector;
1735
1736   return TargetLoweringBase::getPreferredVectorAction(VT);
1737 }
1738
1739 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1740                                           EVT VT) const {
1741   if (!VT.isVector())
1742     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1743
1744   const unsigned NumElts = VT.getVectorNumElements();
1745   const EVT EltVT = VT.getVectorElementType();
1746   if (VT.is512BitVector()) {
1747     if (Subtarget->hasAVX512())
1748       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1749           EltVT == MVT::f32 || EltVT == MVT::f64)
1750         switch(NumElts) {
1751         case  8: return MVT::v8i1;
1752         case 16: return MVT::v16i1;
1753       }
1754     if (Subtarget->hasBWI())
1755       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1756         switch(NumElts) {
1757         case 32: return MVT::v32i1;
1758         case 64: return MVT::v64i1;
1759       }
1760   }
1761
1762   if (VT.is256BitVector() || VT.is128BitVector()) {
1763     if (Subtarget->hasVLX())
1764       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1765           EltVT == MVT::f32 || EltVT == MVT::f64)
1766         switch(NumElts) {
1767         case 2: return MVT::v2i1;
1768         case 4: return MVT::v4i1;
1769         case 8: return MVT::v8i1;
1770       }
1771     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1772       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1773         switch(NumElts) {
1774         case  8: return MVT::v8i1;
1775         case 16: return MVT::v16i1;
1776         case 32: return MVT::v32i1;
1777       }
1778   }
1779
1780   return VT.changeVectorElementTypeToInteger();
1781 }
1782
1783 /// Helper for getByValTypeAlignment to determine
1784 /// the desired ByVal argument alignment.
1785 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1786   if (MaxAlign == 16)
1787     return;
1788   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1789     if (VTy->getBitWidth() == 128)
1790       MaxAlign = 16;
1791   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1792     unsigned EltAlign = 0;
1793     getMaxByValAlign(ATy->getElementType(), EltAlign);
1794     if (EltAlign > MaxAlign)
1795       MaxAlign = EltAlign;
1796   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1797     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1798       unsigned EltAlign = 0;
1799       getMaxByValAlign(STy->getElementType(i), EltAlign);
1800       if (EltAlign > MaxAlign)
1801         MaxAlign = EltAlign;
1802       if (MaxAlign == 16)
1803         break;
1804     }
1805   }
1806 }
1807
1808 /// Return the desired alignment for ByVal aggregate
1809 /// function arguments in the caller parameter area. For X86, aggregates
1810 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1811 /// are at 4-byte boundaries.
1812 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1813                                                   const DataLayout &DL) const {
1814   if (Subtarget->is64Bit()) {
1815     // Max of 8 and alignment of type.
1816     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1817     if (TyAlign > 8)
1818       return TyAlign;
1819     return 8;
1820   }
1821
1822   unsigned Align = 4;
1823   if (Subtarget->hasSSE1())
1824     getMaxByValAlign(Ty, Align);
1825   return Align;
1826 }
1827
1828 /// Returns the target specific optimal type for load
1829 /// and store operations as a result of memset, memcpy, and memmove
1830 /// lowering. If DstAlign is zero that means it's safe to destination
1831 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1832 /// means there isn't a need to check it against alignment requirement,
1833 /// probably because the source does not need to be loaded. If 'IsMemset' is
1834 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1835 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1836 /// source is constant so it does not need to be loaded.
1837 /// It returns EVT::Other if the type should be determined using generic
1838 /// target-independent logic.
1839 EVT
1840 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1841                                        unsigned DstAlign, unsigned SrcAlign,
1842                                        bool IsMemset, bool ZeroMemset,
1843                                        bool MemcpyStrSrc,
1844                                        MachineFunction &MF) const {
1845   const Function *F = MF.getFunction();
1846   if ((!IsMemset || ZeroMemset) &&
1847       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1848     if (Size >= 16 &&
1849         (Subtarget->isUnalignedMemAccessFast() ||
1850          ((DstAlign == 0 || DstAlign >= 16) &&
1851           (SrcAlign == 0 || SrcAlign >= 16)))) {
1852       if (Size >= 32) {
1853         if (Subtarget->hasInt256())
1854           return MVT::v8i32;
1855         if (Subtarget->hasFp256())
1856           return MVT::v8f32;
1857       }
1858       if (Subtarget->hasSSE2())
1859         return MVT::v4i32;
1860       if (Subtarget->hasSSE1())
1861         return MVT::v4f32;
1862     } else if (!MemcpyStrSrc && Size >= 8 &&
1863                !Subtarget->is64Bit() &&
1864                Subtarget->hasSSE2()) {
1865       // Do not use f64 to lower memcpy if source is string constant. It's
1866       // better to use i32 to avoid the loads.
1867       return MVT::f64;
1868     }
1869   }
1870   if (Subtarget->is64Bit() && Size >= 8)
1871     return MVT::i64;
1872   return MVT::i32;
1873 }
1874
1875 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1876   if (VT == MVT::f32)
1877     return X86ScalarSSEf32;
1878   else if (VT == MVT::f64)
1879     return X86ScalarSSEf64;
1880   return true;
1881 }
1882
1883 bool
1884 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1885                                                   unsigned,
1886                                                   unsigned,
1887                                                   bool *Fast) const {
1888   if (Fast)
1889     *Fast = Subtarget->isUnalignedMemAccessFast();
1890   return true;
1891 }
1892
1893 /// Return the entry encoding for a jump table in the
1894 /// current function.  The returned value is a member of the
1895 /// MachineJumpTableInfo::JTEntryKind enum.
1896 unsigned X86TargetLowering::getJumpTableEncoding() const {
1897   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1898   // symbol.
1899   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1900       Subtarget->isPICStyleGOT())
1901     return MachineJumpTableInfo::EK_Custom32;
1902
1903   // Otherwise, use the normal jump table encoding heuristics.
1904   return TargetLowering::getJumpTableEncoding();
1905 }
1906
1907 bool X86TargetLowering::useSoftFloat() const {
1908   return Subtarget->useSoftFloat();
1909 }
1910
1911 const MCExpr *
1912 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1913                                              const MachineBasicBlock *MBB,
1914                                              unsigned uid,MCContext &Ctx) const{
1915   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1916          Subtarget->isPICStyleGOT());
1917   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1918   // entries.
1919   return MCSymbolRefExpr::create(MBB->getSymbol(),
1920                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1921 }
1922
1923 /// Returns relocation base for the given PIC jumptable.
1924 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1925                                                     SelectionDAG &DAG) const {
1926   if (!Subtarget->is64Bit())
1927     // This doesn't have SDLoc associated with it, but is not really the
1928     // same as a Register.
1929     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1930                        getPointerTy(DAG.getDataLayout()));
1931   return Table;
1932 }
1933
1934 /// This returns the relocation base for the given PIC jumptable,
1935 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1936 const MCExpr *X86TargetLowering::
1937 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1938                              MCContext &Ctx) const {
1939   // X86-64 uses RIP relative addressing based on the jump table label.
1940   if (Subtarget->isPICStyleRIPRel())
1941     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1942
1943   // Otherwise, the reference is relative to the PIC base.
1944   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1945 }
1946
1947 std::pair<const TargetRegisterClass *, uint8_t>
1948 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1949                                            MVT VT) const {
1950   const TargetRegisterClass *RRC = nullptr;
1951   uint8_t Cost = 1;
1952   switch (VT.SimpleTy) {
1953   default:
1954     return TargetLowering::findRepresentativeClass(TRI, VT);
1955   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1956     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1957     break;
1958   case MVT::x86mmx:
1959     RRC = &X86::VR64RegClass;
1960     break;
1961   case MVT::f32: case MVT::f64:
1962   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1963   case MVT::v4f32: case MVT::v2f64:
1964   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1965   case MVT::v4f64:
1966     RRC = &X86::VR128RegClass;
1967     break;
1968   }
1969   return std::make_pair(RRC, Cost);
1970 }
1971
1972 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1973                                                unsigned &Offset) const {
1974   if (!Subtarget->isTargetLinux())
1975     return false;
1976
1977   if (Subtarget->is64Bit()) {
1978     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1979     Offset = 0x28;
1980     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1981       AddressSpace = 256;
1982     else
1983       AddressSpace = 257;
1984   } else {
1985     // %gs:0x14 on i386
1986     Offset = 0x14;
1987     AddressSpace = 256;
1988   }
1989   return true;
1990 }
1991
1992 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1993                                             unsigned DestAS) const {
1994   assert(SrcAS != DestAS && "Expected different address spaces!");
1995
1996   return SrcAS < 256 && DestAS < 256;
1997 }
1998
1999 //===----------------------------------------------------------------------===//
2000 //               Return Value Calling Convention Implementation
2001 //===----------------------------------------------------------------------===//
2002
2003 #include "X86GenCallingConv.inc"
2004
2005 bool
2006 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2007                                   MachineFunction &MF, bool isVarArg,
2008                         const SmallVectorImpl<ISD::OutputArg> &Outs,
2009                         LLVMContext &Context) const {
2010   SmallVector<CCValAssign, 16> RVLocs;
2011   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
2012   return CCInfo.CheckReturn(Outs, RetCC_X86);
2013 }
2014
2015 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
2016   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
2017   return ScratchRegs;
2018 }
2019
2020 SDValue
2021 X86TargetLowering::LowerReturn(SDValue Chain,
2022                                CallingConv::ID CallConv, bool isVarArg,
2023                                const SmallVectorImpl<ISD::OutputArg> &Outs,
2024                                const SmallVectorImpl<SDValue> &OutVals,
2025                                SDLoc dl, SelectionDAG &DAG) const {
2026   MachineFunction &MF = DAG.getMachineFunction();
2027   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2028
2029   SmallVector<CCValAssign, 16> RVLocs;
2030   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2031   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2032
2033   SDValue Flag;
2034   SmallVector<SDValue, 6> RetOps;
2035   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2036   // Operand #1 = Bytes To Pop
2037   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2038                    MVT::i16));
2039
2040   // Copy the result values into the output registers.
2041   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2042     CCValAssign &VA = RVLocs[i];
2043     assert(VA.isRegLoc() && "Can only return in registers!");
2044     SDValue ValToCopy = OutVals[i];
2045     EVT ValVT = ValToCopy.getValueType();
2046
2047     // Promote values to the appropriate types.
2048     if (VA.getLocInfo() == CCValAssign::SExt)
2049       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2050     else if (VA.getLocInfo() == CCValAssign::ZExt)
2051       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2052     else if (VA.getLocInfo() == CCValAssign::AExt) {
2053       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2054         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2055       else
2056         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2057     }
2058     else if (VA.getLocInfo() == CCValAssign::BCvt)
2059       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2060
2061     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2062            "Unexpected FP-extend for return value.");
2063
2064     // If this is x86-64, and we disabled SSE, we can't return FP values,
2065     // or SSE or MMX vectors.
2066     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2067          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2068           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2069       report_fatal_error("SSE register return with SSE disabled");
2070     }
2071     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2072     // llvm-gcc has never done it right and no one has noticed, so this
2073     // should be OK for now.
2074     if (ValVT == MVT::f64 &&
2075         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2076       report_fatal_error("SSE2 register return with SSE2 disabled");
2077
2078     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2079     // the RET instruction and handled by the FP Stackifier.
2080     if (VA.getLocReg() == X86::FP0 ||
2081         VA.getLocReg() == X86::FP1) {
2082       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2083       // change the value to the FP stack register class.
2084       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2085         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2086       RetOps.push_back(ValToCopy);
2087       // Don't emit a copytoreg.
2088       continue;
2089     }
2090
2091     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2092     // which is returned in RAX / RDX.
2093     if (Subtarget->is64Bit()) {
2094       if (ValVT == MVT::x86mmx) {
2095         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2096           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2097           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2098                                   ValToCopy);
2099           // If we don't have SSE2 available, convert to v4f32 so the generated
2100           // register is legal.
2101           if (!Subtarget->hasSSE2())
2102             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2103         }
2104       }
2105     }
2106
2107     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2108     Flag = Chain.getValue(1);
2109     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2110   }
2111
2112   // All x86 ABIs require that for returning structs by value we copy
2113   // the sret argument into %rax/%eax (depending on ABI) for the return.
2114   // We saved the argument into a virtual register in the entry block,
2115   // so now we copy the value out and into %rax/%eax.
2116   //
2117   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2118   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2119   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2120   // either case FuncInfo->setSRetReturnReg() will have been called.
2121   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2122     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2123                                      getPointerTy(MF.getDataLayout()));
2124
2125     unsigned RetValReg
2126         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2127           X86::RAX : X86::EAX;
2128     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2129     Flag = Chain.getValue(1);
2130
2131     // RAX/EAX now acts like a return value.
2132     RetOps.push_back(
2133         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2134   }
2135
2136   RetOps[0] = Chain;  // Update chain.
2137
2138   // Add the flag if we have it.
2139   if (Flag.getNode())
2140     RetOps.push_back(Flag);
2141
2142   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2143 }
2144
2145 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2146   if (N->getNumValues() != 1)
2147     return false;
2148   if (!N->hasNUsesOfValue(1, 0))
2149     return false;
2150
2151   SDValue TCChain = Chain;
2152   SDNode *Copy = *N->use_begin();
2153   if (Copy->getOpcode() == ISD::CopyToReg) {
2154     // If the copy has a glue operand, we conservatively assume it isn't safe to
2155     // perform a tail call.
2156     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2157       return false;
2158     TCChain = Copy->getOperand(0);
2159   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2160     return false;
2161
2162   bool HasRet = false;
2163   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2164        UI != UE; ++UI) {
2165     if (UI->getOpcode() != X86ISD::RET_FLAG)
2166       return false;
2167     // If we are returning more than one value, we can definitely
2168     // not make a tail call see PR19530
2169     if (UI->getNumOperands() > 4)
2170       return false;
2171     if (UI->getNumOperands() == 4 &&
2172         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2173       return false;
2174     HasRet = true;
2175   }
2176
2177   if (!HasRet)
2178     return false;
2179
2180   Chain = TCChain;
2181   return true;
2182 }
2183
2184 EVT
2185 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2186                                             ISD::NodeType ExtendKind) const {
2187   MVT ReturnMVT;
2188   // TODO: Is this also valid on 32-bit?
2189   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2190     ReturnMVT = MVT::i8;
2191   else
2192     ReturnMVT = MVT::i32;
2193
2194   EVT MinVT = getRegisterType(Context, ReturnMVT);
2195   return VT.bitsLT(MinVT) ? MinVT : VT;
2196 }
2197
2198 /// Lower the result values of a call into the
2199 /// appropriate copies out of appropriate physical registers.
2200 ///
2201 SDValue
2202 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2203                                    CallingConv::ID CallConv, bool isVarArg,
2204                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2205                                    SDLoc dl, SelectionDAG &DAG,
2206                                    SmallVectorImpl<SDValue> &InVals) const {
2207
2208   // Assign locations to each value returned by this call.
2209   SmallVector<CCValAssign, 16> RVLocs;
2210   bool Is64Bit = Subtarget->is64Bit();
2211   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2212                  *DAG.getContext());
2213   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2214
2215   // Copy all of the result registers out of their specified physreg.
2216   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2217     CCValAssign &VA = RVLocs[i];
2218     EVT CopyVT = VA.getLocVT();
2219
2220     // If this is x86-64, and we disabled SSE, we can't return FP values
2221     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2222         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2223       report_fatal_error("SSE register return with SSE disabled");
2224     }
2225
2226     // If we prefer to use the value in xmm registers, copy it out as f80 and
2227     // use a truncate to move it from fp stack reg to xmm reg.
2228     bool RoundAfterCopy = false;
2229     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2230         isScalarFPTypeInSSEReg(VA.getValVT())) {
2231       CopyVT = MVT::f80;
2232       RoundAfterCopy = (CopyVT != VA.getLocVT());
2233     }
2234
2235     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2236                                CopyVT, InFlag).getValue(1);
2237     SDValue Val = Chain.getValue(0);
2238
2239     if (RoundAfterCopy)
2240       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2241                         // This truncation won't change the value.
2242                         DAG.getIntPtrConstant(1, dl));
2243
2244     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2245       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2246
2247     InFlag = Chain.getValue(2);
2248     InVals.push_back(Val);
2249   }
2250
2251   return Chain;
2252 }
2253
2254 //===----------------------------------------------------------------------===//
2255 //                C & StdCall & Fast Calling Convention implementation
2256 //===----------------------------------------------------------------------===//
2257 //  StdCall calling convention seems to be standard for many Windows' API
2258 //  routines and around. It differs from C calling convention just a little:
2259 //  callee should clean up the stack, not caller. Symbols should be also
2260 //  decorated in some fancy way :) It doesn't support any vector arguments.
2261 //  For info on fast calling convention see Fast Calling Convention (tail call)
2262 //  implementation LowerX86_32FastCCCallTo.
2263
2264 /// CallIsStructReturn - Determines whether a call uses struct return
2265 /// semantics.
2266 enum StructReturnType {
2267   NotStructReturn,
2268   RegStructReturn,
2269   StackStructReturn
2270 };
2271 static StructReturnType
2272 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2273   if (Outs.empty())
2274     return NotStructReturn;
2275
2276   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2277   if (!Flags.isSRet())
2278     return NotStructReturn;
2279   if (Flags.isInReg())
2280     return RegStructReturn;
2281   return StackStructReturn;
2282 }
2283
2284 /// Determines whether a function uses struct return semantics.
2285 static StructReturnType
2286 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2287   if (Ins.empty())
2288     return NotStructReturn;
2289
2290   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2291   if (!Flags.isSRet())
2292     return NotStructReturn;
2293   if (Flags.isInReg())
2294     return RegStructReturn;
2295   return StackStructReturn;
2296 }
2297
2298 /// Make a copy of an aggregate at address specified by "Src" to address
2299 /// "Dst" with size and alignment information specified by the specific
2300 /// parameter attribute. The copy will be passed as a byval function parameter.
2301 static SDValue
2302 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2303                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2304                           SDLoc dl) {
2305   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2306
2307   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2308                        /*isVolatile*/false, /*AlwaysInline=*/true,
2309                        /*isTailCall*/false,
2310                        MachinePointerInfo(), MachinePointerInfo());
2311 }
2312
2313 /// Return true if the calling convention is one that
2314 /// supports tail call optimization.
2315 static bool IsTailCallConvention(CallingConv::ID CC) {
2316   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2317           CC == CallingConv::HiPE);
2318 }
2319
2320 /// \brief Return true if the calling convention is a C calling convention.
2321 static bool IsCCallConvention(CallingConv::ID CC) {
2322   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2323           CC == CallingConv::X86_64_SysV);
2324 }
2325
2326 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2327   auto Attr =
2328       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2329   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2330     return false;
2331
2332   CallSite CS(CI);
2333   CallingConv::ID CalleeCC = CS.getCallingConv();
2334   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2335     return false;
2336
2337   return true;
2338 }
2339
2340 /// Return true if the function is being made into
2341 /// a tailcall target by changing its ABI.
2342 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2343                                    bool GuaranteedTailCallOpt) {
2344   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2345 }
2346
2347 SDValue
2348 X86TargetLowering::LowerMemArgument(SDValue Chain,
2349                                     CallingConv::ID CallConv,
2350                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2351                                     SDLoc dl, SelectionDAG &DAG,
2352                                     const CCValAssign &VA,
2353                                     MachineFrameInfo *MFI,
2354                                     unsigned i) const {
2355   // Create the nodes corresponding to a load from this parameter slot.
2356   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2357   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2358       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2359   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2360   EVT ValVT;
2361
2362   // If value is passed by pointer we have address passed instead of the value
2363   // itself.
2364   bool ExtendedInMem = VA.isExtInLoc() &&
2365     VA.getValVT().getScalarType() == MVT::i1;
2366
2367   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2368     ValVT = VA.getLocVT();
2369   else
2370     ValVT = VA.getValVT();
2371
2372   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2373   // changed with more analysis.
2374   // In case of tail call optimization mark all arguments mutable. Since they
2375   // could be overwritten by lowering of arguments in case of a tail call.
2376   if (Flags.isByVal()) {
2377     unsigned Bytes = Flags.getByValSize();
2378     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2379     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2380     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2381   } else {
2382     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2383                                     VA.getLocMemOffset(), isImmutable);
2384     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2385     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2386                                MachinePointerInfo::getFixedStack(FI),
2387                                false, false, false, 0);
2388     return ExtendedInMem ?
2389       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2390   }
2391 }
2392
2393 // FIXME: Get this from tablegen.
2394 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2395                                                 const X86Subtarget *Subtarget) {
2396   assert(Subtarget->is64Bit());
2397
2398   if (Subtarget->isCallingConvWin64(CallConv)) {
2399     static const MCPhysReg GPR64ArgRegsWin64[] = {
2400       X86::RCX, X86::RDX, X86::R8,  X86::R9
2401     };
2402     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2403   }
2404
2405   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2406     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2407   };
2408   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2409 }
2410
2411 // FIXME: Get this from tablegen.
2412 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2413                                                 CallingConv::ID CallConv,
2414                                                 const X86Subtarget *Subtarget) {
2415   assert(Subtarget->is64Bit());
2416   if (Subtarget->isCallingConvWin64(CallConv)) {
2417     // The XMM registers which might contain var arg parameters are shadowed
2418     // in their paired GPR.  So we only need to save the GPR to their home
2419     // slots.
2420     // TODO: __vectorcall will change this.
2421     return None;
2422   }
2423
2424   const Function *Fn = MF.getFunction();
2425   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2426   bool isSoftFloat = Subtarget->useSoftFloat();
2427   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2428          "SSE register cannot be used when SSE is disabled!");
2429   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2430     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2431     // registers.
2432     return None;
2433
2434   static const MCPhysReg XMMArgRegs64Bit[] = {
2435     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2436     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2437   };
2438   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2439 }
2440
2441 SDValue
2442 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2443                                         CallingConv::ID CallConv,
2444                                         bool isVarArg,
2445                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2446                                         SDLoc dl,
2447                                         SelectionDAG &DAG,
2448                                         SmallVectorImpl<SDValue> &InVals)
2449                                           const {
2450   MachineFunction &MF = DAG.getMachineFunction();
2451   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2452   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2453
2454   const Function* Fn = MF.getFunction();
2455   if (Fn->hasExternalLinkage() &&
2456       Subtarget->isTargetCygMing() &&
2457       Fn->getName() == "main")
2458     FuncInfo->setForceFramePointer(true);
2459
2460   MachineFrameInfo *MFI = MF.getFrameInfo();
2461   bool Is64Bit = Subtarget->is64Bit();
2462   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2463
2464   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2465          "Var args not supported with calling convention fastcc, ghc or hipe");
2466
2467   // Assign locations to all of the incoming arguments.
2468   SmallVector<CCValAssign, 16> ArgLocs;
2469   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2470
2471   // Allocate shadow area for Win64
2472   if (IsWin64)
2473     CCInfo.AllocateStack(32, 8);
2474
2475   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2476
2477   unsigned LastVal = ~0U;
2478   SDValue ArgValue;
2479   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2480     CCValAssign &VA = ArgLocs[i];
2481     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2482     // places.
2483     assert(VA.getValNo() != LastVal &&
2484            "Don't support value assigned to multiple locs yet");
2485     (void)LastVal;
2486     LastVal = VA.getValNo();
2487
2488     if (VA.isRegLoc()) {
2489       EVT RegVT = VA.getLocVT();
2490       const TargetRegisterClass *RC;
2491       if (RegVT == MVT::i32)
2492         RC = &X86::GR32RegClass;
2493       else if (Is64Bit && RegVT == MVT::i64)
2494         RC = &X86::GR64RegClass;
2495       else if (RegVT == MVT::f32)
2496         RC = &X86::FR32RegClass;
2497       else if (RegVT == MVT::f64)
2498         RC = &X86::FR64RegClass;
2499       else if (RegVT.is512BitVector())
2500         RC = &X86::VR512RegClass;
2501       else if (RegVT.is256BitVector())
2502         RC = &X86::VR256RegClass;
2503       else if (RegVT.is128BitVector())
2504         RC = &X86::VR128RegClass;
2505       else if (RegVT == MVT::x86mmx)
2506         RC = &X86::VR64RegClass;
2507       else if (RegVT == MVT::i1)
2508         RC = &X86::VK1RegClass;
2509       else if (RegVT == MVT::v8i1)
2510         RC = &X86::VK8RegClass;
2511       else if (RegVT == MVT::v16i1)
2512         RC = &X86::VK16RegClass;
2513       else if (RegVT == MVT::v32i1)
2514         RC = &X86::VK32RegClass;
2515       else if (RegVT == MVT::v64i1)
2516         RC = &X86::VK64RegClass;
2517       else
2518         llvm_unreachable("Unknown argument type!");
2519
2520       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2521       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2522
2523       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2524       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2525       // right size.
2526       if (VA.getLocInfo() == CCValAssign::SExt)
2527         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2528                                DAG.getValueType(VA.getValVT()));
2529       else if (VA.getLocInfo() == CCValAssign::ZExt)
2530         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2531                                DAG.getValueType(VA.getValVT()));
2532       else if (VA.getLocInfo() == CCValAssign::BCvt)
2533         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2534
2535       if (VA.isExtInLoc()) {
2536         // Handle MMX values passed in XMM regs.
2537         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2538           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2539         else
2540           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2541       }
2542     } else {
2543       assert(VA.isMemLoc());
2544       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2545     }
2546
2547     // If value is passed via pointer - do a load.
2548     if (VA.getLocInfo() == CCValAssign::Indirect)
2549       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2550                              MachinePointerInfo(), false, false, false, 0);
2551
2552     InVals.push_back(ArgValue);
2553   }
2554
2555   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2556     // All x86 ABIs require that for returning structs by value we copy the
2557     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2558     // the argument into a virtual register so that we can access it from the
2559     // return points.
2560     if (Ins[i].Flags.isSRet()) {
2561       unsigned Reg = FuncInfo->getSRetReturnReg();
2562       if (!Reg) {
2563         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2564         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2565         FuncInfo->setSRetReturnReg(Reg);
2566       }
2567       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2568       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2569       break;
2570     }
2571   }
2572
2573   unsigned StackSize = CCInfo.getNextStackOffset();
2574   // Align stack specially for tail calls.
2575   if (FuncIsMadeTailCallSafe(CallConv,
2576                              MF.getTarget().Options.GuaranteedTailCallOpt))
2577     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2578
2579   // If the function takes variable number of arguments, make a frame index for
2580   // the start of the first vararg value... for expansion of llvm.va_start. We
2581   // can skip this if there are no va_start calls.
2582   if (MFI->hasVAStart() &&
2583       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2584                    CallConv != CallingConv::X86_ThisCall))) {
2585     FuncInfo->setVarArgsFrameIndex(
2586         MFI->CreateFixedObject(1, StackSize, true));
2587   }
2588
2589   MachineModuleInfo &MMI = MF.getMMI();
2590   const Function *WinEHParent = nullptr;
2591   if (MMI.hasWinEHFuncInfo(Fn))
2592     WinEHParent = MMI.getWinEHParent(Fn);
2593   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2594   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2595
2596   // Figure out if XMM registers are in use.
2597   assert(!(Subtarget->useSoftFloat() &&
2598            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2599          "SSE register cannot be used when SSE is disabled!");
2600
2601   // 64-bit calling conventions support varargs and register parameters, so we
2602   // have to do extra work to spill them in the prologue.
2603   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2604     // Find the first unallocated argument registers.
2605     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2606     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2607     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2608     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2609     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2610            "SSE register cannot be used when SSE is disabled!");
2611
2612     // Gather all the live in physical registers.
2613     SmallVector<SDValue, 6> LiveGPRs;
2614     SmallVector<SDValue, 8> LiveXMMRegs;
2615     SDValue ALVal;
2616     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2617       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2618       LiveGPRs.push_back(
2619           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2620     }
2621     if (!ArgXMMs.empty()) {
2622       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2623       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2624       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2625         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2626         LiveXMMRegs.push_back(
2627             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2628       }
2629     }
2630
2631     if (IsWin64) {
2632       // Get to the caller-allocated home save location.  Add 8 to account
2633       // for the return address.
2634       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2635       FuncInfo->setRegSaveFrameIndex(
2636           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2637       // Fixup to set vararg frame on shadow area (4 x i64).
2638       if (NumIntRegs < 4)
2639         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2640     } else {
2641       // For X86-64, if there are vararg parameters that are passed via
2642       // registers, then we must store them to their spots on the stack so
2643       // they may be loaded by deferencing the result of va_next.
2644       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2645       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2646       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2647           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2648     }
2649
2650     // Store the integer parameter registers.
2651     SmallVector<SDValue, 8> MemOps;
2652     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2653                                       getPointerTy(DAG.getDataLayout()));
2654     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2655     for (SDValue Val : LiveGPRs) {
2656       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2657                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2658       SDValue Store =
2659         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2660                      MachinePointerInfo::getFixedStack(
2661                        FuncInfo->getRegSaveFrameIndex(), Offset),
2662                      false, false, 0);
2663       MemOps.push_back(Store);
2664       Offset += 8;
2665     }
2666
2667     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2668       // Now store the XMM (fp + vector) parameter registers.
2669       SmallVector<SDValue, 12> SaveXMMOps;
2670       SaveXMMOps.push_back(Chain);
2671       SaveXMMOps.push_back(ALVal);
2672       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2673                              FuncInfo->getRegSaveFrameIndex(), dl));
2674       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2675                              FuncInfo->getVarArgsFPOffset(), dl));
2676       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2677                         LiveXMMRegs.end());
2678       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2679                                    MVT::Other, SaveXMMOps));
2680     }
2681
2682     if (!MemOps.empty())
2683       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2684   } else if (IsWin64 && IsWinEHOutlined) {
2685     // Get to the caller-allocated home save location.  Add 8 to account
2686     // for the return address.
2687     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2688     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2689         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2690
2691     MMI.getWinEHFuncInfo(Fn)
2692         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2693         FuncInfo->getRegSaveFrameIndex();
2694
2695     // Store the second integer parameter (rdx) into rsp+16 relative to the
2696     // stack pointer at the entry of the function.
2697     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2698                                       getPointerTy(DAG.getDataLayout()));
2699     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2700     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2701     Chain = DAG.getStore(
2702         Val.getValue(1), dl, Val, RSFIN,
2703         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2704         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2705   }
2706
2707   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2708     // Find the largest legal vector type.
2709     MVT VecVT = MVT::Other;
2710     // FIXME: Only some x86_32 calling conventions support AVX512.
2711     if (Subtarget->hasAVX512() &&
2712         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2713                      CallConv == CallingConv::Intel_OCL_BI)))
2714       VecVT = MVT::v16f32;
2715     else if (Subtarget->hasAVX())
2716       VecVT = MVT::v8f32;
2717     else if (Subtarget->hasSSE2())
2718       VecVT = MVT::v4f32;
2719
2720     // We forward some GPRs and some vector types.
2721     SmallVector<MVT, 2> RegParmTypes;
2722     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2723     RegParmTypes.push_back(IntVT);
2724     if (VecVT != MVT::Other)
2725       RegParmTypes.push_back(VecVT);
2726
2727     // Compute the set of forwarded registers. The rest are scratch.
2728     SmallVectorImpl<ForwardedRegister> &Forwards =
2729         FuncInfo->getForwardedMustTailRegParms();
2730     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2731
2732     // Conservatively forward AL on x86_64, since it might be used for varargs.
2733     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2734       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2735       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2736     }
2737
2738     // Copy all forwards from physical to virtual registers.
2739     for (ForwardedRegister &F : Forwards) {
2740       // FIXME: Can we use a less constrained schedule?
2741       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2742       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2743       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2744     }
2745   }
2746
2747   // Some CCs need callee pop.
2748   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2749                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2750     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2751   } else {
2752     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2753     // If this is an sret function, the return should pop the hidden pointer.
2754     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2755         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2756         argsAreStructReturn(Ins) == StackStructReturn)
2757       FuncInfo->setBytesToPopOnReturn(4);
2758   }
2759
2760   if (!Is64Bit) {
2761     // RegSaveFrameIndex is X86-64 only.
2762     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2763     if (CallConv == CallingConv::X86_FastCall ||
2764         CallConv == CallingConv::X86_ThisCall)
2765       // fastcc functions can't have varargs.
2766       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2767   }
2768
2769   FuncInfo->setArgumentStackSize(StackSize);
2770
2771   if (IsWinEHParent) {
2772     if (Is64Bit) {
2773       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2774       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2775       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2776       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2777       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2778                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2779                            /*isVolatile=*/true,
2780                            /*isNonTemporal=*/false, /*Alignment=*/0);
2781     } else {
2782       // Functions using Win32 EH are considered to have opaque SP adjustments
2783       // to force local variables to be addressed from the frame or base
2784       // pointers.
2785       MFI->setHasOpaqueSPAdjustment(true);
2786     }
2787   }
2788
2789   return Chain;
2790 }
2791
2792 SDValue
2793 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2794                                     SDValue StackPtr, SDValue Arg,
2795                                     SDLoc dl, SelectionDAG &DAG,
2796                                     const CCValAssign &VA,
2797                                     ISD::ArgFlagsTy Flags) const {
2798   unsigned LocMemOffset = VA.getLocMemOffset();
2799   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2800   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2801                        StackPtr, PtrOff);
2802   if (Flags.isByVal())
2803     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2804
2805   return DAG.getStore(Chain, dl, Arg, PtrOff,
2806                       MachinePointerInfo::getStack(LocMemOffset),
2807                       false, false, 0);
2808 }
2809
2810 /// Emit a load of return address if tail call
2811 /// optimization is performed and it is required.
2812 SDValue
2813 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2814                                            SDValue &OutRetAddr, SDValue Chain,
2815                                            bool IsTailCall, bool Is64Bit,
2816                                            int FPDiff, SDLoc dl) const {
2817   // Adjust the Return address stack slot.
2818   EVT VT = getPointerTy(DAG.getDataLayout());
2819   OutRetAddr = getReturnAddressFrameIndex(DAG);
2820
2821   // Load the "old" Return address.
2822   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2823                            false, false, false, 0);
2824   return SDValue(OutRetAddr.getNode(), 1);
2825 }
2826
2827 /// Emit a store of the return address if tail call
2828 /// optimization is performed and it is required (FPDiff!=0).
2829 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2830                                         SDValue Chain, SDValue RetAddrFrIdx,
2831                                         EVT PtrVT, unsigned SlotSize,
2832                                         int FPDiff, SDLoc dl) {
2833   // Store the return address to the appropriate stack slot.
2834   if (!FPDiff) return Chain;
2835   // Calculate the new stack slot for the return address.
2836   int NewReturnAddrFI =
2837     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2838                                          false);
2839   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2840   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2841                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2842                        false, false, 0);
2843   return Chain;
2844 }
2845
2846 SDValue
2847 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2848                              SmallVectorImpl<SDValue> &InVals) const {
2849   SelectionDAG &DAG                     = CLI.DAG;
2850   SDLoc &dl                             = CLI.DL;
2851   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2852   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2853   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2854   SDValue Chain                         = CLI.Chain;
2855   SDValue Callee                        = CLI.Callee;
2856   CallingConv::ID CallConv              = CLI.CallConv;
2857   bool &isTailCall                      = CLI.IsTailCall;
2858   bool isVarArg                         = CLI.IsVarArg;
2859
2860   MachineFunction &MF = DAG.getMachineFunction();
2861   bool Is64Bit        = Subtarget->is64Bit();
2862   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2863   StructReturnType SR = callIsStructReturn(Outs);
2864   bool IsSibcall      = false;
2865   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2866   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2867
2868   if (Attr.getValueAsString() == "true")
2869     isTailCall = false;
2870
2871   if (Subtarget->isPICStyleGOT() &&
2872       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2873     // If we are using a GOT, disable tail calls to external symbols with
2874     // default visibility. Tail calling such a symbol requires using a GOT
2875     // relocation, which forces early binding of the symbol. This breaks code
2876     // that require lazy function symbol resolution. Using musttail or
2877     // GuaranteedTailCallOpt will override this.
2878     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2879     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2880                G->getGlobal()->hasDefaultVisibility()))
2881       isTailCall = false;
2882   }
2883
2884   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2885   if (IsMustTail) {
2886     // Force this to be a tail call.  The verifier rules are enough to ensure
2887     // that we can lower this successfully without moving the return address
2888     // around.
2889     isTailCall = true;
2890   } else if (isTailCall) {
2891     // Check if it's really possible to do a tail call.
2892     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2893                     isVarArg, SR != NotStructReturn,
2894                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2895                     Outs, OutVals, Ins, DAG);
2896
2897     // Sibcalls are automatically detected tailcalls which do not require
2898     // ABI changes.
2899     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2900       IsSibcall = true;
2901
2902     if (isTailCall)
2903       ++NumTailCalls;
2904   }
2905
2906   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2907          "Var args not supported with calling convention fastcc, ghc or hipe");
2908
2909   // Analyze operands of the call, assigning locations to each operand.
2910   SmallVector<CCValAssign, 16> ArgLocs;
2911   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2912
2913   // Allocate shadow area for Win64
2914   if (IsWin64)
2915     CCInfo.AllocateStack(32, 8);
2916
2917   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2918
2919   // Get a count of how many bytes are to be pushed on the stack.
2920   unsigned NumBytes = CCInfo.getNextStackOffset();
2921   if (IsSibcall)
2922     // This is a sibcall. The memory operands are available in caller's
2923     // own caller's stack.
2924     NumBytes = 0;
2925   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2926            IsTailCallConvention(CallConv))
2927     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2928
2929   int FPDiff = 0;
2930   if (isTailCall && !IsSibcall && !IsMustTail) {
2931     // Lower arguments at fp - stackoffset + fpdiff.
2932     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2933
2934     FPDiff = NumBytesCallerPushed - NumBytes;
2935
2936     // Set the delta of movement of the returnaddr stackslot.
2937     // But only set if delta is greater than previous delta.
2938     if (FPDiff < X86Info->getTCReturnAddrDelta())
2939       X86Info->setTCReturnAddrDelta(FPDiff);
2940   }
2941
2942   unsigned NumBytesToPush = NumBytes;
2943   unsigned NumBytesToPop = NumBytes;
2944
2945   // If we have an inalloca argument, all stack space has already been allocated
2946   // for us and be right at the top of the stack.  We don't support multiple
2947   // arguments passed in memory when using inalloca.
2948   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2949     NumBytesToPush = 0;
2950     if (!ArgLocs.back().isMemLoc())
2951       report_fatal_error("cannot use inalloca attribute on a register "
2952                          "parameter");
2953     if (ArgLocs.back().getLocMemOffset() != 0)
2954       report_fatal_error("any parameter with the inalloca attribute must be "
2955                          "the only memory argument");
2956   }
2957
2958   if (!IsSibcall)
2959     Chain = DAG.getCALLSEQ_START(
2960         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2961
2962   SDValue RetAddrFrIdx;
2963   // Load return address for tail calls.
2964   if (isTailCall && FPDiff)
2965     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2966                                     Is64Bit, FPDiff, dl);
2967
2968   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2969   SmallVector<SDValue, 8> MemOpChains;
2970   SDValue StackPtr;
2971
2972   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2973   // of tail call optimization arguments are handle later.
2974   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2975   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2976     // Skip inalloca arguments, they have already been written.
2977     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2978     if (Flags.isInAlloca())
2979       continue;
2980
2981     CCValAssign &VA = ArgLocs[i];
2982     EVT RegVT = VA.getLocVT();
2983     SDValue Arg = OutVals[i];
2984     bool isByVal = Flags.isByVal();
2985
2986     // Promote the value if needed.
2987     switch (VA.getLocInfo()) {
2988     default: llvm_unreachable("Unknown loc info!");
2989     case CCValAssign::Full: break;
2990     case CCValAssign::SExt:
2991       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2992       break;
2993     case CCValAssign::ZExt:
2994       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2995       break;
2996     case CCValAssign::AExt:
2997       if (Arg.getValueType().isVector() &&
2998           Arg.getValueType().getScalarType() == MVT::i1)
2999         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
3000       else if (RegVT.is128BitVector()) {
3001         // Special case: passing MMX values in XMM registers.
3002         Arg = DAG.getBitcast(MVT::i64, Arg);
3003         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
3004         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
3005       } else
3006         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
3007       break;
3008     case CCValAssign::BCvt:
3009       Arg = DAG.getBitcast(RegVT, Arg);
3010       break;
3011     case CCValAssign::Indirect: {
3012       // Store the argument.
3013       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
3014       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
3015       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
3016                            MachinePointerInfo::getFixedStack(FI),
3017                            false, false, 0);
3018       Arg = SpillSlot;
3019       break;
3020     }
3021     }
3022
3023     if (VA.isRegLoc()) {
3024       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3025       if (isVarArg && IsWin64) {
3026         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3027         // shadow reg if callee is a varargs function.
3028         unsigned ShadowReg = 0;
3029         switch (VA.getLocReg()) {
3030         case X86::XMM0: ShadowReg = X86::RCX; break;
3031         case X86::XMM1: ShadowReg = X86::RDX; break;
3032         case X86::XMM2: ShadowReg = X86::R8; break;
3033         case X86::XMM3: ShadowReg = X86::R9; break;
3034         }
3035         if (ShadowReg)
3036           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3037       }
3038     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3039       assert(VA.isMemLoc());
3040       if (!StackPtr.getNode())
3041         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3042                                       getPointerTy(DAG.getDataLayout()));
3043       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3044                                              dl, DAG, VA, Flags));
3045     }
3046   }
3047
3048   if (!MemOpChains.empty())
3049     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3050
3051   if (Subtarget->isPICStyleGOT()) {
3052     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3053     // GOT pointer.
3054     if (!isTailCall) {
3055       RegsToPass.push_back(std::make_pair(
3056           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3057                                           getPointerTy(DAG.getDataLayout()))));
3058     } else {
3059       // If we are tail calling and generating PIC/GOT style code load the
3060       // address of the callee into ECX. The value in ecx is used as target of
3061       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3062       // for tail calls on PIC/GOT architectures. Normally we would just put the
3063       // address of GOT into ebx and then call target@PLT. But for tail calls
3064       // ebx would be restored (since ebx is callee saved) before jumping to the
3065       // target@PLT.
3066
3067       // Note: The actual moving to ECX is done further down.
3068       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3069       if (G && !G->getGlobal()->hasLocalLinkage() &&
3070           G->getGlobal()->hasDefaultVisibility())
3071         Callee = LowerGlobalAddress(Callee, DAG);
3072       else if (isa<ExternalSymbolSDNode>(Callee))
3073         Callee = LowerExternalSymbol(Callee, DAG);
3074     }
3075   }
3076
3077   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3078     // From AMD64 ABI document:
3079     // For calls that may call functions that use varargs or stdargs
3080     // (prototype-less calls or calls to functions containing ellipsis (...) in
3081     // the declaration) %al is used as hidden argument to specify the number
3082     // of SSE registers used. The contents of %al do not need to match exactly
3083     // the number of registers, but must be an ubound on the number of SSE
3084     // registers used and is in the range 0 - 8 inclusive.
3085
3086     // Count the number of XMM registers allocated.
3087     static const MCPhysReg XMMArgRegs[] = {
3088       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3089       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3090     };
3091     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3092     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3093            && "SSE registers cannot be used when SSE is disabled");
3094
3095     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3096                                         DAG.getConstant(NumXMMRegs, dl,
3097                                                         MVT::i8)));
3098   }
3099
3100   if (isVarArg && IsMustTail) {
3101     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3102     for (const auto &F : Forwards) {
3103       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3104       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3105     }
3106   }
3107
3108   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3109   // don't need this because the eligibility check rejects calls that require
3110   // shuffling arguments passed in memory.
3111   if (!IsSibcall && isTailCall) {
3112     // Force all the incoming stack arguments to be loaded from the stack
3113     // before any new outgoing arguments are stored to the stack, because the
3114     // outgoing stack slots may alias the incoming argument stack slots, and
3115     // the alias isn't otherwise explicit. This is slightly more conservative
3116     // than necessary, because it means that each store effectively depends
3117     // on every argument instead of just those arguments it would clobber.
3118     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3119
3120     SmallVector<SDValue, 8> MemOpChains2;
3121     SDValue FIN;
3122     int FI = 0;
3123     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3124       CCValAssign &VA = ArgLocs[i];
3125       if (VA.isRegLoc())
3126         continue;
3127       assert(VA.isMemLoc());
3128       SDValue Arg = OutVals[i];
3129       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3130       // Skip inalloca arguments.  They don't require any work.
3131       if (Flags.isInAlloca())
3132         continue;
3133       // Create frame index.
3134       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3135       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3136       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3137       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3138
3139       if (Flags.isByVal()) {
3140         // Copy relative to framepointer.
3141         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3142         if (!StackPtr.getNode())
3143           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3144                                         getPointerTy(DAG.getDataLayout()));
3145         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3146                              StackPtr, Source);
3147
3148         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3149                                                          ArgChain,
3150                                                          Flags, DAG, dl));
3151       } else {
3152         // Store relative to framepointer.
3153         MemOpChains2.push_back(
3154           DAG.getStore(ArgChain, dl, Arg, FIN,
3155                        MachinePointerInfo::getFixedStack(FI),
3156                        false, false, 0));
3157       }
3158     }
3159
3160     if (!MemOpChains2.empty())
3161       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3162
3163     // Store the return address to the appropriate stack slot.
3164     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3165                                      getPointerTy(DAG.getDataLayout()),
3166                                      RegInfo->getSlotSize(), FPDiff, dl);
3167   }
3168
3169   // Build a sequence of copy-to-reg nodes chained together with token chain
3170   // and flag operands which copy the outgoing args into registers.
3171   SDValue InFlag;
3172   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3173     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3174                              RegsToPass[i].second, InFlag);
3175     InFlag = Chain.getValue(1);
3176   }
3177
3178   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3179     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3180     // In the 64-bit large code model, we have to make all calls
3181     // through a register, since the call instruction's 32-bit
3182     // pc-relative offset may not be large enough to hold the whole
3183     // address.
3184   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3185     // If the callee is a GlobalAddress node (quite common, every direct call
3186     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3187     // it.
3188     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3189
3190     // We should use extra load for direct calls to dllimported functions in
3191     // non-JIT mode.
3192     const GlobalValue *GV = G->getGlobal();
3193     if (!GV->hasDLLImportStorageClass()) {
3194       unsigned char OpFlags = 0;
3195       bool ExtraLoad = false;
3196       unsigned WrapperKind = ISD::DELETED_NODE;
3197
3198       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3199       // external symbols most go through the PLT in PIC mode.  If the symbol
3200       // has hidden or protected visibility, or if it is static or local, then
3201       // we don't need to use the PLT - we can directly call it.
3202       if (Subtarget->isTargetELF() &&
3203           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3204           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3205         OpFlags = X86II::MO_PLT;
3206       } else if (Subtarget->isPICStyleStubAny() &&
3207                  !GV->isStrongDefinitionForLinker() &&
3208                  (!Subtarget->getTargetTriple().isMacOSX() ||
3209                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3210         // PC-relative references to external symbols should go through $stub,
3211         // unless we're building with the leopard linker or later, which
3212         // automatically synthesizes these stubs.
3213         OpFlags = X86II::MO_DARWIN_STUB;
3214       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3215                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3216         // If the function is marked as non-lazy, generate an indirect call
3217         // which loads from the GOT directly. This avoids runtime overhead
3218         // at the cost of eager binding (and one extra byte of encoding).
3219         OpFlags = X86II::MO_GOTPCREL;
3220         WrapperKind = X86ISD::WrapperRIP;
3221         ExtraLoad = true;
3222       }
3223
3224       Callee = DAG.getTargetGlobalAddress(
3225           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3226
3227       // Add a wrapper if needed.
3228       if (WrapperKind != ISD::DELETED_NODE)
3229         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3230                              getPointerTy(DAG.getDataLayout()), Callee);
3231       // Add extra indirection if needed.
3232       if (ExtraLoad)
3233         Callee = DAG.getLoad(
3234             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3235             MachinePointerInfo::getGOT(), false, false, false, 0);
3236     }
3237   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3238     unsigned char OpFlags = 0;
3239
3240     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3241     // external symbols should go through the PLT.
3242     if (Subtarget->isTargetELF() &&
3243         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3244       OpFlags = X86II::MO_PLT;
3245     } else if (Subtarget->isPICStyleStubAny() &&
3246                (!Subtarget->getTargetTriple().isMacOSX() ||
3247                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3248       // PC-relative references to external symbols should go through $stub,
3249       // unless we're building with the leopard linker or later, which
3250       // automatically synthesizes these stubs.
3251       OpFlags = X86II::MO_DARWIN_STUB;
3252     }
3253
3254     Callee = DAG.getTargetExternalSymbol(
3255         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3256   } else if (Subtarget->isTarget64BitILP32() &&
3257              Callee->getValueType(0) == MVT::i32) {
3258     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3259     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3260   }
3261
3262   // Returns a chain & a flag for retval copy to use.
3263   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3264   SmallVector<SDValue, 8> Ops;
3265
3266   if (!IsSibcall && isTailCall) {
3267     Chain = DAG.getCALLSEQ_END(Chain,
3268                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3269                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3270     InFlag = Chain.getValue(1);
3271   }
3272
3273   Ops.push_back(Chain);
3274   Ops.push_back(Callee);
3275
3276   if (isTailCall)
3277     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3278
3279   // Add argument registers to the end of the list so that they are known live
3280   // into the call.
3281   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3282     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3283                                   RegsToPass[i].second.getValueType()));
3284
3285   // Add a register mask operand representing the call-preserved registers.
3286   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3287   assert(Mask && "Missing call preserved mask for calling convention");
3288
3289   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3290   // the function clobbers all registers. If an exception is thrown, the runtime
3291   // will not restore CSRs.
3292   // FIXME: Model this more precisely so that we can register allocate across
3293   // the normal edge and spill and fill across the exceptional edge.
3294   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3295     const Function *CallerFn = MF.getFunction();
3296     EHPersonality Pers =
3297         CallerFn->hasPersonalityFn()
3298             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3299             : EHPersonality::Unknown;
3300     if (isMSVCEHPersonality(Pers))
3301       Mask = RegInfo->getNoPreservedMask();
3302   }
3303
3304   Ops.push_back(DAG.getRegisterMask(Mask));
3305
3306   if (InFlag.getNode())
3307     Ops.push_back(InFlag);
3308
3309   if (isTailCall) {
3310     // We used to do:
3311     //// If this is the first return lowered for this function, add the regs
3312     //// to the liveout set for the function.
3313     // This isn't right, although it's probably harmless on x86; liveouts
3314     // should be computed from returns not tail calls.  Consider a void
3315     // function making a tail call to a function returning int.
3316     MF.getFrameInfo()->setHasTailCall();
3317     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3318   }
3319
3320   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3321   InFlag = Chain.getValue(1);
3322
3323   // Create the CALLSEQ_END node.
3324   unsigned NumBytesForCalleeToPop;
3325   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3326                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3327     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3328   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3329            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3330            SR == StackStructReturn)
3331     // If this is a call to a struct-return function, the callee
3332     // pops the hidden struct pointer, so we have to push it back.
3333     // This is common for Darwin/X86, Linux & Mingw32 targets.
3334     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3335     NumBytesForCalleeToPop = 4;
3336   else
3337     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3338
3339   // Returns a flag for retval copy to use.
3340   if (!IsSibcall) {
3341     Chain = DAG.getCALLSEQ_END(Chain,
3342                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3343                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3344                                                      true),
3345                                InFlag, dl);
3346     InFlag = Chain.getValue(1);
3347   }
3348
3349   // Handle result values, copying them out of physregs into vregs that we
3350   // return.
3351   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3352                          Ins, dl, DAG, InVals);
3353 }
3354
3355 //===----------------------------------------------------------------------===//
3356 //                Fast Calling Convention (tail call) implementation
3357 //===----------------------------------------------------------------------===//
3358
3359 //  Like std call, callee cleans arguments, convention except that ECX is
3360 //  reserved for storing the tail called function address. Only 2 registers are
3361 //  free for argument passing (inreg). Tail call optimization is performed
3362 //  provided:
3363 //                * tailcallopt is enabled
3364 //                * caller/callee are fastcc
3365 //  On X86_64 architecture with GOT-style position independent code only local
3366 //  (within module) calls are supported at the moment.
3367 //  To keep the stack aligned according to platform abi the function
3368 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3369 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3370 //  If a tail called function callee has more arguments than the caller the
3371 //  caller needs to make sure that there is room to move the RETADDR to. This is
3372 //  achieved by reserving an area the size of the argument delta right after the
3373 //  original RETADDR, but before the saved framepointer or the spilled registers
3374 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3375 //  stack layout:
3376 //    arg1
3377 //    arg2
3378 //    RETADDR
3379 //    [ new RETADDR
3380 //      move area ]
3381 //    (possible EBP)
3382 //    ESI
3383 //    EDI
3384 //    local1 ..
3385
3386 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3387 /// for a 16 byte align requirement.
3388 unsigned
3389 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3390                                                SelectionDAG& DAG) const {
3391   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3392   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3393   unsigned StackAlignment = TFI.getStackAlignment();
3394   uint64_t AlignMask = StackAlignment - 1;
3395   int64_t Offset = StackSize;
3396   unsigned SlotSize = RegInfo->getSlotSize();
3397   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3398     // Number smaller than 12 so just add the difference.
3399     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3400   } else {
3401     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3402     Offset = ((~AlignMask) & Offset) + StackAlignment +
3403       (StackAlignment-SlotSize);
3404   }
3405   return Offset;
3406 }
3407
3408 /// MatchingStackOffset - Return true if the given stack call argument is
3409 /// already available in the same position (relatively) of the caller's
3410 /// incoming argument stack.
3411 static
3412 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3413                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3414                          const X86InstrInfo *TII) {
3415   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3416   int FI = INT_MAX;
3417   if (Arg.getOpcode() == ISD::CopyFromReg) {
3418     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3419     if (!TargetRegisterInfo::isVirtualRegister(VR))
3420       return false;
3421     MachineInstr *Def = MRI->getVRegDef(VR);
3422     if (!Def)
3423       return false;
3424     if (!Flags.isByVal()) {
3425       if (!TII->isLoadFromStackSlot(Def, FI))
3426         return false;
3427     } else {
3428       unsigned Opcode = Def->getOpcode();
3429       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3430            Opcode == X86::LEA64_32r) &&
3431           Def->getOperand(1).isFI()) {
3432         FI = Def->getOperand(1).getIndex();
3433         Bytes = Flags.getByValSize();
3434       } else
3435         return false;
3436     }
3437   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3438     if (Flags.isByVal())
3439       // ByVal argument is passed in as a pointer but it's now being
3440       // dereferenced. e.g.
3441       // define @foo(%struct.X* %A) {
3442       //   tail call @bar(%struct.X* byval %A)
3443       // }
3444       return false;
3445     SDValue Ptr = Ld->getBasePtr();
3446     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3447     if (!FINode)
3448       return false;
3449     FI = FINode->getIndex();
3450   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3451     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3452     FI = FINode->getIndex();
3453     Bytes = Flags.getByValSize();
3454   } else
3455     return false;
3456
3457   assert(FI != INT_MAX);
3458   if (!MFI->isFixedObjectIndex(FI))
3459     return false;
3460   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3461 }
3462
3463 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3464 /// for tail call optimization. Targets which want to do tail call
3465 /// optimization should implement this function.
3466 bool
3467 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3468                                                      CallingConv::ID CalleeCC,
3469                                                      bool isVarArg,
3470                                                      bool isCalleeStructRet,
3471                                                      bool isCallerStructRet,
3472                                                      Type *RetTy,
3473                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3474                                     const SmallVectorImpl<SDValue> &OutVals,
3475                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3476                                                      SelectionDAG &DAG) const {
3477   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3478     return false;
3479
3480   // If -tailcallopt is specified, make fastcc functions tail-callable.
3481   const MachineFunction &MF = DAG.getMachineFunction();
3482   const Function *CallerF = MF.getFunction();
3483
3484   // If the function return type is x86_fp80 and the callee return type is not,
3485   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3486   // perform a tailcall optimization here.
3487   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3488     return false;
3489
3490   CallingConv::ID CallerCC = CallerF->getCallingConv();
3491   bool CCMatch = CallerCC == CalleeCC;
3492   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3493   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3494
3495   // Win64 functions have extra shadow space for argument homing. Don't do the
3496   // sibcall if the caller and callee have mismatched expectations for this
3497   // space.
3498   if (IsCalleeWin64 != IsCallerWin64)
3499     return false;
3500
3501   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3502     if (IsTailCallConvention(CalleeCC) && CCMatch)
3503       return true;
3504     return false;
3505   }
3506
3507   // Look for obvious safe cases to perform tail call optimization that do not
3508   // require ABI changes. This is what gcc calls sibcall.
3509
3510   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3511   // emit a special epilogue.
3512   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3513   if (RegInfo->needsStackRealignment(MF))
3514     return false;
3515
3516   // Also avoid sibcall optimization if either caller or callee uses struct
3517   // return semantics.
3518   if (isCalleeStructRet || isCallerStructRet)
3519     return false;
3520
3521   // An stdcall/thiscall caller is expected to clean up its arguments; the
3522   // callee isn't going to do that.
3523   // FIXME: this is more restrictive than needed. We could produce a tailcall
3524   // when the stack adjustment matches. For example, with a thiscall that takes
3525   // only one argument.
3526   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3527                    CallerCC == CallingConv::X86_ThisCall))
3528     return false;
3529
3530   // Do not sibcall optimize vararg calls unless all arguments are passed via
3531   // registers.
3532   if (isVarArg && !Outs.empty()) {
3533
3534     // Optimizing for varargs on Win64 is unlikely to be safe without
3535     // additional testing.
3536     if (IsCalleeWin64 || IsCallerWin64)
3537       return false;
3538
3539     SmallVector<CCValAssign, 16> ArgLocs;
3540     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3541                    *DAG.getContext());
3542
3543     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3544     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3545       if (!ArgLocs[i].isRegLoc())
3546         return false;
3547   }
3548
3549   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3550   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3551   // this into a sibcall.
3552   bool Unused = false;
3553   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3554     if (!Ins[i].Used) {
3555       Unused = true;
3556       break;
3557     }
3558   }
3559   if (Unused) {
3560     SmallVector<CCValAssign, 16> RVLocs;
3561     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3562                    *DAG.getContext());
3563     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3564     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3565       CCValAssign &VA = RVLocs[i];
3566       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3567         return false;
3568     }
3569   }
3570
3571   // If the calling conventions do not match, then we'd better make sure the
3572   // results are returned in the same way as what the caller expects.
3573   if (!CCMatch) {
3574     SmallVector<CCValAssign, 16> RVLocs1;
3575     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3576                     *DAG.getContext());
3577     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3578
3579     SmallVector<CCValAssign, 16> RVLocs2;
3580     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3581                     *DAG.getContext());
3582     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3583
3584     if (RVLocs1.size() != RVLocs2.size())
3585       return false;
3586     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3587       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3588         return false;
3589       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3590         return false;
3591       if (RVLocs1[i].isRegLoc()) {
3592         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3593           return false;
3594       } else {
3595         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3596           return false;
3597       }
3598     }
3599   }
3600
3601   // If the callee takes no arguments then go on to check the results of the
3602   // call.
3603   if (!Outs.empty()) {
3604     // Check if stack adjustment is needed. For now, do not do this if any
3605     // argument is passed on the stack.
3606     SmallVector<CCValAssign, 16> ArgLocs;
3607     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3608                    *DAG.getContext());
3609
3610     // Allocate shadow area for Win64
3611     if (IsCalleeWin64)
3612       CCInfo.AllocateStack(32, 8);
3613
3614     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3615     if (CCInfo.getNextStackOffset()) {
3616       MachineFunction &MF = DAG.getMachineFunction();
3617       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3618         return false;
3619
3620       // Check if the arguments are already laid out in the right way as
3621       // the caller's fixed stack objects.
3622       MachineFrameInfo *MFI = MF.getFrameInfo();
3623       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3624       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3625       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3626         CCValAssign &VA = ArgLocs[i];
3627         SDValue Arg = OutVals[i];
3628         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3629         if (VA.getLocInfo() == CCValAssign::Indirect)
3630           return false;
3631         if (!VA.isRegLoc()) {
3632           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3633                                    MFI, MRI, TII))
3634             return false;
3635         }
3636       }
3637     }
3638
3639     // If the tailcall address may be in a register, then make sure it's
3640     // possible to register allocate for it. In 32-bit, the call address can
3641     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3642     // callee-saved registers are restored. These happen to be the same
3643     // registers used to pass 'inreg' arguments so watch out for those.
3644     if (!Subtarget->is64Bit() &&
3645         ((!isa<GlobalAddressSDNode>(Callee) &&
3646           !isa<ExternalSymbolSDNode>(Callee)) ||
3647          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3648       unsigned NumInRegs = 0;
3649       // In PIC we need an extra register to formulate the address computation
3650       // for the callee.
3651       unsigned MaxInRegs =
3652         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3653
3654       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3655         CCValAssign &VA = ArgLocs[i];
3656         if (!VA.isRegLoc())
3657           continue;
3658         unsigned Reg = VA.getLocReg();
3659         switch (Reg) {
3660         default: break;
3661         case X86::EAX: case X86::EDX: case X86::ECX:
3662           if (++NumInRegs == MaxInRegs)
3663             return false;
3664           break;
3665         }
3666       }
3667     }
3668   }
3669
3670   return true;
3671 }
3672
3673 FastISel *
3674 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3675                                   const TargetLibraryInfo *libInfo) const {
3676   return X86::createFastISel(funcInfo, libInfo);
3677 }
3678
3679 //===----------------------------------------------------------------------===//
3680 //                           Other Lowering Hooks
3681 //===----------------------------------------------------------------------===//
3682
3683 static bool MayFoldLoad(SDValue Op) {
3684   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3685 }
3686
3687 static bool MayFoldIntoStore(SDValue Op) {
3688   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3689 }
3690
3691 static bool isTargetShuffle(unsigned Opcode) {
3692   switch(Opcode) {
3693   default: return false;
3694   case X86ISD::BLENDI:
3695   case X86ISD::PSHUFB:
3696   case X86ISD::PSHUFD:
3697   case X86ISD::PSHUFHW:
3698   case X86ISD::PSHUFLW:
3699   case X86ISD::SHUFP:
3700   case X86ISD::PALIGNR:
3701   case X86ISD::MOVLHPS:
3702   case X86ISD::MOVLHPD:
3703   case X86ISD::MOVHLPS:
3704   case X86ISD::MOVLPS:
3705   case X86ISD::MOVLPD:
3706   case X86ISD::MOVSHDUP:
3707   case X86ISD::MOVSLDUP:
3708   case X86ISD::MOVDDUP:
3709   case X86ISD::MOVSS:
3710   case X86ISD::MOVSD:
3711   case X86ISD::UNPCKL:
3712   case X86ISD::UNPCKH:
3713   case X86ISD::VPERMILPI:
3714   case X86ISD::VPERM2X128:
3715   case X86ISD::VPERMI:
3716     return true;
3717   }
3718 }
3719
3720 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3721                                     SDValue V1, unsigned TargetMask,
3722                                     SelectionDAG &DAG) {
3723   switch(Opc) {
3724   default: llvm_unreachable("Unknown x86 shuffle node");
3725   case X86ISD::PSHUFD:
3726   case X86ISD::PSHUFHW:
3727   case X86ISD::PSHUFLW:
3728   case X86ISD::VPERMILPI:
3729   case X86ISD::VPERMI:
3730     return DAG.getNode(Opc, dl, VT, V1,
3731                        DAG.getConstant(TargetMask, dl, MVT::i8));
3732   }
3733 }
3734
3735 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3736                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3737   switch(Opc) {
3738   default: llvm_unreachable("Unknown x86 shuffle node");
3739   case X86ISD::MOVLHPS:
3740   case X86ISD::MOVLHPD:
3741   case X86ISD::MOVHLPS:
3742   case X86ISD::MOVLPS:
3743   case X86ISD::MOVLPD:
3744   case X86ISD::MOVSS:
3745   case X86ISD::MOVSD:
3746   case X86ISD::UNPCKL:
3747   case X86ISD::UNPCKH:
3748     return DAG.getNode(Opc, dl, VT, V1, V2);
3749   }
3750 }
3751
3752 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3753   MachineFunction &MF = DAG.getMachineFunction();
3754   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3755   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3756   int ReturnAddrIndex = FuncInfo->getRAIndex();
3757
3758   if (ReturnAddrIndex == 0) {
3759     // Set up a frame object for the return address.
3760     unsigned SlotSize = RegInfo->getSlotSize();
3761     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3762                                                            -(int64_t)SlotSize,
3763                                                            false);
3764     FuncInfo->setRAIndex(ReturnAddrIndex);
3765   }
3766
3767   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3768 }
3769
3770 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3771                                        bool hasSymbolicDisplacement) {
3772   // Offset should fit into 32 bit immediate field.
3773   if (!isInt<32>(Offset))
3774     return false;
3775
3776   // If we don't have a symbolic displacement - we don't have any extra
3777   // restrictions.
3778   if (!hasSymbolicDisplacement)
3779     return true;
3780
3781   // FIXME: Some tweaks might be needed for medium code model.
3782   if (M != CodeModel::Small && M != CodeModel::Kernel)
3783     return false;
3784
3785   // For small code model we assume that latest object is 16MB before end of 31
3786   // bits boundary. We may also accept pretty large negative constants knowing
3787   // that all objects are in the positive half of address space.
3788   if (M == CodeModel::Small && Offset < 16*1024*1024)
3789     return true;
3790
3791   // For kernel code model we know that all object resist in the negative half
3792   // of 32bits address space. We may not accept negative offsets, since they may
3793   // be just off and we may accept pretty large positive ones.
3794   if (M == CodeModel::Kernel && Offset >= 0)
3795     return true;
3796
3797   return false;
3798 }
3799
3800 /// isCalleePop - Determines whether the callee is required to pop its
3801 /// own arguments. Callee pop is necessary to support tail calls.
3802 bool X86::isCalleePop(CallingConv::ID CallingConv,
3803                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3804   switch (CallingConv) {
3805   default:
3806     return false;
3807   case CallingConv::X86_StdCall:
3808   case CallingConv::X86_FastCall:
3809   case CallingConv::X86_ThisCall:
3810     return !is64Bit;
3811   case CallingConv::Fast:
3812   case CallingConv::GHC:
3813   case CallingConv::HiPE:
3814     if (IsVarArg)
3815       return false;
3816     return TailCallOpt;
3817   }
3818 }
3819
3820 /// \brief Return true if the condition is an unsigned comparison operation.
3821 static bool isX86CCUnsigned(unsigned X86CC) {
3822   switch (X86CC) {
3823   default: llvm_unreachable("Invalid integer condition!");
3824   case X86::COND_E:     return true;
3825   case X86::COND_G:     return false;
3826   case X86::COND_GE:    return false;
3827   case X86::COND_L:     return false;
3828   case X86::COND_LE:    return false;
3829   case X86::COND_NE:    return true;
3830   case X86::COND_B:     return true;
3831   case X86::COND_A:     return true;
3832   case X86::COND_BE:    return true;
3833   case X86::COND_AE:    return true;
3834   }
3835   llvm_unreachable("covered switch fell through?!");
3836 }
3837
3838 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3839 /// specific condition code, returning the condition code and the LHS/RHS of the
3840 /// comparison to make.
3841 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3842                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3843   if (!isFP) {
3844     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3845       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3846         // X > -1   -> X == 0, jump !sign.
3847         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3848         return X86::COND_NS;
3849       }
3850       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3851         // X < 0   -> X == 0, jump on sign.
3852         return X86::COND_S;
3853       }
3854       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3855         // X < 1   -> X <= 0
3856         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3857         return X86::COND_LE;
3858       }
3859     }
3860
3861     switch (SetCCOpcode) {
3862     default: llvm_unreachable("Invalid integer condition!");
3863     case ISD::SETEQ:  return X86::COND_E;
3864     case ISD::SETGT:  return X86::COND_G;
3865     case ISD::SETGE:  return X86::COND_GE;
3866     case ISD::SETLT:  return X86::COND_L;
3867     case ISD::SETLE:  return X86::COND_LE;
3868     case ISD::SETNE:  return X86::COND_NE;
3869     case ISD::SETULT: return X86::COND_B;
3870     case ISD::SETUGT: return X86::COND_A;
3871     case ISD::SETULE: return X86::COND_BE;
3872     case ISD::SETUGE: return X86::COND_AE;
3873     }
3874   }
3875
3876   // First determine if it is required or is profitable to flip the operands.
3877
3878   // If LHS is a foldable load, but RHS is not, flip the condition.
3879   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3880       !ISD::isNON_EXTLoad(RHS.getNode())) {
3881     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3882     std::swap(LHS, RHS);
3883   }
3884
3885   switch (SetCCOpcode) {
3886   default: break;
3887   case ISD::SETOLT:
3888   case ISD::SETOLE:
3889   case ISD::SETUGT:
3890   case ISD::SETUGE:
3891     std::swap(LHS, RHS);
3892     break;
3893   }
3894
3895   // On a floating point condition, the flags are set as follows:
3896   // ZF  PF  CF   op
3897   //  0 | 0 | 0 | X > Y
3898   //  0 | 0 | 1 | X < Y
3899   //  1 | 0 | 0 | X == Y
3900   //  1 | 1 | 1 | unordered
3901   switch (SetCCOpcode) {
3902   default: llvm_unreachable("Condcode should be pre-legalized away");
3903   case ISD::SETUEQ:
3904   case ISD::SETEQ:   return X86::COND_E;
3905   case ISD::SETOLT:              // flipped
3906   case ISD::SETOGT:
3907   case ISD::SETGT:   return X86::COND_A;
3908   case ISD::SETOLE:              // flipped
3909   case ISD::SETOGE:
3910   case ISD::SETGE:   return X86::COND_AE;
3911   case ISD::SETUGT:              // flipped
3912   case ISD::SETULT:
3913   case ISD::SETLT:   return X86::COND_B;
3914   case ISD::SETUGE:              // flipped
3915   case ISD::SETULE:
3916   case ISD::SETLE:   return X86::COND_BE;
3917   case ISD::SETONE:
3918   case ISD::SETNE:   return X86::COND_NE;
3919   case ISD::SETUO:   return X86::COND_P;
3920   case ISD::SETO:    return X86::COND_NP;
3921   case ISD::SETOEQ:
3922   case ISD::SETUNE:  return X86::COND_INVALID;
3923   }
3924 }
3925
3926 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3927 /// code. Current x86 isa includes the following FP cmov instructions:
3928 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3929 static bool hasFPCMov(unsigned X86CC) {
3930   switch (X86CC) {
3931   default:
3932     return false;
3933   case X86::COND_B:
3934   case X86::COND_BE:
3935   case X86::COND_E:
3936   case X86::COND_P:
3937   case X86::COND_A:
3938   case X86::COND_AE:
3939   case X86::COND_NE:
3940   case X86::COND_NP:
3941     return true;
3942   }
3943 }
3944
3945 /// isFPImmLegal - Returns true if the target can instruction select the
3946 /// specified FP immediate natively. If false, the legalizer will
3947 /// materialize the FP immediate as a load from a constant pool.
3948 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3949   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3950     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3951       return true;
3952   }
3953   return false;
3954 }
3955
3956 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3957                                               ISD::LoadExtType ExtTy,
3958                                               EVT NewVT) const {
3959   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3960   // relocation target a movq or addq instruction: don't let the load shrink.
3961   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3962   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3963     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3964       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3965   return true;
3966 }
3967
3968 /// \brief Returns true if it is beneficial to convert a load of a constant
3969 /// to just the constant itself.
3970 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3971                                                           Type *Ty) const {
3972   assert(Ty->isIntegerTy());
3973
3974   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3975   if (BitSize == 0 || BitSize > 64)
3976     return false;
3977   return true;
3978 }
3979
3980 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3981                                                 unsigned Index) const {
3982   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3983     return false;
3984
3985   return (Index == 0 || Index == ResVT.getVectorNumElements());
3986 }
3987
3988 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3989   // Speculate cttz only if we can directly use TZCNT.
3990   return Subtarget->hasBMI();
3991 }
3992
3993 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3994   // Speculate ctlz only if we can directly use LZCNT.
3995   return Subtarget->hasLZCNT();
3996 }
3997
3998 /// isUndefInRange - Return true if every element in Mask, beginning
3999 /// from position Pos and ending in Pos+Size is undef.
4000 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
4001   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
4002     if (0 <= Mask[i])
4003       return false;
4004   return true;
4005 }
4006
4007 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
4008 /// the specified range (L, H].
4009 static bool isUndefOrInRange(int Val, int Low, int Hi) {
4010   return (Val < 0) || (Val >= Low && Val < Hi);
4011 }
4012
4013 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
4014 /// specified value.
4015 static bool isUndefOrEqual(int Val, int CmpVal) {
4016   return (Val < 0 || Val == CmpVal);
4017 }
4018
4019 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
4020 /// from position Pos and ending in Pos+Size, falls within the specified
4021 /// sequential range (Low, Low+Size]. or is undef.
4022 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
4023                                        unsigned Pos, unsigned Size, int Low) {
4024   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4025     if (!isUndefOrEqual(Mask[i], Low))
4026       return false;
4027   return true;
4028 }
4029
4030 /// isVEXTRACTIndex - Return true if the specified
4031 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4032 /// suitable for instruction that extract 128 or 256 bit vectors
4033 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4034   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4035   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4036     return false;
4037
4038   // The index should be aligned on a vecWidth-bit boundary.
4039   uint64_t Index =
4040     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4041
4042   MVT VT = N->getSimpleValueType(0);
4043   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4044   bool Result = (Index * ElSize) % vecWidth == 0;
4045
4046   return Result;
4047 }
4048
4049 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4050 /// operand specifies a subvector insert that is suitable for input to
4051 /// insertion of 128 or 256-bit subvectors
4052 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4053   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4054   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4055     return false;
4056   // The index should be aligned on a vecWidth-bit boundary.
4057   uint64_t Index =
4058     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4059
4060   MVT VT = N->getSimpleValueType(0);
4061   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4062   bool Result = (Index * ElSize) % vecWidth == 0;
4063
4064   return Result;
4065 }
4066
4067 bool X86::isVINSERT128Index(SDNode *N) {
4068   return isVINSERTIndex(N, 128);
4069 }
4070
4071 bool X86::isVINSERT256Index(SDNode *N) {
4072   return isVINSERTIndex(N, 256);
4073 }
4074
4075 bool X86::isVEXTRACT128Index(SDNode *N) {
4076   return isVEXTRACTIndex(N, 128);
4077 }
4078
4079 bool X86::isVEXTRACT256Index(SDNode *N) {
4080   return isVEXTRACTIndex(N, 256);
4081 }
4082
4083 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4084   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4085   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4086     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4087
4088   uint64_t Index =
4089     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4090
4091   MVT VecVT = N->getOperand(0).getSimpleValueType();
4092   MVT ElVT = VecVT.getVectorElementType();
4093
4094   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4095   return Index / NumElemsPerChunk;
4096 }
4097
4098 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4099   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4100   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4101     llvm_unreachable("Illegal insert subvector for VINSERT");
4102
4103   uint64_t Index =
4104     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4105
4106   MVT VecVT = N->getSimpleValueType(0);
4107   MVT ElVT = VecVT.getVectorElementType();
4108
4109   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4110   return Index / NumElemsPerChunk;
4111 }
4112
4113 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4114 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4115 /// and VINSERTI128 instructions.
4116 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4117   return getExtractVEXTRACTImmediate(N, 128);
4118 }
4119
4120 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4121 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4122 /// and VINSERTI64x4 instructions.
4123 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4124   return getExtractVEXTRACTImmediate(N, 256);
4125 }
4126
4127 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4128 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4129 /// and VINSERTI128 instructions.
4130 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4131   return getInsertVINSERTImmediate(N, 128);
4132 }
4133
4134 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4135 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4136 /// and VINSERTI64x4 instructions.
4137 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4138   return getInsertVINSERTImmediate(N, 256);
4139 }
4140
4141 /// isZero - Returns true if Elt is a constant integer zero
4142 static bool isZero(SDValue V) {
4143   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4144   return C && C->isNullValue();
4145 }
4146
4147 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4148 /// constant +0.0.
4149 bool X86::isZeroNode(SDValue Elt) {
4150   if (isZero(Elt))
4151     return true;
4152   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4153     return CFP->getValueAPF().isPosZero();
4154   return false;
4155 }
4156
4157 /// getZeroVector - Returns a vector of specified type with all zero elements.
4158 ///
4159 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4160                              SelectionDAG &DAG, SDLoc dl) {
4161   assert(VT.isVector() && "Expected a vector type");
4162
4163   // Always build SSE zero vectors as <4 x i32> bitcasted
4164   // to their dest type. This ensures they get CSE'd.
4165   SDValue Vec;
4166   if (VT.is128BitVector()) {  // SSE
4167     if (Subtarget->hasSSE2()) {  // SSE2
4168       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4169       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4170     } else { // SSE1
4171       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4172       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4173     }
4174   } else if (VT.is256BitVector()) { // AVX
4175     if (Subtarget->hasInt256()) { // AVX2
4176       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4177       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4178       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4179     } else {
4180       // 256-bit logic and arithmetic instructions in AVX are all
4181       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4182       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4183       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4184       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4185     }
4186   } else if (VT.is512BitVector()) { // AVX-512
4187       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4188       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4189                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4190       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4191   } else if (VT.getScalarType() == MVT::i1) {
4192
4193     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4194             && "Unexpected vector type");
4195     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4196             && "Unexpected vector type");
4197     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4198     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4199     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4200   } else
4201     llvm_unreachable("Unexpected vector type");
4202
4203   return DAG.getBitcast(VT, Vec);
4204 }
4205
4206 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4207                                 SelectionDAG &DAG, SDLoc dl,
4208                                 unsigned vectorWidth) {
4209   assert((vectorWidth == 128 || vectorWidth == 256) &&
4210          "Unsupported vector width");
4211   EVT VT = Vec.getValueType();
4212   EVT ElVT = VT.getVectorElementType();
4213   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4214   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4215                                   VT.getVectorNumElements()/Factor);
4216
4217   // Extract from UNDEF is UNDEF.
4218   if (Vec.getOpcode() == ISD::UNDEF)
4219     return DAG.getUNDEF(ResultVT);
4220
4221   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4222   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4223
4224   // This is the index of the first element of the vectorWidth-bit chunk
4225   // we want.
4226   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4227                                * ElemsPerChunk);
4228
4229   // If the input is a buildvector just emit a smaller one.
4230   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4231     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4232                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4233                                     ElemsPerChunk));
4234
4235   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4236   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4237 }
4238
4239 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4240 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4241 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4242 /// instructions or a simple subregister reference. Idx is an index in the
4243 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4244 /// lowering EXTRACT_VECTOR_ELT operations easier.
4245 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4246                                    SelectionDAG &DAG, SDLoc dl) {
4247   assert((Vec.getValueType().is256BitVector() ||
4248           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4249   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4250 }
4251
4252 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4253 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4254                                    SelectionDAG &DAG, SDLoc dl) {
4255   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4256   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4257 }
4258
4259 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4260                                unsigned IdxVal, SelectionDAG &DAG,
4261                                SDLoc dl, unsigned vectorWidth) {
4262   assert((vectorWidth == 128 || vectorWidth == 256) &&
4263          "Unsupported vector width");
4264   // Inserting UNDEF is Result
4265   if (Vec.getOpcode() == ISD::UNDEF)
4266     return Result;
4267   EVT VT = Vec.getValueType();
4268   EVT ElVT = VT.getVectorElementType();
4269   EVT ResultVT = Result.getValueType();
4270
4271   // Insert the relevant vectorWidth bits.
4272   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4273
4274   // This is the index of the first element of the vectorWidth-bit chunk
4275   // we want.
4276   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4277                                * ElemsPerChunk);
4278
4279   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4280   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4281 }
4282
4283 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4284 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4285 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4286 /// simple superregister reference.  Idx is an index in the 128 bits
4287 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4288 /// lowering INSERT_VECTOR_ELT operations easier.
4289 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4290                                   SelectionDAG &DAG, SDLoc dl) {
4291   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4292
4293   // For insertion into the zero index (low half) of a 256-bit vector, it is
4294   // more efficient to generate a blend with immediate instead of an insert*128.
4295   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4296   // extend the subvector to the size of the result vector. Make sure that
4297   // we are not recursing on that node by checking for undef here.
4298   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4299       Result.getOpcode() != ISD::UNDEF) {
4300     EVT ResultVT = Result.getValueType();
4301     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4302     SDValue Undef = DAG.getUNDEF(ResultVT);
4303     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4304                                  Vec, ZeroIndex);
4305
4306     // The blend instruction, and therefore its mask, depend on the data type.
4307     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4308     if (ScalarType.isFloatingPoint()) {
4309       // Choose either vblendps (float) or vblendpd (double).
4310       unsigned ScalarSize = ScalarType.getSizeInBits();
4311       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4312       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4313       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4314       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4315     }
4316
4317     const X86Subtarget &Subtarget =
4318     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4319
4320     // AVX2 is needed for 256-bit integer blend support.
4321     // Integers must be cast to 32-bit because there is only vpblendd;
4322     // vpblendw can't be used for this because it has a handicapped mask.
4323
4324     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4325     // is still more efficient than using the wrong domain vinsertf128 that
4326     // will be created by InsertSubVector().
4327     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4328
4329     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4330     Vec256 = DAG.getBitcast(CastVT, Vec256);
4331     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4332     return DAG.getBitcast(ResultVT, Vec256);
4333   }
4334
4335   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4336 }
4337
4338 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4339                                   SelectionDAG &DAG, SDLoc dl) {
4340   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4341   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4342 }
4343
4344 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4345 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4346 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4347 /// large BUILD_VECTORS.
4348 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4349                                    unsigned NumElems, SelectionDAG &DAG,
4350                                    SDLoc dl) {
4351   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4352   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4353 }
4354
4355 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4356                                    unsigned NumElems, SelectionDAG &DAG,
4357                                    SDLoc dl) {
4358   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4359   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4360 }
4361
4362 /// getOnesVector - Returns a vector of specified type with all bits set.
4363 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4364 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4365 /// Then bitcast to their original type, ensuring they get CSE'd.
4366 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4367                              SDLoc dl) {
4368   assert(VT.isVector() && "Expected a vector type");
4369
4370   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4371   SDValue Vec;
4372   if (VT.is256BitVector()) {
4373     if (HasInt256) { // AVX2
4374       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4375       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4376     } else { // AVX
4377       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4378       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4379     }
4380   } else if (VT.is128BitVector()) {
4381     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4382   } else
4383     llvm_unreachable("Unexpected vector type");
4384
4385   return DAG.getBitcast(VT, Vec);
4386 }
4387
4388 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4389 /// operation of specified width.
4390 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4391                        SDValue V2) {
4392   unsigned NumElems = VT.getVectorNumElements();
4393   SmallVector<int, 8> Mask;
4394   Mask.push_back(NumElems);
4395   for (unsigned i = 1; i != NumElems; ++i)
4396     Mask.push_back(i);
4397   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4398 }
4399
4400 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4401 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4402                           SDValue V2) {
4403   unsigned NumElems = VT.getVectorNumElements();
4404   SmallVector<int, 8> Mask;
4405   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4406     Mask.push_back(i);
4407     Mask.push_back(i + NumElems);
4408   }
4409   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4410 }
4411
4412 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4413 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4414                           SDValue V2) {
4415   unsigned NumElems = VT.getVectorNumElements();
4416   SmallVector<int, 8> Mask;
4417   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4418     Mask.push_back(i + Half);
4419     Mask.push_back(i + NumElems + Half);
4420   }
4421   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4422 }
4423
4424 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4425 /// vector of zero or undef vector.  This produces a shuffle where the low
4426 /// element of V2 is swizzled into the zero/undef vector, landing at element
4427 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4428 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4429                                            bool IsZero,
4430                                            const X86Subtarget *Subtarget,
4431                                            SelectionDAG &DAG) {
4432   MVT VT = V2.getSimpleValueType();
4433   SDValue V1 = IsZero
4434     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4435   unsigned NumElems = VT.getVectorNumElements();
4436   SmallVector<int, 16> MaskVec;
4437   for (unsigned i = 0; i != NumElems; ++i)
4438     // If this is the insertion idx, put the low elt of V2 here.
4439     MaskVec.push_back(i == Idx ? NumElems : i);
4440   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4441 }
4442
4443 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4444 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4445 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4446 /// shuffles which use a single input multiple times, and in those cases it will
4447 /// adjust the mask to only have indices within that single input.
4448 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4449 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4450                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4451   unsigned NumElems = VT.getVectorNumElements();
4452   SDValue ImmN;
4453
4454   IsUnary = false;
4455   bool IsFakeUnary = false;
4456   switch(N->getOpcode()) {
4457   case X86ISD::BLENDI:
4458     ImmN = N->getOperand(N->getNumOperands()-1);
4459     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4460     break;
4461   case X86ISD::SHUFP:
4462     ImmN = N->getOperand(N->getNumOperands()-1);
4463     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4464     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4465     break;
4466   case X86ISD::UNPCKH:
4467     DecodeUNPCKHMask(VT, Mask);
4468     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4469     break;
4470   case X86ISD::UNPCKL:
4471     DecodeUNPCKLMask(VT, Mask);
4472     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4473     break;
4474   case X86ISD::MOVHLPS:
4475     DecodeMOVHLPSMask(NumElems, Mask);
4476     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4477     break;
4478   case X86ISD::MOVLHPS:
4479     DecodeMOVLHPSMask(NumElems, Mask);
4480     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4481     break;
4482   case X86ISD::PALIGNR:
4483     ImmN = N->getOperand(N->getNumOperands()-1);
4484     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4485     break;
4486   case X86ISD::PSHUFD:
4487   case X86ISD::VPERMILPI:
4488     ImmN = N->getOperand(N->getNumOperands()-1);
4489     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4490     IsUnary = true;
4491     break;
4492   case X86ISD::PSHUFHW:
4493     ImmN = N->getOperand(N->getNumOperands()-1);
4494     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4495     IsUnary = true;
4496     break;
4497   case X86ISD::PSHUFLW:
4498     ImmN = N->getOperand(N->getNumOperands()-1);
4499     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4500     IsUnary = true;
4501     break;
4502   case X86ISD::PSHUFB: {
4503     IsUnary = true;
4504     SDValue MaskNode = N->getOperand(1);
4505     while (MaskNode->getOpcode() == ISD::BITCAST)
4506       MaskNode = MaskNode->getOperand(0);
4507
4508     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4509       // If we have a build-vector, then things are easy.
4510       EVT VT = MaskNode.getValueType();
4511       assert(VT.isVector() &&
4512              "Can't produce a non-vector with a build_vector!");
4513       if (!VT.isInteger())
4514         return false;
4515
4516       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4517
4518       SmallVector<uint64_t, 32> RawMask;
4519       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4520         SDValue Op = MaskNode->getOperand(i);
4521         if (Op->getOpcode() == ISD::UNDEF) {
4522           RawMask.push_back((uint64_t)SM_SentinelUndef);
4523           continue;
4524         }
4525         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4526         if (!CN)
4527           return false;
4528         APInt MaskElement = CN->getAPIntValue();
4529
4530         // We now have to decode the element which could be any integer size and
4531         // extract each byte of it.
4532         for (int j = 0; j < NumBytesPerElement; ++j) {
4533           // Note that this is x86 and so always little endian: the low byte is
4534           // the first byte of the mask.
4535           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4536           MaskElement = MaskElement.lshr(8);
4537         }
4538       }
4539       DecodePSHUFBMask(RawMask, Mask);
4540       break;
4541     }
4542
4543     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4544     if (!MaskLoad)
4545       return false;
4546
4547     SDValue Ptr = MaskLoad->getBasePtr();
4548     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4549         Ptr->getOpcode() == X86ISD::WrapperRIP)
4550       Ptr = Ptr->getOperand(0);
4551
4552     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4553     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4554       return false;
4555
4556     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4557       DecodePSHUFBMask(C, Mask);
4558       if (Mask.empty())
4559         return false;
4560       break;
4561     }
4562
4563     return false;
4564   }
4565   case X86ISD::VPERMI:
4566     ImmN = N->getOperand(N->getNumOperands()-1);
4567     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4568     IsUnary = true;
4569     break;
4570   case X86ISD::MOVSS:
4571   case X86ISD::MOVSD:
4572     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4573     break;
4574   case X86ISD::VPERM2X128:
4575     ImmN = N->getOperand(N->getNumOperands()-1);
4576     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4577     if (Mask.empty()) return false;
4578     // Mask only contains negative index if an element is zero.
4579     if (std::any_of(Mask.begin(), Mask.end(),
4580                     [](int M){ return M == SM_SentinelZero; }))
4581       return false;
4582     break;
4583   case X86ISD::MOVSLDUP:
4584     DecodeMOVSLDUPMask(VT, Mask);
4585     IsUnary = true;
4586     break;
4587   case X86ISD::MOVSHDUP:
4588     DecodeMOVSHDUPMask(VT, Mask);
4589     IsUnary = true;
4590     break;
4591   case X86ISD::MOVDDUP:
4592     DecodeMOVDDUPMask(VT, Mask);
4593     IsUnary = true;
4594     break;
4595   case X86ISD::MOVLHPD:
4596   case X86ISD::MOVLPD:
4597   case X86ISD::MOVLPS:
4598     // Not yet implemented
4599     return false;
4600   default: llvm_unreachable("unknown target shuffle node");
4601   }
4602
4603   // If we have a fake unary shuffle, the shuffle mask is spread across two
4604   // inputs that are actually the same node. Re-map the mask to always point
4605   // into the first input.
4606   if (IsFakeUnary)
4607     for (int &M : Mask)
4608       if (M >= (int)Mask.size())
4609         M -= Mask.size();
4610
4611   return true;
4612 }
4613
4614 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4615 /// element of the result of the vector shuffle.
4616 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4617                                    unsigned Depth) {
4618   if (Depth == 6)
4619     return SDValue();  // Limit search depth.
4620
4621   SDValue V = SDValue(N, 0);
4622   EVT VT = V.getValueType();
4623   unsigned Opcode = V.getOpcode();
4624
4625   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4626   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4627     int Elt = SV->getMaskElt(Index);
4628
4629     if (Elt < 0)
4630       return DAG.getUNDEF(VT.getVectorElementType());
4631
4632     unsigned NumElems = VT.getVectorNumElements();
4633     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4634                                          : SV->getOperand(1);
4635     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4636   }
4637
4638   // Recurse into target specific vector shuffles to find scalars.
4639   if (isTargetShuffle(Opcode)) {
4640     MVT ShufVT = V.getSimpleValueType();
4641     unsigned NumElems = ShufVT.getVectorNumElements();
4642     SmallVector<int, 16> ShuffleMask;
4643     bool IsUnary;
4644
4645     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4646       return SDValue();
4647
4648     int Elt = ShuffleMask[Index];
4649     if (Elt < 0)
4650       return DAG.getUNDEF(ShufVT.getVectorElementType());
4651
4652     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4653                                          : N->getOperand(1);
4654     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4655                                Depth+1);
4656   }
4657
4658   // Actual nodes that may contain scalar elements
4659   if (Opcode == ISD::BITCAST) {
4660     V = V.getOperand(0);
4661     EVT SrcVT = V.getValueType();
4662     unsigned NumElems = VT.getVectorNumElements();
4663
4664     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4665       return SDValue();
4666   }
4667
4668   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4669     return (Index == 0) ? V.getOperand(0)
4670                         : DAG.getUNDEF(VT.getVectorElementType());
4671
4672   if (V.getOpcode() == ISD::BUILD_VECTOR)
4673     return V.getOperand(Index);
4674
4675   return SDValue();
4676 }
4677
4678 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4679 ///
4680 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4681                                        unsigned NumNonZero, unsigned NumZero,
4682                                        SelectionDAG &DAG,
4683                                        const X86Subtarget* Subtarget,
4684                                        const TargetLowering &TLI) {
4685   if (NumNonZero > 8)
4686     return SDValue();
4687
4688   SDLoc dl(Op);
4689   SDValue V;
4690   bool First = true;
4691
4692   // SSE4.1 - use PINSRB to insert each byte directly.
4693   if (Subtarget->hasSSE41()) {
4694     for (unsigned i = 0; i < 16; ++i) {
4695       bool isNonZero = (NonZeros & (1 << i)) != 0;
4696       if (isNonZero) {
4697         if (First) {
4698           if (NumZero)
4699             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4700           else
4701             V = DAG.getUNDEF(MVT::v16i8);
4702           First = false;
4703         }
4704         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4705                         MVT::v16i8, V, Op.getOperand(i),
4706                         DAG.getIntPtrConstant(i, dl));
4707       }
4708     }
4709
4710     return V;
4711   }
4712
4713   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4714   for (unsigned i = 0; i < 16; ++i) {
4715     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4716     if (ThisIsNonZero && First) {
4717       if (NumZero)
4718         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4719       else
4720         V = DAG.getUNDEF(MVT::v8i16);
4721       First = false;
4722     }
4723
4724     if ((i & 1) != 0) {
4725       SDValue ThisElt, LastElt;
4726       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4727       if (LastIsNonZero) {
4728         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4729                               MVT::i16, Op.getOperand(i-1));
4730       }
4731       if (ThisIsNonZero) {
4732         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4733         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4734                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4735         if (LastIsNonZero)
4736           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4737       } else
4738         ThisElt = LastElt;
4739
4740       if (ThisElt.getNode())
4741         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4742                         DAG.getIntPtrConstant(i/2, dl));
4743     }
4744   }
4745
4746   return DAG.getBitcast(MVT::v16i8, V);
4747 }
4748
4749 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4750 ///
4751 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4752                                      unsigned NumNonZero, unsigned NumZero,
4753                                      SelectionDAG &DAG,
4754                                      const X86Subtarget* Subtarget,
4755                                      const TargetLowering &TLI) {
4756   if (NumNonZero > 4)
4757     return SDValue();
4758
4759   SDLoc dl(Op);
4760   SDValue V;
4761   bool First = true;
4762   for (unsigned i = 0; i < 8; ++i) {
4763     bool isNonZero = (NonZeros & (1 << i)) != 0;
4764     if (isNonZero) {
4765       if (First) {
4766         if (NumZero)
4767           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4768         else
4769           V = DAG.getUNDEF(MVT::v8i16);
4770         First = false;
4771       }
4772       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4773                       MVT::v8i16, V, Op.getOperand(i),
4774                       DAG.getIntPtrConstant(i, dl));
4775     }
4776   }
4777
4778   return V;
4779 }
4780
4781 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4782 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4783                                      const X86Subtarget *Subtarget,
4784                                      const TargetLowering &TLI) {
4785   // Find all zeroable elements.
4786   std::bitset<4> Zeroable;
4787   for (int i=0; i < 4; ++i) {
4788     SDValue Elt = Op->getOperand(i);
4789     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4790   }
4791   assert(Zeroable.size() - Zeroable.count() > 1 &&
4792          "We expect at least two non-zero elements!");
4793
4794   // We only know how to deal with build_vector nodes where elements are either
4795   // zeroable or extract_vector_elt with constant index.
4796   SDValue FirstNonZero;
4797   unsigned FirstNonZeroIdx;
4798   for (unsigned i=0; i < 4; ++i) {
4799     if (Zeroable[i])
4800       continue;
4801     SDValue Elt = Op->getOperand(i);
4802     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4803         !isa<ConstantSDNode>(Elt.getOperand(1)))
4804       return SDValue();
4805     // Make sure that this node is extracting from a 128-bit vector.
4806     MVT VT = Elt.getOperand(0).getSimpleValueType();
4807     if (!VT.is128BitVector())
4808       return SDValue();
4809     if (!FirstNonZero.getNode()) {
4810       FirstNonZero = Elt;
4811       FirstNonZeroIdx = i;
4812     }
4813   }
4814
4815   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4816   SDValue V1 = FirstNonZero.getOperand(0);
4817   MVT VT = V1.getSimpleValueType();
4818
4819   // See if this build_vector can be lowered as a blend with zero.
4820   SDValue Elt;
4821   unsigned EltMaskIdx, EltIdx;
4822   int Mask[4];
4823   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4824     if (Zeroable[EltIdx]) {
4825       // The zero vector will be on the right hand side.
4826       Mask[EltIdx] = EltIdx+4;
4827       continue;
4828     }
4829
4830     Elt = Op->getOperand(EltIdx);
4831     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4832     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4833     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4834       break;
4835     Mask[EltIdx] = EltIdx;
4836   }
4837
4838   if (EltIdx == 4) {
4839     // Let the shuffle legalizer deal with blend operations.
4840     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4841     if (V1.getSimpleValueType() != VT)
4842       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4843     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4844   }
4845
4846   // See if we can lower this build_vector to a INSERTPS.
4847   if (!Subtarget->hasSSE41())
4848     return SDValue();
4849
4850   SDValue V2 = Elt.getOperand(0);
4851   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4852     V1 = SDValue();
4853
4854   bool CanFold = true;
4855   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4856     if (Zeroable[i])
4857       continue;
4858
4859     SDValue Current = Op->getOperand(i);
4860     SDValue SrcVector = Current->getOperand(0);
4861     if (!V1.getNode())
4862       V1 = SrcVector;
4863     CanFold = SrcVector == V1 &&
4864       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4865   }
4866
4867   if (!CanFold)
4868     return SDValue();
4869
4870   assert(V1.getNode() && "Expected at least two non-zero elements!");
4871   if (V1.getSimpleValueType() != MVT::v4f32)
4872     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4873   if (V2.getSimpleValueType() != MVT::v4f32)
4874     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4875
4876   // Ok, we can emit an INSERTPS instruction.
4877   unsigned ZMask = Zeroable.to_ulong();
4878
4879   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4880   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4881   SDLoc DL(Op);
4882   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4883                                DAG.getIntPtrConstant(InsertPSMask, DL));
4884   return DAG.getBitcast(VT, Result);
4885 }
4886
4887 /// Return a vector logical shift node.
4888 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4889                          unsigned NumBits, SelectionDAG &DAG,
4890                          const TargetLowering &TLI, SDLoc dl) {
4891   assert(VT.is128BitVector() && "Unknown type for VShift");
4892   MVT ShVT = MVT::v2i64;
4893   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4894   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4895   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4896   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4897   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4898   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4899 }
4900
4901 static SDValue
4902 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4903
4904   // Check if the scalar load can be widened into a vector load. And if
4905   // the address is "base + cst" see if the cst can be "absorbed" into
4906   // the shuffle mask.
4907   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4908     SDValue Ptr = LD->getBasePtr();
4909     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4910       return SDValue();
4911     EVT PVT = LD->getValueType(0);
4912     if (PVT != MVT::i32 && PVT != MVT::f32)
4913       return SDValue();
4914
4915     int FI = -1;
4916     int64_t Offset = 0;
4917     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4918       FI = FINode->getIndex();
4919       Offset = 0;
4920     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4921                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4922       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4923       Offset = Ptr.getConstantOperandVal(1);
4924       Ptr = Ptr.getOperand(0);
4925     } else {
4926       return SDValue();
4927     }
4928
4929     // FIXME: 256-bit vector instructions don't require a strict alignment,
4930     // improve this code to support it better.
4931     unsigned RequiredAlign = VT.getSizeInBits()/8;
4932     SDValue Chain = LD->getChain();
4933     // Make sure the stack object alignment is at least 16 or 32.
4934     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4935     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4936       if (MFI->isFixedObjectIndex(FI)) {
4937         // Can't change the alignment. FIXME: It's possible to compute
4938         // the exact stack offset and reference FI + adjust offset instead.
4939         // If someone *really* cares about this. That's the way to implement it.
4940         return SDValue();
4941       } else {
4942         MFI->setObjectAlignment(FI, RequiredAlign);
4943       }
4944     }
4945
4946     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4947     // Ptr + (Offset & ~15).
4948     if (Offset < 0)
4949       return SDValue();
4950     if ((Offset % RequiredAlign) & 3)
4951       return SDValue();
4952     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4953     if (StartOffset) {
4954       SDLoc DL(Ptr);
4955       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4956                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4957     }
4958
4959     int EltNo = (Offset - StartOffset) >> 2;
4960     unsigned NumElems = VT.getVectorNumElements();
4961
4962     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4963     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4964                              LD->getPointerInfo().getWithOffset(StartOffset),
4965                              false, false, false, 0);
4966
4967     SmallVector<int, 8> Mask(NumElems, EltNo);
4968
4969     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4970   }
4971
4972   return SDValue();
4973 }
4974
4975 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4976 /// elements can be replaced by a single large load which has the same value as
4977 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4978 ///
4979 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4980 ///
4981 /// FIXME: we'd also like to handle the case where the last elements are zero
4982 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4983 /// There's even a handy isZeroNode for that purpose.
4984 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4985                                         SDLoc &DL, SelectionDAG &DAG,
4986                                         bool isAfterLegalize) {
4987   unsigned NumElems = Elts.size();
4988
4989   LoadSDNode *LDBase = nullptr;
4990   unsigned LastLoadedElt = -1U;
4991
4992   // For each element in the initializer, see if we've found a load or an undef.
4993   // If we don't find an initial load element, or later load elements are
4994   // non-consecutive, bail out.
4995   for (unsigned i = 0; i < NumElems; ++i) {
4996     SDValue Elt = Elts[i];
4997     // Look through a bitcast.
4998     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4999       Elt = Elt.getOperand(0);
5000     if (!Elt.getNode() ||
5001         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
5002       return SDValue();
5003     if (!LDBase) {
5004       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
5005         return SDValue();
5006       LDBase = cast<LoadSDNode>(Elt.getNode());
5007       LastLoadedElt = i;
5008       continue;
5009     }
5010     if (Elt.getOpcode() == ISD::UNDEF)
5011       continue;
5012
5013     LoadSDNode *LD = cast<LoadSDNode>(Elt);
5014     EVT LdVT = Elt.getValueType();
5015     // Each loaded element must be the correct fractional portion of the
5016     // requested vector load.
5017     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
5018       return SDValue();
5019     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
5020       return SDValue();
5021     LastLoadedElt = i;
5022   }
5023
5024   // If we have found an entire vector of loads and undefs, then return a large
5025   // load of the entire vector width starting at the base pointer.  If we found
5026   // consecutive loads for the low half, generate a vzext_load node.
5027   if (LastLoadedElt == NumElems - 1) {
5028     assert(LDBase && "Did not find base load for merging consecutive loads");
5029     EVT EltVT = LDBase->getValueType(0);
5030     // Ensure that the input vector size for the merged loads matches the
5031     // cumulative size of the input elements.
5032     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5033       return SDValue();
5034
5035     if (isAfterLegalize &&
5036         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5037       return SDValue();
5038
5039     SDValue NewLd = SDValue();
5040
5041     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5042                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5043                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5044                         LDBase->getAlignment());
5045
5046     if (LDBase->hasAnyUseOfValue(1)) {
5047       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5048                                      SDValue(LDBase, 1),
5049                                      SDValue(NewLd.getNode(), 1));
5050       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5051       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5052                              SDValue(NewLd.getNode(), 1));
5053     }
5054
5055     return NewLd;
5056   }
5057
5058   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5059   //of a v4i32 / v4f32. It's probably worth generalizing.
5060   EVT EltVT = VT.getVectorElementType();
5061   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5062       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5063     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5064     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5065     SDValue ResNode =
5066         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5067                                 LDBase->getPointerInfo(),
5068                                 LDBase->getAlignment(),
5069                                 false/*isVolatile*/, true/*ReadMem*/,
5070                                 false/*WriteMem*/);
5071
5072     // Make sure the newly-created LOAD is in the same position as LDBase in
5073     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5074     // update uses of LDBase's output chain to use the TokenFactor.
5075     if (LDBase->hasAnyUseOfValue(1)) {
5076       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5077                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5078       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5079       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5080                              SDValue(ResNode.getNode(), 1));
5081     }
5082
5083     return DAG.getBitcast(VT, ResNode);
5084   }
5085   return SDValue();
5086 }
5087
5088 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5089 /// to generate a splat value for the following cases:
5090 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5091 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5092 /// a scalar load, or a constant.
5093 /// The VBROADCAST node is returned when a pattern is found,
5094 /// or SDValue() otherwise.
5095 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5096                                     SelectionDAG &DAG) {
5097   // VBROADCAST requires AVX.
5098   // TODO: Splats could be generated for non-AVX CPUs using SSE
5099   // instructions, but there's less potential gain for only 128-bit vectors.
5100   if (!Subtarget->hasAVX())
5101     return SDValue();
5102
5103   MVT VT = Op.getSimpleValueType();
5104   SDLoc dl(Op);
5105
5106   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5107          "Unsupported vector type for broadcast.");
5108
5109   SDValue Ld;
5110   bool ConstSplatVal;
5111
5112   switch (Op.getOpcode()) {
5113     default:
5114       // Unknown pattern found.
5115       return SDValue();
5116
5117     case ISD::BUILD_VECTOR: {
5118       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5119       BitVector UndefElements;
5120       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5121
5122       // We need a splat of a single value to use broadcast, and it doesn't
5123       // make any sense if the value is only in one element of the vector.
5124       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5125         return SDValue();
5126
5127       Ld = Splat;
5128       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5129                        Ld.getOpcode() == ISD::ConstantFP);
5130
5131       // Make sure that all of the users of a non-constant load are from the
5132       // BUILD_VECTOR node.
5133       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5134         return SDValue();
5135       break;
5136     }
5137
5138     case ISD::VECTOR_SHUFFLE: {
5139       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5140
5141       // Shuffles must have a splat mask where the first element is
5142       // broadcasted.
5143       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5144         return SDValue();
5145
5146       SDValue Sc = Op.getOperand(0);
5147       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5148           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5149
5150         if (!Subtarget->hasInt256())
5151           return SDValue();
5152
5153         // Use the register form of the broadcast instruction available on AVX2.
5154         if (VT.getSizeInBits() >= 256)
5155           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5156         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5157       }
5158
5159       Ld = Sc.getOperand(0);
5160       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5161                        Ld.getOpcode() == ISD::ConstantFP);
5162
5163       // The scalar_to_vector node and the suspected
5164       // load node must have exactly one user.
5165       // Constants may have multiple users.
5166
5167       // AVX-512 has register version of the broadcast
5168       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5169         Ld.getValueType().getSizeInBits() >= 32;
5170       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5171           !hasRegVer))
5172         return SDValue();
5173       break;
5174     }
5175   }
5176
5177   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5178   bool IsGE256 = (VT.getSizeInBits() >= 256);
5179
5180   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5181   // instruction to save 8 or more bytes of constant pool data.
5182   // TODO: If multiple splats are generated to load the same constant,
5183   // it may be detrimental to overall size. There needs to be a way to detect
5184   // that condition to know if this is truly a size win.
5185   const Function *F = DAG.getMachineFunction().getFunction();
5186   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5187
5188   // Handle broadcasting a single constant scalar from the constant pool
5189   // into a vector.
5190   // On Sandybridge (no AVX2), it is still better to load a constant vector
5191   // from the constant pool and not to broadcast it from a scalar.
5192   // But override that restriction when optimizing for size.
5193   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5194   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5195     EVT CVT = Ld.getValueType();
5196     assert(!CVT.isVector() && "Must not broadcast a vector type");
5197
5198     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5199     // For size optimization, also splat v2f64 and v2i64, and for size opt
5200     // with AVX2, also splat i8 and i16.
5201     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5202     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5203         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5204       const Constant *C = nullptr;
5205       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5206         C = CI->getConstantIntValue();
5207       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5208         C = CF->getConstantFPValue();
5209
5210       assert(C && "Invalid constant type");
5211
5212       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5213       SDValue CP =
5214           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5215       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5216       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5217                        MachinePointerInfo::getConstantPool(),
5218                        false, false, false, Alignment);
5219
5220       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5221     }
5222   }
5223
5224   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5225
5226   // Handle AVX2 in-register broadcasts.
5227   if (!IsLoad && Subtarget->hasInt256() &&
5228       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5229     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5230
5231   // The scalar source must be a normal load.
5232   if (!IsLoad)
5233     return SDValue();
5234
5235   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5236       (Subtarget->hasVLX() && ScalarSize == 64))
5237     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5238
5239   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5240   // double since there is no vbroadcastsd xmm
5241   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5242     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5243       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5244   }
5245
5246   // Unsupported broadcast.
5247   return SDValue();
5248 }
5249
5250 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5251 /// underlying vector and index.
5252 ///
5253 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5254 /// index.
5255 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5256                                          SDValue ExtIdx) {
5257   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5258   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5259     return Idx;
5260
5261   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5262   // lowered this:
5263   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5264   // to:
5265   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5266   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5267   //                           undef)
5268   //                       Constant<0>)
5269   // In this case the vector is the extract_subvector expression and the index
5270   // is 2, as specified by the shuffle.
5271   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5272   SDValue ShuffleVec = SVOp->getOperand(0);
5273   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5274   assert(ShuffleVecVT.getVectorElementType() ==
5275          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5276
5277   int ShuffleIdx = SVOp->getMaskElt(Idx);
5278   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5279     ExtractedFromVec = ShuffleVec;
5280     return ShuffleIdx;
5281   }
5282   return Idx;
5283 }
5284
5285 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5286   MVT VT = Op.getSimpleValueType();
5287
5288   // Skip if insert_vec_elt is not supported.
5289   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5290   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5291     return SDValue();
5292
5293   SDLoc DL(Op);
5294   unsigned NumElems = Op.getNumOperands();
5295
5296   SDValue VecIn1;
5297   SDValue VecIn2;
5298   SmallVector<unsigned, 4> InsertIndices;
5299   SmallVector<int, 8> Mask(NumElems, -1);
5300
5301   for (unsigned i = 0; i != NumElems; ++i) {
5302     unsigned Opc = Op.getOperand(i).getOpcode();
5303
5304     if (Opc == ISD::UNDEF)
5305       continue;
5306
5307     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5308       // Quit if more than 1 elements need inserting.
5309       if (InsertIndices.size() > 1)
5310         return SDValue();
5311
5312       InsertIndices.push_back(i);
5313       continue;
5314     }
5315
5316     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5317     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5318     // Quit if non-constant index.
5319     if (!isa<ConstantSDNode>(ExtIdx))
5320       return SDValue();
5321     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5322
5323     // Quit if extracted from vector of different type.
5324     if (ExtractedFromVec.getValueType() != VT)
5325       return SDValue();
5326
5327     if (!VecIn1.getNode())
5328       VecIn1 = ExtractedFromVec;
5329     else if (VecIn1 != ExtractedFromVec) {
5330       if (!VecIn2.getNode())
5331         VecIn2 = ExtractedFromVec;
5332       else if (VecIn2 != ExtractedFromVec)
5333         // Quit if more than 2 vectors to shuffle
5334         return SDValue();
5335     }
5336
5337     if (ExtractedFromVec == VecIn1)
5338       Mask[i] = Idx;
5339     else if (ExtractedFromVec == VecIn2)
5340       Mask[i] = Idx + NumElems;
5341   }
5342
5343   if (!VecIn1.getNode())
5344     return SDValue();
5345
5346   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5347   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5348   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5349     unsigned Idx = InsertIndices[i];
5350     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5351                      DAG.getIntPtrConstant(Idx, DL));
5352   }
5353
5354   return NV;
5355 }
5356
5357 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5358   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5359          Op.getScalarValueSizeInBits() == 1 &&
5360          "Can not convert non-constant vector");
5361   uint64_t Immediate = 0;
5362   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5363     SDValue In = Op.getOperand(idx);
5364     if (In.getOpcode() != ISD::UNDEF)
5365       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5366   }
5367   SDLoc dl(Op);
5368   MVT VT =
5369    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5370   return DAG.getConstant(Immediate, dl, VT);
5371 }
5372 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5373 SDValue
5374 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5375
5376   MVT VT = Op.getSimpleValueType();
5377   assert((VT.getVectorElementType() == MVT::i1) &&
5378          "Unexpected type in LowerBUILD_VECTORvXi1!");
5379
5380   SDLoc dl(Op);
5381   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5382     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5383     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5384     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5385   }
5386
5387   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5388     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5389     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5390     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5391   }
5392
5393   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5394     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5395     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5396       return DAG.getBitcast(VT, Imm);
5397     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5398     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5399                         DAG.getIntPtrConstant(0, dl));
5400   }
5401
5402   // Vector has one or more non-const elements
5403   uint64_t Immediate = 0;
5404   SmallVector<unsigned, 16> NonConstIdx;
5405   bool IsSplat = true;
5406   bool HasConstElts = false;
5407   int SplatIdx = -1;
5408   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5409     SDValue In = Op.getOperand(idx);
5410     if (In.getOpcode() == ISD::UNDEF)
5411       continue;
5412     if (!isa<ConstantSDNode>(In))
5413       NonConstIdx.push_back(idx);
5414     else {
5415       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5416       HasConstElts = true;
5417     }
5418     if (SplatIdx == -1)
5419       SplatIdx = idx;
5420     else if (In != Op.getOperand(SplatIdx))
5421       IsSplat = false;
5422   }
5423
5424   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5425   if (IsSplat)
5426     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5427                        DAG.getConstant(1, dl, VT),
5428                        DAG.getConstant(0, dl, VT));
5429
5430   // insert elements one by one
5431   SDValue DstVec;
5432   SDValue Imm;
5433   if (Immediate) {
5434     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5435     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5436   }
5437   else if (HasConstElts)
5438     Imm = DAG.getConstant(0, dl, VT);
5439   else
5440     Imm = DAG.getUNDEF(VT);
5441   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5442     DstVec = DAG.getBitcast(VT, Imm);
5443   else {
5444     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5445     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5446                          DAG.getIntPtrConstant(0, dl));
5447   }
5448
5449   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5450     unsigned InsertIdx = NonConstIdx[i];
5451     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5452                          Op.getOperand(InsertIdx),
5453                          DAG.getIntPtrConstant(InsertIdx, dl));
5454   }
5455   return DstVec;
5456 }
5457
5458 /// \brief Return true if \p N implements a horizontal binop and return the
5459 /// operands for the horizontal binop into V0 and V1.
5460 ///
5461 /// This is a helper function of LowerToHorizontalOp().
5462 /// This function checks that the build_vector \p N in input implements a
5463 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5464 /// operation to match.
5465 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5466 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5467 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5468 /// arithmetic sub.
5469 ///
5470 /// This function only analyzes elements of \p N whose indices are
5471 /// in range [BaseIdx, LastIdx).
5472 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5473                               SelectionDAG &DAG,
5474                               unsigned BaseIdx, unsigned LastIdx,
5475                               SDValue &V0, SDValue &V1) {
5476   EVT VT = N->getValueType(0);
5477
5478   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5479   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5480          "Invalid Vector in input!");
5481
5482   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5483   bool CanFold = true;
5484   unsigned ExpectedVExtractIdx = BaseIdx;
5485   unsigned NumElts = LastIdx - BaseIdx;
5486   V0 = DAG.getUNDEF(VT);
5487   V1 = DAG.getUNDEF(VT);
5488
5489   // Check if N implements a horizontal binop.
5490   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5491     SDValue Op = N->getOperand(i + BaseIdx);
5492
5493     // Skip UNDEFs.
5494     if (Op->getOpcode() == ISD::UNDEF) {
5495       // Update the expected vector extract index.
5496       if (i * 2 == NumElts)
5497         ExpectedVExtractIdx = BaseIdx;
5498       ExpectedVExtractIdx += 2;
5499       continue;
5500     }
5501
5502     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5503
5504     if (!CanFold)
5505       break;
5506
5507     SDValue Op0 = Op.getOperand(0);
5508     SDValue Op1 = Op.getOperand(1);
5509
5510     // Try to match the following pattern:
5511     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5512     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5513         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5514         Op0.getOperand(0) == Op1.getOperand(0) &&
5515         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5516         isa<ConstantSDNode>(Op1.getOperand(1)));
5517     if (!CanFold)
5518       break;
5519
5520     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5521     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5522
5523     if (i * 2 < NumElts) {
5524       if (V0.getOpcode() == ISD::UNDEF) {
5525         V0 = Op0.getOperand(0);
5526         if (V0.getValueType() != VT)
5527           return false;
5528       }
5529     } else {
5530       if (V1.getOpcode() == ISD::UNDEF) {
5531         V1 = Op0.getOperand(0);
5532         if (V1.getValueType() != VT)
5533           return false;
5534       }
5535       if (i * 2 == NumElts)
5536         ExpectedVExtractIdx = BaseIdx;
5537     }
5538
5539     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5540     if (I0 == ExpectedVExtractIdx)
5541       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5542     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5543       // Try to match the following dag sequence:
5544       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5545       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5546     } else
5547       CanFold = false;
5548
5549     ExpectedVExtractIdx += 2;
5550   }
5551
5552   return CanFold;
5553 }
5554
5555 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5556 /// a concat_vector.
5557 ///
5558 /// This is a helper function of LowerToHorizontalOp().
5559 /// This function expects two 256-bit vectors called V0 and V1.
5560 /// At first, each vector is split into two separate 128-bit vectors.
5561 /// Then, the resulting 128-bit vectors are used to implement two
5562 /// horizontal binary operations.
5563 ///
5564 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5565 ///
5566 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5567 /// the two new horizontal binop.
5568 /// When Mode is set, the first horizontal binop dag node would take as input
5569 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5570 /// horizontal binop dag node would take as input the lower 128-bit of V1
5571 /// and the upper 128-bit of V1.
5572 ///   Example:
5573 ///     HADD V0_LO, V0_HI
5574 ///     HADD V1_LO, V1_HI
5575 ///
5576 /// Otherwise, the first horizontal binop dag node takes as input the lower
5577 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5578 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5579 ///   Example:
5580 ///     HADD V0_LO, V1_LO
5581 ///     HADD V0_HI, V1_HI
5582 ///
5583 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5584 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5585 /// the upper 128-bits of the result.
5586 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5587                                      SDLoc DL, SelectionDAG &DAG,
5588                                      unsigned X86Opcode, bool Mode,
5589                                      bool isUndefLO, bool isUndefHI) {
5590   EVT VT = V0.getValueType();
5591   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5592          "Invalid nodes in input!");
5593
5594   unsigned NumElts = VT.getVectorNumElements();
5595   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5596   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5597   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5598   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5599   EVT NewVT = V0_LO.getValueType();
5600
5601   SDValue LO = DAG.getUNDEF(NewVT);
5602   SDValue HI = DAG.getUNDEF(NewVT);
5603
5604   if (Mode) {
5605     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5606     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5607       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5608     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5609       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5610   } else {
5611     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5612     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5613                        V1_LO->getOpcode() != ISD::UNDEF))
5614       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5615
5616     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5617                        V1_HI->getOpcode() != ISD::UNDEF))
5618       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5619   }
5620
5621   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5622 }
5623
5624 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5625 /// node.
5626 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5627                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5628   EVT VT = BV->getValueType(0);
5629   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5630       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5631     return SDValue();
5632
5633   SDLoc DL(BV);
5634   unsigned NumElts = VT.getVectorNumElements();
5635   SDValue InVec0 = DAG.getUNDEF(VT);
5636   SDValue InVec1 = DAG.getUNDEF(VT);
5637
5638   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5639           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5640
5641   // Odd-numbered elements in the input build vector are obtained from
5642   // adding two integer/float elements.
5643   // Even-numbered elements in the input build vector are obtained from
5644   // subtracting two integer/float elements.
5645   unsigned ExpectedOpcode = ISD::FSUB;
5646   unsigned NextExpectedOpcode = ISD::FADD;
5647   bool AddFound = false;
5648   bool SubFound = false;
5649
5650   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5651     SDValue Op = BV->getOperand(i);
5652
5653     // Skip 'undef' values.
5654     unsigned Opcode = Op.getOpcode();
5655     if (Opcode == ISD::UNDEF) {
5656       std::swap(ExpectedOpcode, NextExpectedOpcode);
5657       continue;
5658     }
5659
5660     // Early exit if we found an unexpected opcode.
5661     if (Opcode != ExpectedOpcode)
5662       return SDValue();
5663
5664     SDValue Op0 = Op.getOperand(0);
5665     SDValue Op1 = Op.getOperand(1);
5666
5667     // Try to match the following pattern:
5668     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5669     // Early exit if we cannot match that sequence.
5670     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5671         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5672         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5673         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5674         Op0.getOperand(1) != Op1.getOperand(1))
5675       return SDValue();
5676
5677     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5678     if (I0 != i)
5679       return SDValue();
5680
5681     // We found a valid add/sub node. Update the information accordingly.
5682     if (i & 1)
5683       AddFound = true;
5684     else
5685       SubFound = true;
5686
5687     // Update InVec0 and InVec1.
5688     if (InVec0.getOpcode() == ISD::UNDEF) {
5689       InVec0 = Op0.getOperand(0);
5690       if (InVec0.getValueType() != VT)
5691         return SDValue();
5692     }
5693     if (InVec1.getOpcode() == ISD::UNDEF) {
5694       InVec1 = Op1.getOperand(0);
5695       if (InVec1.getValueType() != VT)
5696         return SDValue();
5697     }
5698
5699     // Make sure that operands in input to each add/sub node always
5700     // come from a same pair of vectors.
5701     if (InVec0 != Op0.getOperand(0)) {
5702       if (ExpectedOpcode == ISD::FSUB)
5703         return SDValue();
5704
5705       // FADD is commutable. Try to commute the operands
5706       // and then test again.
5707       std::swap(Op0, Op1);
5708       if (InVec0 != Op0.getOperand(0))
5709         return SDValue();
5710     }
5711
5712     if (InVec1 != Op1.getOperand(0))
5713       return SDValue();
5714
5715     // Update the pair of expected opcodes.
5716     std::swap(ExpectedOpcode, NextExpectedOpcode);
5717   }
5718
5719   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5720   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5721       InVec1.getOpcode() != ISD::UNDEF)
5722     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5723
5724   return SDValue();
5725 }
5726
5727 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5728 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5729                                    const X86Subtarget *Subtarget,
5730                                    SelectionDAG &DAG) {
5731   EVT VT = BV->getValueType(0);
5732   unsigned NumElts = VT.getVectorNumElements();
5733   unsigned NumUndefsLO = 0;
5734   unsigned NumUndefsHI = 0;
5735   unsigned Half = NumElts/2;
5736
5737   // Count the number of UNDEF operands in the build_vector in input.
5738   for (unsigned i = 0, e = Half; i != e; ++i)
5739     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5740       NumUndefsLO++;
5741
5742   for (unsigned i = Half, e = NumElts; i != e; ++i)
5743     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5744       NumUndefsHI++;
5745
5746   // Early exit if this is either a build_vector of all UNDEFs or all the
5747   // operands but one are UNDEF.
5748   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5749     return SDValue();
5750
5751   SDLoc DL(BV);
5752   SDValue InVec0, InVec1;
5753   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5754     // Try to match an SSE3 float HADD/HSUB.
5755     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5756       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5757
5758     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5759       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5760   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5761     // Try to match an SSSE3 integer HADD/HSUB.
5762     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5763       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5764
5765     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5766       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5767   }
5768
5769   if (!Subtarget->hasAVX())
5770     return SDValue();
5771
5772   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5773     // Try to match an AVX horizontal add/sub of packed single/double
5774     // precision floating point values from 256-bit vectors.
5775     SDValue InVec2, InVec3;
5776     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5777         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5778         ((InVec0.getOpcode() == ISD::UNDEF ||
5779           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5780         ((InVec1.getOpcode() == ISD::UNDEF ||
5781           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5782       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5783
5784     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5785         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5786         ((InVec0.getOpcode() == ISD::UNDEF ||
5787           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5788         ((InVec1.getOpcode() == ISD::UNDEF ||
5789           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5790       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5791   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5792     // Try to match an AVX2 horizontal add/sub of signed integers.
5793     SDValue InVec2, InVec3;
5794     unsigned X86Opcode;
5795     bool CanFold = true;
5796
5797     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5798         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5799         ((InVec0.getOpcode() == ISD::UNDEF ||
5800           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5801         ((InVec1.getOpcode() == ISD::UNDEF ||
5802           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5803       X86Opcode = X86ISD::HADD;
5804     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5805         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5806         ((InVec0.getOpcode() == ISD::UNDEF ||
5807           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5808         ((InVec1.getOpcode() == ISD::UNDEF ||
5809           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5810       X86Opcode = X86ISD::HSUB;
5811     else
5812       CanFold = false;
5813
5814     if (CanFold) {
5815       // Fold this build_vector into a single horizontal add/sub.
5816       // Do this only if the target has AVX2.
5817       if (Subtarget->hasAVX2())
5818         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5819
5820       // Do not try to expand this build_vector into a pair of horizontal
5821       // add/sub if we can emit a pair of scalar add/sub.
5822       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5823         return SDValue();
5824
5825       // Convert this build_vector into a pair of horizontal binop followed by
5826       // a concat vector.
5827       bool isUndefLO = NumUndefsLO == Half;
5828       bool isUndefHI = NumUndefsHI == Half;
5829       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5830                                    isUndefLO, isUndefHI);
5831     }
5832   }
5833
5834   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5835        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5836     unsigned X86Opcode;
5837     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5838       X86Opcode = X86ISD::HADD;
5839     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5840       X86Opcode = X86ISD::HSUB;
5841     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5842       X86Opcode = X86ISD::FHADD;
5843     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5844       X86Opcode = X86ISD::FHSUB;
5845     else
5846       return SDValue();
5847
5848     // Don't try to expand this build_vector into a pair of horizontal add/sub
5849     // if we can simply emit a pair of scalar add/sub.
5850     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5851       return SDValue();
5852
5853     // Convert this build_vector into two horizontal add/sub followed by
5854     // a concat vector.
5855     bool isUndefLO = NumUndefsLO == Half;
5856     bool isUndefHI = NumUndefsHI == Half;
5857     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5858                                  isUndefLO, isUndefHI);
5859   }
5860
5861   return SDValue();
5862 }
5863
5864 SDValue
5865 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5866   SDLoc dl(Op);
5867
5868   MVT VT = Op.getSimpleValueType();
5869   MVT ExtVT = VT.getVectorElementType();
5870   unsigned NumElems = Op.getNumOperands();
5871
5872   // Generate vectors for predicate vectors.
5873   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5874     return LowerBUILD_VECTORvXi1(Op, DAG);
5875
5876   // Vectors containing all zeros can be matched by pxor and xorps later
5877   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5878     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5879     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5880     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5881       return Op;
5882
5883     return getZeroVector(VT, Subtarget, DAG, dl);
5884   }
5885
5886   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5887   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5888   // vpcmpeqd on 256-bit vectors.
5889   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5890     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5891       return Op;
5892
5893     if (!VT.is512BitVector())
5894       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5895   }
5896
5897   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5898   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5899     return AddSub;
5900   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5901     return HorizontalOp;
5902   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5903     return Broadcast;
5904
5905   unsigned EVTBits = ExtVT.getSizeInBits();
5906
5907   unsigned NumZero  = 0;
5908   unsigned NumNonZero = 0;
5909   unsigned NonZeros = 0;
5910   bool IsAllConstants = true;
5911   SmallSet<SDValue, 8> Values;
5912   for (unsigned i = 0; i < NumElems; ++i) {
5913     SDValue Elt = Op.getOperand(i);
5914     if (Elt.getOpcode() == ISD::UNDEF)
5915       continue;
5916     Values.insert(Elt);
5917     if (Elt.getOpcode() != ISD::Constant &&
5918         Elt.getOpcode() != ISD::ConstantFP)
5919       IsAllConstants = false;
5920     if (X86::isZeroNode(Elt))
5921       NumZero++;
5922     else {
5923       NonZeros |= (1 << i);
5924       NumNonZero++;
5925     }
5926   }
5927
5928   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5929   if (NumNonZero == 0)
5930     return DAG.getUNDEF(VT);
5931
5932   // Special case for single non-zero, non-undef, element.
5933   if (NumNonZero == 1) {
5934     unsigned Idx = countTrailingZeros(NonZeros);
5935     SDValue Item = Op.getOperand(Idx);
5936
5937     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5938     // the value are obviously zero, truncate the value to i32 and do the
5939     // insertion that way.  Only do this if the value is non-constant or if the
5940     // value is a constant being inserted into element 0.  It is cheaper to do
5941     // a constant pool load than it is to do a movd + shuffle.
5942     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5943         (!IsAllConstants || Idx == 0)) {
5944       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5945         // Handle SSE only.
5946         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5947         EVT VecVT = MVT::v4i32;
5948
5949         // Truncate the value (which may itself be a constant) to i32, and
5950         // convert it to a vector with movd (S2V+shuffle to zero extend).
5951         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5952         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5953         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5954                                       Item, Idx * 2, true, Subtarget, DAG));
5955       }
5956     }
5957
5958     // If we have a constant or non-constant insertion into the low element of
5959     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5960     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5961     // depending on what the source datatype is.
5962     if (Idx == 0) {
5963       if (NumZero == 0)
5964         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5965
5966       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5967           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5968         if (VT.is512BitVector()) {
5969           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5970           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5971                              Item, DAG.getIntPtrConstant(0, dl));
5972         }
5973         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5974                "Expected an SSE value type!");
5975         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5976         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5977         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5978       }
5979
5980       // We can't directly insert an i8 or i16 into a vector, so zero extend
5981       // it to i32 first.
5982       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5983         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5984         if (VT.is256BitVector()) {
5985           if (Subtarget->hasAVX()) {
5986             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5987             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5988           } else {
5989             // Without AVX, we need to extend to a 128-bit vector and then
5990             // insert into the 256-bit vector.
5991             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5992             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5993             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5994           }
5995         } else {
5996           assert(VT.is128BitVector() && "Expected an SSE value type!");
5997           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5998           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5999         }
6000         return DAG.getBitcast(VT, Item);
6001       }
6002     }
6003
6004     // Is it a vector logical left shift?
6005     if (NumElems == 2 && Idx == 1 &&
6006         X86::isZeroNode(Op.getOperand(0)) &&
6007         !X86::isZeroNode(Op.getOperand(1))) {
6008       unsigned NumBits = VT.getSizeInBits();
6009       return getVShift(true, VT,
6010                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
6011                                    VT, Op.getOperand(1)),
6012                        NumBits/2, DAG, *this, dl);
6013     }
6014
6015     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
6016       return SDValue();
6017
6018     // Otherwise, if this is a vector with i32 or f32 elements, and the element
6019     // is a non-constant being inserted into an element other than the low one,
6020     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
6021     // movd/movss) to move this into the low element, then shuffle it into
6022     // place.
6023     if (EVTBits == 32) {
6024       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6025       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6026     }
6027   }
6028
6029   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6030   if (Values.size() == 1) {
6031     if (EVTBits == 32) {
6032       // Instead of a shuffle like this:
6033       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6034       // Check if it's possible to issue this instead.
6035       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6036       unsigned Idx = countTrailingZeros(NonZeros);
6037       SDValue Item = Op.getOperand(Idx);
6038       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6039         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6040     }
6041     return SDValue();
6042   }
6043
6044   // A vector full of immediates; various special cases are already
6045   // handled, so this is best done with a single constant-pool load.
6046   if (IsAllConstants)
6047     return SDValue();
6048
6049   // For AVX-length vectors, see if we can use a vector load to get all of the
6050   // elements, otherwise build the individual 128-bit pieces and use
6051   // shuffles to put them in place.
6052   if (VT.is256BitVector() || VT.is512BitVector()) {
6053     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6054
6055     // Check for a build vector of consecutive loads.
6056     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6057       return LD;
6058
6059     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6060
6061     // Build both the lower and upper subvector.
6062     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6063                                 makeArrayRef(&V[0], NumElems/2));
6064     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6065                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6066
6067     // Recreate the wider vector with the lower and upper part.
6068     if (VT.is256BitVector())
6069       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6070     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6071   }
6072
6073   // Let legalizer expand 2-wide build_vectors.
6074   if (EVTBits == 64) {
6075     if (NumNonZero == 1) {
6076       // One half is zero or undef.
6077       unsigned Idx = countTrailingZeros(NonZeros);
6078       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6079                                  Op.getOperand(Idx));
6080       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6081     }
6082     return SDValue();
6083   }
6084
6085   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6086   if (EVTBits == 8 && NumElems == 16)
6087     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6088                                         Subtarget, *this))
6089       return V;
6090
6091   if (EVTBits == 16 && NumElems == 8)
6092     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6093                                       Subtarget, *this))
6094       return V;
6095
6096   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6097   if (EVTBits == 32 && NumElems == 4)
6098     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6099       return V;
6100
6101   // If element VT is == 32 bits, turn it into a number of shuffles.
6102   SmallVector<SDValue, 8> V(NumElems);
6103   if (NumElems == 4 && NumZero > 0) {
6104     for (unsigned i = 0; i < 4; ++i) {
6105       bool isZero = !(NonZeros & (1 << i));
6106       if (isZero)
6107         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6108       else
6109         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6110     }
6111
6112     for (unsigned i = 0; i < 2; ++i) {
6113       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6114         default: break;
6115         case 0:
6116           V[i] = V[i*2];  // Must be a zero vector.
6117           break;
6118         case 1:
6119           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6120           break;
6121         case 2:
6122           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6123           break;
6124         case 3:
6125           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6126           break;
6127       }
6128     }
6129
6130     bool Reverse1 = (NonZeros & 0x3) == 2;
6131     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6132     int MaskVec[] = {
6133       Reverse1 ? 1 : 0,
6134       Reverse1 ? 0 : 1,
6135       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6136       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6137     };
6138     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6139   }
6140
6141   if (Values.size() > 1 && VT.is128BitVector()) {
6142     // Check for a build vector of consecutive loads.
6143     for (unsigned i = 0; i < NumElems; ++i)
6144       V[i] = Op.getOperand(i);
6145
6146     // Check for elements which are consecutive loads.
6147     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6148       return LD;
6149
6150     // Check for a build vector from mostly shuffle plus few inserting.
6151     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6152       return Sh;
6153
6154     // For SSE 4.1, use insertps to put the high elements into the low element.
6155     if (Subtarget->hasSSE41()) {
6156       SDValue Result;
6157       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6158         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6159       else
6160         Result = DAG.getUNDEF(VT);
6161
6162       for (unsigned i = 1; i < NumElems; ++i) {
6163         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6164         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6165                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6166       }
6167       return Result;
6168     }
6169
6170     // Otherwise, expand into a number of unpckl*, start by extending each of
6171     // our (non-undef) elements to the full vector width with the element in the
6172     // bottom slot of the vector (which generates no code for SSE).
6173     for (unsigned i = 0; i < NumElems; ++i) {
6174       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6175         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6176       else
6177         V[i] = DAG.getUNDEF(VT);
6178     }
6179
6180     // Next, we iteratively mix elements, e.g. for v4f32:
6181     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6182     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6183     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6184     unsigned EltStride = NumElems >> 1;
6185     while (EltStride != 0) {
6186       for (unsigned i = 0; i < EltStride; ++i) {
6187         // If V[i+EltStride] is undef and this is the first round of mixing,
6188         // then it is safe to just drop this shuffle: V[i] is already in the
6189         // right place, the one element (since it's the first round) being
6190         // inserted as undef can be dropped.  This isn't safe for successive
6191         // rounds because they will permute elements within both vectors.
6192         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6193             EltStride == NumElems/2)
6194           continue;
6195
6196         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6197       }
6198       EltStride >>= 1;
6199     }
6200     return V[0];
6201   }
6202   return SDValue();
6203 }
6204
6205 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6206 // to create 256-bit vectors from two other 128-bit ones.
6207 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6208   SDLoc dl(Op);
6209   MVT ResVT = Op.getSimpleValueType();
6210
6211   assert((ResVT.is256BitVector() ||
6212           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6213
6214   SDValue V1 = Op.getOperand(0);
6215   SDValue V2 = Op.getOperand(1);
6216   unsigned NumElems = ResVT.getVectorNumElements();
6217   if (ResVT.is256BitVector())
6218     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6219
6220   if (Op.getNumOperands() == 4) {
6221     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6222                                 ResVT.getVectorNumElements()/2);
6223     SDValue V3 = Op.getOperand(2);
6224     SDValue V4 = Op.getOperand(3);
6225     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6226       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6227   }
6228   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6229 }
6230
6231 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6232                                        const X86Subtarget *Subtarget,
6233                                        SelectionDAG & DAG) {
6234   SDLoc dl(Op);
6235   MVT ResVT = Op.getSimpleValueType();
6236   unsigned NumOfOperands = Op.getNumOperands();
6237
6238   assert(isPowerOf2_32(NumOfOperands) &&
6239          "Unexpected number of operands in CONCAT_VECTORS");
6240
6241   if (NumOfOperands > 2) {
6242     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6243                                   ResVT.getVectorNumElements()/2);
6244     SmallVector<SDValue, 2> Ops;
6245     for (unsigned i = 0; i < NumOfOperands/2; i++)
6246       Ops.push_back(Op.getOperand(i));
6247     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6248     Ops.clear();
6249     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6250       Ops.push_back(Op.getOperand(i));
6251     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6252     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6253   }
6254
6255   SDValue V1 = Op.getOperand(0);
6256   SDValue V2 = Op.getOperand(1);
6257   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6258   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6259
6260   if (IsZeroV1 && IsZeroV2)
6261     return getZeroVector(ResVT, Subtarget, DAG, dl);
6262
6263   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6264   SDValue Undef = DAG.getUNDEF(ResVT);
6265   unsigned NumElems = ResVT.getVectorNumElements();
6266   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6267
6268   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6269   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6270   if (IsZeroV1)
6271     return V2;
6272
6273   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6274   // Zero the upper bits of V1
6275   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6276   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6277   if (IsZeroV2)
6278     return V1;
6279   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6280 }
6281
6282 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6283                                    const X86Subtarget *Subtarget,
6284                                    SelectionDAG &DAG) {
6285   MVT VT = Op.getSimpleValueType();
6286   if (VT.getVectorElementType() == MVT::i1)
6287     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6288
6289   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6290          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6291           Op.getNumOperands() == 4)));
6292
6293   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6294   // from two other 128-bit ones.
6295
6296   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6297   return LowerAVXCONCAT_VECTORS(Op, DAG);
6298 }
6299
6300
6301 //===----------------------------------------------------------------------===//
6302 // Vector shuffle lowering
6303 //
6304 // This is an experimental code path for lowering vector shuffles on x86. It is
6305 // designed to handle arbitrary vector shuffles and blends, gracefully
6306 // degrading performance as necessary. It works hard to recognize idiomatic
6307 // shuffles and lower them to optimal instruction patterns without leaving
6308 // a framework that allows reasonably efficient handling of all vector shuffle
6309 // patterns.
6310 //===----------------------------------------------------------------------===//
6311
6312 /// \brief Tiny helper function to identify a no-op mask.
6313 ///
6314 /// This is a somewhat boring predicate function. It checks whether the mask
6315 /// array input, which is assumed to be a single-input shuffle mask of the kind
6316 /// used by the X86 shuffle instructions (not a fully general
6317 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6318 /// in-place shuffle are 'no-op's.
6319 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6320   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6321     if (Mask[i] != -1 && Mask[i] != i)
6322       return false;
6323   return true;
6324 }
6325
6326 /// \brief Helper function to classify a mask as a single-input mask.
6327 ///
6328 /// This isn't a generic single-input test because in the vector shuffle
6329 /// lowering we canonicalize single inputs to be the first input operand. This
6330 /// means we can more quickly test for a single input by only checking whether
6331 /// an input from the second operand exists. We also assume that the size of
6332 /// mask corresponds to the size of the input vectors which isn't true in the
6333 /// fully general case.
6334 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6335   for (int M : Mask)
6336     if (M >= (int)Mask.size())
6337       return false;
6338   return true;
6339 }
6340
6341 /// \brief Test whether there are elements crossing 128-bit lanes in this
6342 /// shuffle mask.
6343 ///
6344 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6345 /// and we routinely test for these.
6346 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6347   int LaneSize = 128 / VT.getScalarSizeInBits();
6348   int Size = Mask.size();
6349   for (int i = 0; i < Size; ++i)
6350     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6351       return true;
6352   return false;
6353 }
6354
6355 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6356 ///
6357 /// This checks a shuffle mask to see if it is performing the same
6358 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6359 /// that it is also not lane-crossing. It may however involve a blend from the
6360 /// same lane of a second vector.
6361 ///
6362 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6363 /// non-trivial to compute in the face of undef lanes. The representation is
6364 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6365 /// entries from both V1 and V2 inputs to the wider mask.
6366 static bool
6367 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6368                                 SmallVectorImpl<int> &RepeatedMask) {
6369   int LaneSize = 128 / VT.getScalarSizeInBits();
6370   RepeatedMask.resize(LaneSize, -1);
6371   int Size = Mask.size();
6372   for (int i = 0; i < Size; ++i) {
6373     if (Mask[i] < 0)
6374       continue;
6375     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6376       // This entry crosses lanes, so there is no way to model this shuffle.
6377       return false;
6378
6379     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6380     if (RepeatedMask[i % LaneSize] == -1)
6381       // This is the first non-undef entry in this slot of a 128-bit lane.
6382       RepeatedMask[i % LaneSize] =
6383           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6384     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6385       // Found a mismatch with the repeated mask.
6386       return false;
6387   }
6388   return true;
6389 }
6390
6391 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6392 /// arguments.
6393 ///
6394 /// This is a fast way to test a shuffle mask against a fixed pattern:
6395 ///
6396 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6397 ///
6398 /// It returns true if the mask is exactly as wide as the argument list, and
6399 /// each element of the mask is either -1 (signifying undef) or the value given
6400 /// in the argument.
6401 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6402                                 ArrayRef<int> ExpectedMask) {
6403   if (Mask.size() != ExpectedMask.size())
6404     return false;
6405
6406   int Size = Mask.size();
6407
6408   // If the values are build vectors, we can look through them to find
6409   // equivalent inputs that make the shuffles equivalent.
6410   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6411   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6412
6413   for (int i = 0; i < Size; ++i)
6414     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6415       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6416       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6417       if (!MaskBV || !ExpectedBV ||
6418           MaskBV->getOperand(Mask[i] % Size) !=
6419               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6420         return false;
6421     }
6422
6423   return true;
6424 }
6425
6426 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6427 ///
6428 /// This helper function produces an 8-bit shuffle immediate corresponding to
6429 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6430 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6431 /// example.
6432 ///
6433 /// NB: We rely heavily on "undef" masks preserving the input lane.
6434 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6435                                           SelectionDAG &DAG) {
6436   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6437   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6438   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6439   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6440   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6441
6442   unsigned Imm = 0;
6443   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6444   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6445   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6446   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6447   return DAG.getConstant(Imm, DL, MVT::i8);
6448 }
6449
6450 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6451 ///
6452 /// This is used as a fallback approach when first class blend instructions are
6453 /// unavailable. Currently it is only suitable for integer vectors, but could
6454 /// be generalized for floating point vectors if desirable.
6455 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6456                                             SDValue V2, ArrayRef<int> Mask,
6457                                             SelectionDAG &DAG) {
6458   assert(VT.isInteger() && "Only supports integer vector types!");
6459   MVT EltVT = VT.getScalarType();
6460   int NumEltBits = EltVT.getSizeInBits();
6461   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6462   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6463                                     EltVT);
6464   SmallVector<SDValue, 16> MaskOps;
6465   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6466     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6467       return SDValue(); // Shuffled input!
6468     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6469   }
6470
6471   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6472   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6473   // We have to cast V2 around.
6474   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6475   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6476                                       DAG.getBitcast(MaskVT, V1Mask),
6477                                       DAG.getBitcast(MaskVT, V2)));
6478   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6479 }
6480
6481 /// \brief Try to emit a blend instruction for a shuffle.
6482 ///
6483 /// This doesn't do any checks for the availability of instructions for blending
6484 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6485 /// be matched in the backend with the type given. What it does check for is
6486 /// that the shuffle mask is in fact a blend.
6487 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6488                                          SDValue V2, ArrayRef<int> Mask,
6489                                          const X86Subtarget *Subtarget,
6490                                          SelectionDAG &DAG) {
6491   unsigned BlendMask = 0;
6492   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6493     if (Mask[i] >= Size) {
6494       if (Mask[i] != i + Size)
6495         return SDValue(); // Shuffled V2 input!
6496       BlendMask |= 1u << i;
6497       continue;
6498     }
6499     if (Mask[i] >= 0 && Mask[i] != i)
6500       return SDValue(); // Shuffled V1 input!
6501   }
6502   switch (VT.SimpleTy) {
6503   case MVT::v2f64:
6504   case MVT::v4f32:
6505   case MVT::v4f64:
6506   case MVT::v8f32:
6507     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6508                        DAG.getConstant(BlendMask, DL, MVT::i8));
6509
6510   case MVT::v4i64:
6511   case MVT::v8i32:
6512     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6513     // FALLTHROUGH
6514   case MVT::v2i64:
6515   case MVT::v4i32:
6516     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6517     // that instruction.
6518     if (Subtarget->hasAVX2()) {
6519       // Scale the blend by the number of 32-bit dwords per element.
6520       int Scale =  VT.getScalarSizeInBits() / 32;
6521       BlendMask = 0;
6522       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6523         if (Mask[i] >= Size)
6524           for (int j = 0; j < Scale; ++j)
6525             BlendMask |= 1u << (i * Scale + j);
6526
6527       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6528       V1 = DAG.getBitcast(BlendVT, V1);
6529       V2 = DAG.getBitcast(BlendVT, V2);
6530       return DAG.getBitcast(
6531           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6532                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6533     }
6534     // FALLTHROUGH
6535   case MVT::v8i16: {
6536     // For integer shuffles we need to expand the mask and cast the inputs to
6537     // v8i16s prior to blending.
6538     int Scale = 8 / VT.getVectorNumElements();
6539     BlendMask = 0;
6540     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6541       if (Mask[i] >= Size)
6542         for (int j = 0; j < Scale; ++j)
6543           BlendMask |= 1u << (i * Scale + j);
6544
6545     V1 = DAG.getBitcast(MVT::v8i16, V1);
6546     V2 = DAG.getBitcast(MVT::v8i16, V2);
6547     return DAG.getBitcast(VT,
6548                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6549                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6550   }
6551
6552   case MVT::v16i16: {
6553     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6554     SmallVector<int, 8> RepeatedMask;
6555     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6556       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6557       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6558       BlendMask = 0;
6559       for (int i = 0; i < 8; ++i)
6560         if (RepeatedMask[i] >= 16)
6561           BlendMask |= 1u << i;
6562       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6563                          DAG.getConstant(BlendMask, DL, MVT::i8));
6564     }
6565   }
6566     // FALLTHROUGH
6567   case MVT::v16i8:
6568   case MVT::v32i8: {
6569     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6570            "256-bit byte-blends require AVX2 support!");
6571
6572     // Scale the blend by the number of bytes per element.
6573     int Scale = VT.getScalarSizeInBits() / 8;
6574
6575     // This form of blend is always done on bytes. Compute the byte vector
6576     // type.
6577     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6578
6579     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6580     // mix of LLVM's code generator and the x86 backend. We tell the code
6581     // generator that boolean values in the elements of an x86 vector register
6582     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6583     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6584     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6585     // of the element (the remaining are ignored) and 0 in that high bit would
6586     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6587     // the LLVM model for boolean values in vector elements gets the relevant
6588     // bit set, it is set backwards and over constrained relative to x86's
6589     // actual model.
6590     SmallVector<SDValue, 32> VSELECTMask;
6591     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6592       for (int j = 0; j < Scale; ++j)
6593         VSELECTMask.push_back(
6594             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6595                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6596                                           MVT::i8));
6597
6598     V1 = DAG.getBitcast(BlendVT, V1);
6599     V2 = DAG.getBitcast(BlendVT, V2);
6600     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6601                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6602                                                       BlendVT, VSELECTMask),
6603                                           V1, V2));
6604   }
6605
6606   default:
6607     llvm_unreachable("Not a supported integer vector type!");
6608   }
6609 }
6610
6611 /// \brief Try to lower as a blend of elements from two inputs followed by
6612 /// a single-input permutation.
6613 ///
6614 /// This matches the pattern where we can blend elements from two inputs and
6615 /// then reduce the shuffle to a single-input permutation.
6616 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6617                                                    SDValue V2,
6618                                                    ArrayRef<int> Mask,
6619                                                    SelectionDAG &DAG) {
6620   // We build up the blend mask while checking whether a blend is a viable way
6621   // to reduce the shuffle.
6622   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6623   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6624
6625   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6626     if (Mask[i] < 0)
6627       continue;
6628
6629     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6630
6631     if (BlendMask[Mask[i] % Size] == -1)
6632       BlendMask[Mask[i] % Size] = Mask[i];
6633     else if (BlendMask[Mask[i] % Size] != Mask[i])
6634       return SDValue(); // Can't blend in the needed input!
6635
6636     PermuteMask[i] = Mask[i] % Size;
6637   }
6638
6639   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6640   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6641 }
6642
6643 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6644 /// blends and permutes.
6645 ///
6646 /// This matches the extremely common pattern for handling combined
6647 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6648 /// operations. It will try to pick the best arrangement of shuffles and
6649 /// blends.
6650 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6651                                                           SDValue V1,
6652                                                           SDValue V2,
6653                                                           ArrayRef<int> Mask,
6654                                                           SelectionDAG &DAG) {
6655   // Shuffle the input elements into the desired positions in V1 and V2 and
6656   // blend them together.
6657   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6658   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6659   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6660   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6661     if (Mask[i] >= 0 && Mask[i] < Size) {
6662       V1Mask[i] = Mask[i];
6663       BlendMask[i] = i;
6664     } else if (Mask[i] >= Size) {
6665       V2Mask[i] = Mask[i] - Size;
6666       BlendMask[i] = i + Size;
6667     }
6668
6669   // Try to lower with the simpler initial blend strategy unless one of the
6670   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6671   // shuffle may be able to fold with a load or other benefit. However, when
6672   // we'll have to do 2x as many shuffles in order to achieve this, blending
6673   // first is a better strategy.
6674   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6675     if (SDValue BlendPerm =
6676             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6677       return BlendPerm;
6678
6679   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6680   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6681   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6682 }
6683
6684 /// \brief Try to lower a vector shuffle as a byte rotation.
6685 ///
6686 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6687 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6688 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6689 /// try to generically lower a vector shuffle through such an pattern. It
6690 /// does not check for the profitability of lowering either as PALIGNR or
6691 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6692 /// This matches shuffle vectors that look like:
6693 ///
6694 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6695 ///
6696 /// Essentially it concatenates V1 and V2, shifts right by some number of
6697 /// elements, and takes the low elements as the result. Note that while this is
6698 /// specified as a *right shift* because x86 is little-endian, it is a *left
6699 /// rotate* of the vector lanes.
6700 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6701                                               SDValue V2,
6702                                               ArrayRef<int> Mask,
6703                                               const X86Subtarget *Subtarget,
6704                                               SelectionDAG &DAG) {
6705   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6706
6707   int NumElts = Mask.size();
6708   int NumLanes = VT.getSizeInBits() / 128;
6709   int NumLaneElts = NumElts / NumLanes;
6710
6711   // We need to detect various ways of spelling a rotation:
6712   //   [11, 12, 13, 14, 15,  0,  1,  2]
6713   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6714   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6715   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6716   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6717   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6718   int Rotation = 0;
6719   SDValue Lo, Hi;
6720   for (int l = 0; l < NumElts; l += NumLaneElts) {
6721     for (int i = 0; i < NumLaneElts; ++i) {
6722       if (Mask[l + i] == -1)
6723         continue;
6724       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6725
6726       // Get the mod-Size index and lane correct it.
6727       int LaneIdx = (Mask[l + i] % NumElts) - l;
6728       // Make sure it was in this lane.
6729       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6730         return SDValue();
6731
6732       // Determine where a rotated vector would have started.
6733       int StartIdx = i - LaneIdx;
6734       if (StartIdx == 0)
6735         // The identity rotation isn't interesting, stop.
6736         return SDValue();
6737
6738       // If we found the tail of a vector the rotation must be the missing
6739       // front. If we found the head of a vector, it must be how much of the
6740       // head.
6741       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6742
6743       if (Rotation == 0)
6744         Rotation = CandidateRotation;
6745       else if (Rotation != CandidateRotation)
6746         // The rotations don't match, so we can't match this mask.
6747         return SDValue();
6748
6749       // Compute which value this mask is pointing at.
6750       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6751
6752       // Compute which of the two target values this index should be assigned
6753       // to. This reflects whether the high elements are remaining or the low
6754       // elements are remaining.
6755       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6756
6757       // Either set up this value if we've not encountered it before, or check
6758       // that it remains consistent.
6759       if (!TargetV)
6760         TargetV = MaskV;
6761       else if (TargetV != MaskV)
6762         // This may be a rotation, but it pulls from the inputs in some
6763         // unsupported interleaving.
6764         return SDValue();
6765     }
6766   }
6767
6768   // Check that we successfully analyzed the mask, and normalize the results.
6769   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6770   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6771   if (!Lo)
6772     Lo = Hi;
6773   else if (!Hi)
6774     Hi = Lo;
6775
6776   // The actual rotate instruction rotates bytes, so we need to scale the
6777   // rotation based on how many bytes are in the vector lane.
6778   int Scale = 16 / NumLaneElts;
6779
6780   // SSSE3 targets can use the palignr instruction.
6781   if (Subtarget->hasSSSE3()) {
6782     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6783     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6784     Lo = DAG.getBitcast(AlignVT, Lo);
6785     Hi = DAG.getBitcast(AlignVT, Hi);
6786
6787     return DAG.getBitcast(
6788         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6789                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6790   }
6791
6792   assert(VT.getSizeInBits() == 128 &&
6793          "Rotate-based lowering only supports 128-bit lowering!");
6794   assert(Mask.size() <= 16 &&
6795          "Can shuffle at most 16 bytes in a 128-bit vector!");
6796
6797   // Default SSE2 implementation
6798   int LoByteShift = 16 - Rotation * Scale;
6799   int HiByteShift = Rotation * Scale;
6800
6801   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6802   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6803   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6804
6805   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6806                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6807   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6808                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6809   return DAG.getBitcast(VT,
6810                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6811 }
6812
6813 /// \brief Compute whether each element of a shuffle is zeroable.
6814 ///
6815 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6816 /// Either it is an undef element in the shuffle mask, the element of the input
6817 /// referenced is undef, or the element of the input referenced is known to be
6818 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6819 /// as many lanes with this technique as possible to simplify the remaining
6820 /// shuffle.
6821 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6822                                                      SDValue V1, SDValue V2) {
6823   SmallBitVector Zeroable(Mask.size(), false);
6824
6825   while (V1.getOpcode() == ISD::BITCAST)
6826     V1 = V1->getOperand(0);
6827   while (V2.getOpcode() == ISD::BITCAST)
6828     V2 = V2->getOperand(0);
6829
6830   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6831   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6832
6833   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6834     int M = Mask[i];
6835     // Handle the easy cases.
6836     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6837       Zeroable[i] = true;
6838       continue;
6839     }
6840
6841     // If this is an index into a build_vector node (which has the same number
6842     // of elements), dig out the input value and use it.
6843     SDValue V = M < Size ? V1 : V2;
6844     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6845       continue;
6846
6847     SDValue Input = V.getOperand(M % Size);
6848     // The UNDEF opcode check really should be dead code here, but not quite
6849     // worth asserting on (it isn't invalid, just unexpected).
6850     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6851       Zeroable[i] = true;
6852   }
6853
6854   return Zeroable;
6855 }
6856
6857 /// \brief Try to emit a bitmask instruction for a shuffle.
6858 ///
6859 /// This handles cases where we can model a blend exactly as a bitmask due to
6860 /// one of the inputs being zeroable.
6861 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6862                                            SDValue V2, ArrayRef<int> Mask,
6863                                            SelectionDAG &DAG) {
6864   MVT EltVT = VT.getScalarType();
6865   int NumEltBits = EltVT.getSizeInBits();
6866   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6867   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6868   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6869                                     IntEltVT);
6870   if (EltVT.isFloatingPoint()) {
6871     Zero = DAG.getBitcast(EltVT, Zero);
6872     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6873   }
6874   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6875   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6876   SDValue V;
6877   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6878     if (Zeroable[i])
6879       continue;
6880     if (Mask[i] % Size != i)
6881       return SDValue(); // Not a blend.
6882     if (!V)
6883       V = Mask[i] < Size ? V1 : V2;
6884     else if (V != (Mask[i] < Size ? V1 : V2))
6885       return SDValue(); // Can only let one input through the mask.
6886
6887     VMaskOps[i] = AllOnes;
6888   }
6889   if (!V)
6890     return SDValue(); // No non-zeroable elements!
6891
6892   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6893   V = DAG.getNode(VT.isFloatingPoint()
6894                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6895                   DL, VT, V, VMask);
6896   return V;
6897 }
6898
6899 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6900 ///
6901 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6902 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6903 /// matches elements from one of the input vectors shuffled to the left or
6904 /// right with zeroable elements 'shifted in'. It handles both the strictly
6905 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6906 /// quad word lane.
6907 ///
6908 /// PSHL : (little-endian) left bit shift.
6909 /// [ zz, 0, zz,  2 ]
6910 /// [ -1, 4, zz, -1 ]
6911 /// PSRL : (little-endian) right bit shift.
6912 /// [  1, zz,  3, zz]
6913 /// [ -1, -1,  7, zz]
6914 /// PSLLDQ : (little-endian) left byte shift
6915 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6916 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6917 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6918 /// PSRLDQ : (little-endian) right byte shift
6919 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6920 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6921 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6922 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6923                                          SDValue V2, ArrayRef<int> Mask,
6924                                          SelectionDAG &DAG) {
6925   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6926
6927   int Size = Mask.size();
6928   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6929
6930   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6931     for (int i = 0; i < Size; i += Scale)
6932       for (int j = 0; j < Shift; ++j)
6933         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6934           return false;
6935
6936     return true;
6937   };
6938
6939   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6940     for (int i = 0; i != Size; i += Scale) {
6941       unsigned Pos = Left ? i + Shift : i;
6942       unsigned Low = Left ? i : i + Shift;
6943       unsigned Len = Scale - Shift;
6944       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6945                                       Low + (V == V1 ? 0 : Size)))
6946         return SDValue();
6947     }
6948
6949     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6950     bool ByteShift = ShiftEltBits > 64;
6951     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6952                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6953     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6954
6955     // Normalize the scale for byte shifts to still produce an i64 element
6956     // type.
6957     Scale = ByteShift ? Scale / 2 : Scale;
6958
6959     // We need to round trip through the appropriate type for the shift.
6960     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6961     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6962     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6963            "Illegal integer vector type");
6964     V = DAG.getBitcast(ShiftVT, V);
6965
6966     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6967                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6968     return DAG.getBitcast(VT, V);
6969   };
6970
6971   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6972   // keep doubling the size of the integer elements up to that. We can
6973   // then shift the elements of the integer vector by whole multiples of
6974   // their width within the elements of the larger integer vector. Test each
6975   // multiple to see if we can find a match with the moved element indices
6976   // and that the shifted in elements are all zeroable.
6977   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6978     for (int Shift = 1; Shift != Scale; ++Shift)
6979       for (bool Left : {true, false})
6980         if (CheckZeros(Shift, Scale, Left))
6981           for (SDValue V : {V1, V2})
6982             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6983               return Match;
6984
6985   // no match
6986   return SDValue();
6987 }
6988
6989 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6990 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6991                                            SDValue V2, ArrayRef<int> Mask,
6992                                            SelectionDAG &DAG) {
6993   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6994   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6995
6996   int Size = Mask.size();
6997   int HalfSize = Size / 2;
6998   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6999
7000   // Upper half must be undefined.
7001   if (!isUndefInRange(Mask, HalfSize, HalfSize))
7002     return SDValue();
7003
7004   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
7005   // Remainder of lower half result is zero and upper half is all undef.
7006   auto LowerAsEXTRQ = [&]() {
7007     // Determine the extraction length from the part of the
7008     // lower half that isn't zeroable.
7009     int Len = HalfSize;
7010     for (; Len >= 0; --Len)
7011       if (!Zeroable[Len - 1])
7012         break;
7013     assert(Len > 0 && "Zeroable shuffle mask");
7014
7015     // Attempt to match first Len sequential elements from the lower half.
7016     SDValue Src;
7017     int Idx = -1;
7018     for (int i = 0; i != Len; ++i) {
7019       int M = Mask[i];
7020       if (M < 0)
7021         continue;
7022       SDValue &V = (M < Size ? V1 : V2);
7023       M = M % Size;
7024
7025       // All mask elements must be in the lower half.
7026       if (M > HalfSize)
7027         return SDValue();
7028
7029       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7030         Src = V;
7031         Idx = M - i;
7032         continue;
7033       }
7034       return SDValue();
7035     }
7036
7037     if (Idx < 0)
7038       return SDValue();
7039
7040     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7041     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7042     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7043     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7044                        DAG.getConstant(BitLen, DL, MVT::i8),
7045                        DAG.getConstant(BitIdx, DL, MVT::i8));
7046   };
7047
7048   if (SDValue ExtrQ = LowerAsEXTRQ())
7049     return ExtrQ;
7050
7051   // INSERTQ: Extract lowest Len elements from lower half of second source and
7052   // insert over first source, starting at Idx.
7053   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7054   auto LowerAsInsertQ = [&]() {
7055     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7056       SDValue Base;
7057
7058       // Attempt to match first source from mask before insertion point.
7059       if (isUndefInRange(Mask, 0, Idx)) {
7060         /* EMPTY */
7061       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7062         Base = V1;
7063       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7064         Base = V2;
7065       } else {
7066         continue;
7067       }
7068
7069       // Extend the extraction length looking to match both the insertion of
7070       // the second source and the remaining elements of the first.
7071       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7072         SDValue Insert;
7073         int Len = Hi - Idx;
7074
7075         // Match insertion.
7076         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7077           Insert = V1;
7078         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7079           Insert = V2;
7080         } else {
7081           continue;
7082         }
7083
7084         // Match the remaining elements of the lower half.
7085         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7086           /* EMPTY */
7087         } else if ((!Base || (Base == V1)) &&
7088                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7089           Base = V1;
7090         } else if ((!Base || (Base == V2)) &&
7091                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7092                                               Size + Hi)) {
7093           Base = V2;
7094         } else {
7095           continue;
7096         }
7097
7098         // We may not have a base (first source) - this can safely be undefined.
7099         if (!Base)
7100           Base = DAG.getUNDEF(VT);
7101
7102         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7103         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7104         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7105                            DAG.getConstant(BitLen, DL, MVT::i8),
7106                            DAG.getConstant(BitIdx, DL, MVT::i8));
7107       }
7108     }
7109
7110     return SDValue();
7111   };
7112
7113   if (SDValue InsertQ = LowerAsInsertQ())
7114     return InsertQ;
7115
7116   return SDValue();
7117 }
7118
7119 /// \brief Lower a vector shuffle as a zero or any extension.
7120 ///
7121 /// Given a specific number of elements, element bit width, and extension
7122 /// stride, produce either a zero or any extension based on the available
7123 /// features of the subtarget.
7124 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7125     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7126     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7127   assert(Scale > 1 && "Need a scale to extend.");
7128   int NumElements = VT.getVectorNumElements();
7129   int EltBits = VT.getScalarSizeInBits();
7130   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7131          "Only 8, 16, and 32 bit elements can be extended.");
7132   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7133
7134   // Found a valid zext mask! Try various lowering strategies based on the
7135   // input type and available ISA extensions.
7136   if (Subtarget->hasSSE41()) {
7137     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7138                                  NumElements / Scale);
7139     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7140   }
7141
7142   // For any extends we can cheat for larger element sizes and use shuffle
7143   // instructions that can fold with a load and/or copy.
7144   if (AnyExt && EltBits == 32) {
7145     int PSHUFDMask[4] = {0, -1, 1, -1};
7146     return DAG.getBitcast(
7147         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7148                         DAG.getBitcast(MVT::v4i32, InputV),
7149                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7150   }
7151   if (AnyExt && EltBits == 16 && Scale > 2) {
7152     int PSHUFDMask[4] = {0, -1, 0, -1};
7153     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7154                          DAG.getBitcast(MVT::v4i32, InputV),
7155                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7156     int PSHUFHWMask[4] = {1, -1, -1, -1};
7157     return DAG.getBitcast(
7158         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7159                         DAG.getBitcast(MVT::v8i16, InputV),
7160                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7161   }
7162
7163   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7164   // to 64-bits.
7165   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7166     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7167     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7168
7169     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7170                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7171                                          DAG.getConstant(EltBits, DL, MVT::i8),
7172                                          DAG.getConstant(0, DL, MVT::i8)));
7173     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7174       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7175
7176     SDValue Hi =
7177         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7178                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7179                                 DAG.getConstant(EltBits, DL, MVT::i8),
7180                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7181     return DAG.getNode(ISD::BITCAST, DL, VT,
7182                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7183   }
7184
7185   // If this would require more than 2 unpack instructions to expand, use
7186   // pshufb when available. We can only use more than 2 unpack instructions
7187   // when zero extending i8 elements which also makes it easier to use pshufb.
7188   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7189     assert(NumElements == 16 && "Unexpected byte vector width!");
7190     SDValue PSHUFBMask[16];
7191     for (int i = 0; i < 16; ++i)
7192       PSHUFBMask[i] =
7193           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7194     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7195     return DAG.getBitcast(VT,
7196                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7197                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7198                                                   MVT::v16i8, PSHUFBMask)));
7199   }
7200
7201   // Otherwise emit a sequence of unpacks.
7202   do {
7203     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7204     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7205                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7206     InputV = DAG.getBitcast(InputVT, InputV);
7207     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7208     Scale /= 2;
7209     EltBits *= 2;
7210     NumElements /= 2;
7211   } while (Scale > 1);
7212   return DAG.getBitcast(VT, InputV);
7213 }
7214
7215 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7216 ///
7217 /// This routine will try to do everything in its power to cleverly lower
7218 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7219 /// check for the profitability of this lowering,  it tries to aggressively
7220 /// match this pattern. It will use all of the micro-architectural details it
7221 /// can to emit an efficient lowering. It handles both blends with all-zero
7222 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7223 /// masking out later).
7224 ///
7225 /// The reason we have dedicated lowering for zext-style shuffles is that they
7226 /// are both incredibly common and often quite performance sensitive.
7227 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7228     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7229     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7230   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7231
7232   int Bits = VT.getSizeInBits();
7233   int NumElements = VT.getVectorNumElements();
7234   assert(VT.getScalarSizeInBits() <= 32 &&
7235          "Exceeds 32-bit integer zero extension limit");
7236   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7237
7238   // Define a helper function to check a particular ext-scale and lower to it if
7239   // valid.
7240   auto Lower = [&](int Scale) -> SDValue {
7241     SDValue InputV;
7242     bool AnyExt = true;
7243     for (int i = 0; i < NumElements; ++i) {
7244       if (Mask[i] == -1)
7245         continue; // Valid anywhere but doesn't tell us anything.
7246       if (i % Scale != 0) {
7247         // Each of the extended elements need to be zeroable.
7248         if (!Zeroable[i])
7249           return SDValue();
7250
7251         // We no longer are in the anyext case.
7252         AnyExt = false;
7253         continue;
7254       }
7255
7256       // Each of the base elements needs to be consecutive indices into the
7257       // same input vector.
7258       SDValue V = Mask[i] < NumElements ? V1 : V2;
7259       if (!InputV)
7260         InputV = V;
7261       else if (InputV != V)
7262         return SDValue(); // Flip-flopping inputs.
7263
7264       if (Mask[i] % NumElements != i / Scale)
7265         return SDValue(); // Non-consecutive strided elements.
7266     }
7267
7268     // If we fail to find an input, we have a zero-shuffle which should always
7269     // have already been handled.
7270     // FIXME: Maybe handle this here in case during blending we end up with one?
7271     if (!InputV)
7272       return SDValue();
7273
7274     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7275         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7276   };
7277
7278   // The widest scale possible for extending is to a 64-bit integer.
7279   assert(Bits % 64 == 0 &&
7280          "The number of bits in a vector must be divisible by 64 on x86!");
7281   int NumExtElements = Bits / 64;
7282
7283   // Each iteration, try extending the elements half as much, but into twice as
7284   // many elements.
7285   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7286     assert(NumElements % NumExtElements == 0 &&
7287            "The input vector size must be divisible by the extended size.");
7288     if (SDValue V = Lower(NumElements / NumExtElements))
7289       return V;
7290   }
7291
7292   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7293   if (Bits != 128)
7294     return SDValue();
7295
7296   // Returns one of the source operands if the shuffle can be reduced to a
7297   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7298   auto CanZExtLowHalf = [&]() {
7299     for (int i = NumElements / 2; i != NumElements; ++i)
7300       if (!Zeroable[i])
7301         return SDValue();
7302     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7303       return V1;
7304     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7305       return V2;
7306     return SDValue();
7307   };
7308
7309   if (SDValue V = CanZExtLowHalf()) {
7310     V = DAG.getBitcast(MVT::v2i64, V);
7311     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7312     return DAG.getBitcast(VT, V);
7313   }
7314
7315   // No viable ext lowering found.
7316   return SDValue();
7317 }
7318
7319 /// \brief Try to get a scalar value for a specific element of a vector.
7320 ///
7321 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7322 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7323                                               SelectionDAG &DAG) {
7324   MVT VT = V.getSimpleValueType();
7325   MVT EltVT = VT.getVectorElementType();
7326   while (V.getOpcode() == ISD::BITCAST)
7327     V = V.getOperand(0);
7328   // If the bitcasts shift the element size, we can't extract an equivalent
7329   // element from it.
7330   MVT NewVT = V.getSimpleValueType();
7331   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7332     return SDValue();
7333
7334   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7335       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7336     // Ensure the scalar operand is the same size as the destination.
7337     // FIXME: Add support for scalar truncation where possible.
7338     SDValue S = V.getOperand(Idx);
7339     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7340       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7341   }
7342
7343   return SDValue();
7344 }
7345
7346 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7347 ///
7348 /// This is particularly important because the set of instructions varies
7349 /// significantly based on whether the operand is a load or not.
7350 static bool isShuffleFoldableLoad(SDValue V) {
7351   while (V.getOpcode() == ISD::BITCAST)
7352     V = V.getOperand(0);
7353
7354   return ISD::isNON_EXTLoad(V.getNode());
7355 }
7356
7357 /// \brief Try to lower insertion of a single element into a zero vector.
7358 ///
7359 /// This is a common pattern that we have especially efficient patterns to lower
7360 /// across all subtarget feature sets.
7361 static SDValue lowerVectorShuffleAsElementInsertion(
7362     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7363     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7364   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7365   MVT ExtVT = VT;
7366   MVT EltVT = VT.getVectorElementType();
7367
7368   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7369                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7370                 Mask.begin();
7371   bool IsV1Zeroable = true;
7372   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7373     if (i != V2Index && !Zeroable[i]) {
7374       IsV1Zeroable = false;
7375       break;
7376     }
7377
7378   // Check for a single input from a SCALAR_TO_VECTOR node.
7379   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7380   // all the smarts here sunk into that routine. However, the current
7381   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7382   // vector shuffle lowering is dead.
7383   if (SDValue V2S = getScalarValueForVectorElement(
7384           V2, Mask[V2Index] - Mask.size(), DAG)) {
7385     // We need to zext the scalar if it is smaller than an i32.
7386     V2S = DAG.getBitcast(EltVT, V2S);
7387     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7388       // Using zext to expand a narrow element won't work for non-zero
7389       // insertions.
7390       if (!IsV1Zeroable)
7391         return SDValue();
7392
7393       // Zero-extend directly to i32.
7394       ExtVT = MVT::v4i32;
7395       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7396     }
7397     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7398   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7399              EltVT == MVT::i16) {
7400     // Either not inserting from the low element of the input or the input
7401     // element size is too small to use VZEXT_MOVL to clear the high bits.
7402     return SDValue();
7403   }
7404
7405   if (!IsV1Zeroable) {
7406     // If V1 can't be treated as a zero vector we have fewer options to lower
7407     // this. We can't support integer vectors or non-zero targets cheaply, and
7408     // the V1 elements can't be permuted in any way.
7409     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7410     if (!VT.isFloatingPoint() || V2Index != 0)
7411       return SDValue();
7412     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7413     V1Mask[V2Index] = -1;
7414     if (!isNoopShuffleMask(V1Mask))
7415       return SDValue();
7416     // This is essentially a special case blend operation, but if we have
7417     // general purpose blend operations, they are always faster. Bail and let
7418     // the rest of the lowering handle these as blends.
7419     if (Subtarget->hasSSE41())
7420       return SDValue();
7421
7422     // Otherwise, use MOVSD or MOVSS.
7423     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7424            "Only two types of floating point element types to handle!");
7425     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7426                        ExtVT, V1, V2);
7427   }
7428
7429   // This lowering only works for the low element with floating point vectors.
7430   if (VT.isFloatingPoint() && V2Index != 0)
7431     return SDValue();
7432
7433   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7434   if (ExtVT != VT)
7435     V2 = DAG.getBitcast(VT, V2);
7436
7437   if (V2Index != 0) {
7438     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7439     // the desired position. Otherwise it is more efficient to do a vector
7440     // shift left. We know that we can do a vector shift left because all
7441     // the inputs are zero.
7442     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7443       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7444       V2Shuffle[V2Index] = 0;
7445       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7446     } else {
7447       V2 = DAG.getBitcast(MVT::v2i64, V2);
7448       V2 = DAG.getNode(
7449           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7450           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7451                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7452                               DAG.getDataLayout(), VT)));
7453       V2 = DAG.getBitcast(VT, V2);
7454     }
7455   }
7456   return V2;
7457 }
7458
7459 /// \brief Try to lower broadcast of a single element.
7460 ///
7461 /// For convenience, this code also bundles all of the subtarget feature set
7462 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7463 /// a convenient way to factor it out.
7464 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7465                                              ArrayRef<int> Mask,
7466                                              const X86Subtarget *Subtarget,
7467                                              SelectionDAG &DAG) {
7468   if (!Subtarget->hasAVX())
7469     return SDValue();
7470   if (VT.isInteger() && !Subtarget->hasAVX2())
7471     return SDValue();
7472
7473   // Check that the mask is a broadcast.
7474   int BroadcastIdx = -1;
7475   for (int M : Mask)
7476     if (M >= 0 && BroadcastIdx == -1)
7477       BroadcastIdx = M;
7478     else if (M >= 0 && M != BroadcastIdx)
7479       return SDValue();
7480
7481   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7482                                             "a sorted mask where the broadcast "
7483                                             "comes from V1.");
7484
7485   // Go up the chain of (vector) values to find a scalar load that we can
7486   // combine with the broadcast.
7487   for (;;) {
7488     switch (V.getOpcode()) {
7489     case ISD::CONCAT_VECTORS: {
7490       int OperandSize = Mask.size() / V.getNumOperands();
7491       V = V.getOperand(BroadcastIdx / OperandSize);
7492       BroadcastIdx %= OperandSize;
7493       continue;
7494     }
7495
7496     case ISD::INSERT_SUBVECTOR: {
7497       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7498       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7499       if (!ConstantIdx)
7500         break;
7501
7502       int BeginIdx = (int)ConstantIdx->getZExtValue();
7503       int EndIdx =
7504           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7505       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7506         BroadcastIdx -= BeginIdx;
7507         V = VInner;
7508       } else {
7509         V = VOuter;
7510       }
7511       continue;
7512     }
7513     }
7514     break;
7515   }
7516
7517   // Check if this is a broadcast of a scalar. We special case lowering
7518   // for scalars so that we can more effectively fold with loads.
7519   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7520       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7521     V = V.getOperand(BroadcastIdx);
7522
7523     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7524     // Only AVX2 has register broadcasts.
7525     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7526       return SDValue();
7527   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7528     // We can't broadcast from a vector register without AVX2, and we can only
7529     // broadcast from the zero-element of a vector register.
7530     return SDValue();
7531   }
7532
7533   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7534 }
7535
7536 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7537 // INSERTPS when the V1 elements are already in the correct locations
7538 // because otherwise we can just always use two SHUFPS instructions which
7539 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7540 // perform INSERTPS if a single V1 element is out of place and all V2
7541 // elements are zeroable.
7542 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7543                                             ArrayRef<int> Mask,
7544                                             SelectionDAG &DAG) {
7545   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7546   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7547   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7548   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7549
7550   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7551
7552   unsigned ZMask = 0;
7553   int V1DstIndex = -1;
7554   int V2DstIndex = -1;
7555   bool V1UsedInPlace = false;
7556
7557   for (int i = 0; i < 4; ++i) {
7558     // Synthesize a zero mask from the zeroable elements (includes undefs).
7559     if (Zeroable[i]) {
7560       ZMask |= 1 << i;
7561       continue;
7562     }
7563
7564     // Flag if we use any V1 inputs in place.
7565     if (i == Mask[i]) {
7566       V1UsedInPlace = true;
7567       continue;
7568     }
7569
7570     // We can only insert a single non-zeroable element.
7571     if (V1DstIndex != -1 || V2DstIndex != -1)
7572       return SDValue();
7573
7574     if (Mask[i] < 4) {
7575       // V1 input out of place for insertion.
7576       V1DstIndex = i;
7577     } else {
7578       // V2 input for insertion.
7579       V2DstIndex = i;
7580     }
7581   }
7582
7583   // Don't bother if we have no (non-zeroable) element for insertion.
7584   if (V1DstIndex == -1 && V2DstIndex == -1)
7585     return SDValue();
7586
7587   // Determine element insertion src/dst indices. The src index is from the
7588   // start of the inserted vector, not the start of the concatenated vector.
7589   unsigned V2SrcIndex = 0;
7590   if (V1DstIndex != -1) {
7591     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7592     // and don't use the original V2 at all.
7593     V2SrcIndex = Mask[V1DstIndex];
7594     V2DstIndex = V1DstIndex;
7595     V2 = V1;
7596   } else {
7597     V2SrcIndex = Mask[V2DstIndex] - 4;
7598   }
7599
7600   // If no V1 inputs are used in place, then the result is created only from
7601   // the zero mask and the V2 insertion - so remove V1 dependency.
7602   if (!V1UsedInPlace)
7603     V1 = DAG.getUNDEF(MVT::v4f32);
7604
7605   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7606   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7607
7608   // Insert the V2 element into the desired position.
7609   SDLoc DL(Op);
7610   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7611                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7612 }
7613
7614 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7615 /// UNPCK instruction.
7616 ///
7617 /// This specifically targets cases where we end up with alternating between
7618 /// the two inputs, and so can permute them into something that feeds a single
7619 /// UNPCK instruction. Note that this routine only targets integer vectors
7620 /// because for floating point vectors we have a generalized SHUFPS lowering
7621 /// strategy that handles everything that doesn't *exactly* match an unpack,
7622 /// making this clever lowering unnecessary.
7623 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7624                                           SDValue V2, ArrayRef<int> Mask,
7625                                           SelectionDAG &DAG) {
7626   assert(!VT.isFloatingPoint() &&
7627          "This routine only supports integer vectors.");
7628   assert(!isSingleInputShuffleMask(Mask) &&
7629          "This routine should only be used when blending two inputs.");
7630   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7631
7632   int Size = Mask.size();
7633
7634   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7635     return M >= 0 && M % Size < Size / 2;
7636   });
7637   int NumHiInputs = std::count_if(
7638       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7639
7640   bool UnpackLo = NumLoInputs >= NumHiInputs;
7641
7642   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7643     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7644     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7645
7646     for (int i = 0; i < Size; ++i) {
7647       if (Mask[i] < 0)
7648         continue;
7649
7650       // Each element of the unpack contains Scale elements from this mask.
7651       int UnpackIdx = i / Scale;
7652
7653       // We only handle the case where V1 feeds the first slots of the unpack.
7654       // We rely on canonicalization to ensure this is the case.
7655       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7656         return SDValue();
7657
7658       // Setup the mask for this input. The indexing is tricky as we have to
7659       // handle the unpack stride.
7660       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7661       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7662           Mask[i] % Size;
7663     }
7664
7665     // If we will have to shuffle both inputs to use the unpack, check whether
7666     // we can just unpack first and shuffle the result. If so, skip this unpack.
7667     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7668         !isNoopShuffleMask(V2Mask))
7669       return SDValue();
7670
7671     // Shuffle the inputs into place.
7672     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7673     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7674
7675     // Cast the inputs to the type we will use to unpack them.
7676     V1 = DAG.getBitcast(UnpackVT, V1);
7677     V2 = DAG.getBitcast(UnpackVT, V2);
7678
7679     // Unpack the inputs and cast the result back to the desired type.
7680     return DAG.getBitcast(
7681         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7682                         UnpackVT, V1, V2));
7683   };
7684
7685   // We try each unpack from the largest to the smallest to try and find one
7686   // that fits this mask.
7687   int OrigNumElements = VT.getVectorNumElements();
7688   int OrigScalarSize = VT.getScalarSizeInBits();
7689   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7690     int Scale = ScalarSize / OrigScalarSize;
7691     int NumElements = OrigNumElements / Scale;
7692     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7693     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7694       return Unpack;
7695   }
7696
7697   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7698   // initial unpack.
7699   if (NumLoInputs == 0 || NumHiInputs == 0) {
7700     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7701            "We have to have *some* inputs!");
7702     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7703
7704     // FIXME: We could consider the total complexity of the permute of each
7705     // possible unpacking. Or at the least we should consider how many
7706     // half-crossings are created.
7707     // FIXME: We could consider commuting the unpacks.
7708
7709     SmallVector<int, 32> PermMask;
7710     PermMask.assign(Size, -1);
7711     for (int i = 0; i < Size; ++i) {
7712       if (Mask[i] < 0)
7713         continue;
7714
7715       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7716
7717       PermMask[i] =
7718           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7719     }
7720     return DAG.getVectorShuffle(
7721         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7722                             DL, VT, V1, V2),
7723         DAG.getUNDEF(VT), PermMask);
7724   }
7725
7726   return SDValue();
7727 }
7728
7729 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7730 ///
7731 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7732 /// support for floating point shuffles but not integer shuffles. These
7733 /// instructions will incur a domain crossing penalty on some chips though so
7734 /// it is better to avoid lowering through this for integer vectors where
7735 /// possible.
7736 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7737                                        const X86Subtarget *Subtarget,
7738                                        SelectionDAG &DAG) {
7739   SDLoc DL(Op);
7740   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7741   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7742   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7743   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7744   ArrayRef<int> Mask = SVOp->getMask();
7745   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7746
7747   if (isSingleInputShuffleMask(Mask)) {
7748     // Use low duplicate instructions for masks that match their pattern.
7749     if (Subtarget->hasSSE3())
7750       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7751         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7752
7753     // Straight shuffle of a single input vector. Simulate this by using the
7754     // single input as both of the "inputs" to this instruction..
7755     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7756
7757     if (Subtarget->hasAVX()) {
7758       // If we have AVX, we can use VPERMILPS which will allow folding a load
7759       // into the shuffle.
7760       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7761                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7762     }
7763
7764     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7765                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7766   }
7767   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7768   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7769
7770   // If we have a single input, insert that into V1 if we can do so cheaply.
7771   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7772     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7773             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7774       return Insertion;
7775     // Try inverting the insertion since for v2 masks it is easy to do and we
7776     // can't reliably sort the mask one way or the other.
7777     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7778                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7779     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7780             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7781       return Insertion;
7782   }
7783
7784   // Try to use one of the special instruction patterns to handle two common
7785   // blend patterns if a zero-blend above didn't work.
7786   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7787       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7788     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7789       // We can either use a special instruction to load over the low double or
7790       // to move just the low double.
7791       return DAG.getNode(
7792           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7793           DL, MVT::v2f64, V2,
7794           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7795
7796   if (Subtarget->hasSSE41())
7797     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7798                                                   Subtarget, DAG))
7799       return Blend;
7800
7801   // Use dedicated unpack instructions for masks that match their pattern.
7802   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7803     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7804   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7805     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7806
7807   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7808   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7809                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7810 }
7811
7812 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7813 ///
7814 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7815 /// the integer unit to minimize domain crossing penalties. However, for blends
7816 /// it falls back to the floating point shuffle operation with appropriate bit
7817 /// casting.
7818 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7819                                        const X86Subtarget *Subtarget,
7820                                        SelectionDAG &DAG) {
7821   SDLoc DL(Op);
7822   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7823   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7824   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7825   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7826   ArrayRef<int> Mask = SVOp->getMask();
7827   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7828
7829   if (isSingleInputShuffleMask(Mask)) {
7830     // Check for being able to broadcast a single element.
7831     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7832                                                           Mask, Subtarget, DAG))
7833       return Broadcast;
7834
7835     // Straight shuffle of a single input vector. For everything from SSE2
7836     // onward this has a single fast instruction with no scary immediates.
7837     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7838     V1 = DAG.getBitcast(MVT::v4i32, V1);
7839     int WidenedMask[4] = {
7840         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7841         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7842     return DAG.getBitcast(
7843         MVT::v2i64,
7844         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7845                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7846   }
7847   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7848   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7849   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7850   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7851
7852   // If we have a blend of two PACKUS operations an the blend aligns with the
7853   // low and half halves, we can just merge the PACKUS operations. This is
7854   // particularly important as it lets us merge shuffles that this routine itself
7855   // creates.
7856   auto GetPackNode = [](SDValue V) {
7857     while (V.getOpcode() == ISD::BITCAST)
7858       V = V.getOperand(0);
7859
7860     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7861   };
7862   if (SDValue V1Pack = GetPackNode(V1))
7863     if (SDValue V2Pack = GetPackNode(V2))
7864       return DAG.getBitcast(MVT::v2i64,
7865                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7866                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7867                                                      : V1Pack.getOperand(1),
7868                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7869                                                      : V2Pack.getOperand(1)));
7870
7871   // Try to use shift instructions.
7872   if (SDValue Shift =
7873           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7874     return Shift;
7875
7876   // When loading a scalar and then shuffling it into a vector we can often do
7877   // the insertion cheaply.
7878   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7879           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7880     return Insertion;
7881   // Try inverting the insertion since for v2 masks it is easy to do and we
7882   // can't reliably sort the mask one way or the other.
7883   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7884   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7885           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7886     return Insertion;
7887
7888   // We have different paths for blend lowering, but they all must use the
7889   // *exact* same predicate.
7890   bool IsBlendSupported = Subtarget->hasSSE41();
7891   if (IsBlendSupported)
7892     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7893                                                   Subtarget, DAG))
7894       return Blend;
7895
7896   // Use dedicated unpack instructions for masks that match their pattern.
7897   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7898     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7899   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7900     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7901
7902   // Try to use byte rotation instructions.
7903   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7904   if (Subtarget->hasSSSE3())
7905     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7906             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7907       return Rotate;
7908
7909   // If we have direct support for blends, we should lower by decomposing into
7910   // a permute. That will be faster than the domain cross.
7911   if (IsBlendSupported)
7912     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7913                                                       Mask, DAG);
7914
7915   // We implement this with SHUFPD which is pretty lame because it will likely
7916   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7917   // However, all the alternatives are still more cycles and newer chips don't
7918   // have this problem. It would be really nice if x86 had better shuffles here.
7919   V1 = DAG.getBitcast(MVT::v2f64, V1);
7920   V2 = DAG.getBitcast(MVT::v2f64, V2);
7921   return DAG.getBitcast(MVT::v2i64,
7922                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7923 }
7924
7925 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7926 ///
7927 /// This is used to disable more specialized lowerings when the shufps lowering
7928 /// will happen to be efficient.
7929 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7930   // This routine only handles 128-bit shufps.
7931   assert(Mask.size() == 4 && "Unsupported mask size!");
7932
7933   // To lower with a single SHUFPS we need to have the low half and high half
7934   // each requiring a single input.
7935   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7936     return false;
7937   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7938     return false;
7939
7940   return true;
7941 }
7942
7943 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7944 ///
7945 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7946 /// It makes no assumptions about whether this is the *best* lowering, it simply
7947 /// uses it.
7948 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7949                                             ArrayRef<int> Mask, SDValue V1,
7950                                             SDValue V2, SelectionDAG &DAG) {
7951   SDValue LowV = V1, HighV = V2;
7952   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7953
7954   int NumV2Elements =
7955       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7956
7957   if (NumV2Elements == 1) {
7958     int V2Index =
7959         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7960         Mask.begin();
7961
7962     // Compute the index adjacent to V2Index and in the same half by toggling
7963     // the low bit.
7964     int V2AdjIndex = V2Index ^ 1;
7965
7966     if (Mask[V2AdjIndex] == -1) {
7967       // Handles all the cases where we have a single V2 element and an undef.
7968       // This will only ever happen in the high lanes because we commute the
7969       // vector otherwise.
7970       if (V2Index < 2)
7971         std::swap(LowV, HighV);
7972       NewMask[V2Index] -= 4;
7973     } else {
7974       // Handle the case where the V2 element ends up adjacent to a V1 element.
7975       // To make this work, blend them together as the first step.
7976       int V1Index = V2AdjIndex;
7977       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7978       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7979                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7980
7981       // Now proceed to reconstruct the final blend as we have the necessary
7982       // high or low half formed.
7983       if (V2Index < 2) {
7984         LowV = V2;
7985         HighV = V1;
7986       } else {
7987         HighV = V2;
7988       }
7989       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7990       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7991     }
7992   } else if (NumV2Elements == 2) {
7993     if (Mask[0] < 4 && Mask[1] < 4) {
7994       // Handle the easy case where we have V1 in the low lanes and V2 in the
7995       // high lanes.
7996       NewMask[2] -= 4;
7997       NewMask[3] -= 4;
7998     } else if (Mask[2] < 4 && Mask[3] < 4) {
7999       // We also handle the reversed case because this utility may get called
8000       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
8001       // arrange things in the right direction.
8002       NewMask[0] -= 4;
8003       NewMask[1] -= 4;
8004       HighV = V1;
8005       LowV = V2;
8006     } else {
8007       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
8008       // trying to place elements directly, just blend them and set up the final
8009       // shuffle to place them.
8010
8011       // The first two blend mask elements are for V1, the second two are for
8012       // V2.
8013       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
8014                           Mask[2] < 4 ? Mask[2] : Mask[3],
8015                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
8016                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
8017       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
8018                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
8019
8020       // Now we do a normal shuffle of V1 by giving V1 as both operands to
8021       // a blend.
8022       LowV = HighV = V1;
8023       NewMask[0] = Mask[0] < 4 ? 0 : 2;
8024       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8025       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8026       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8027     }
8028   }
8029   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8030                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8031 }
8032
8033 /// \brief Lower 4-lane 32-bit floating point shuffles.
8034 ///
8035 /// Uses instructions exclusively from the floating point unit to minimize
8036 /// domain crossing penalties, as these are sufficient to implement all v4f32
8037 /// shuffles.
8038 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8039                                        const X86Subtarget *Subtarget,
8040                                        SelectionDAG &DAG) {
8041   SDLoc DL(Op);
8042   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8043   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8044   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8045   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8046   ArrayRef<int> Mask = SVOp->getMask();
8047   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8048
8049   int NumV2Elements =
8050       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8051
8052   if (NumV2Elements == 0) {
8053     // Check for being able to broadcast a single element.
8054     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8055                                                           Mask, Subtarget, DAG))
8056       return Broadcast;
8057
8058     // Use even/odd duplicate instructions for masks that match their pattern.
8059     if (Subtarget->hasSSE3()) {
8060       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8061         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8062       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8063         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8064     }
8065
8066     if (Subtarget->hasAVX()) {
8067       // If we have AVX, we can use VPERMILPS which will allow folding a load
8068       // into the shuffle.
8069       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8070                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8071     }
8072
8073     // Otherwise, use a straight shuffle of a single input vector. We pass the
8074     // input vector to both operands to simulate this with a SHUFPS.
8075     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8076                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8077   }
8078
8079   // There are special ways we can lower some single-element blends. However, we
8080   // have custom ways we can lower more complex single-element blends below that
8081   // we defer to if both this and BLENDPS fail to match, so restrict this to
8082   // when the V2 input is targeting element 0 of the mask -- that is the fast
8083   // case here.
8084   if (NumV2Elements == 1 && Mask[0] >= 4)
8085     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8086                                                          Mask, Subtarget, DAG))
8087       return V;
8088
8089   if (Subtarget->hasSSE41()) {
8090     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8091                                                   Subtarget, DAG))
8092       return Blend;
8093
8094     // Use INSERTPS if we can complete the shuffle efficiently.
8095     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8096       return V;
8097
8098     if (!isSingleSHUFPSMask(Mask))
8099       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8100               DL, MVT::v4f32, V1, V2, Mask, DAG))
8101         return BlendPerm;
8102   }
8103
8104   // Use dedicated unpack instructions for masks that match their pattern.
8105   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8106     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8107   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8108     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8109   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8110     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8111   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8112     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8113
8114   // Otherwise fall back to a SHUFPS lowering strategy.
8115   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8116 }
8117
8118 /// \brief Lower 4-lane i32 vector shuffles.
8119 ///
8120 /// We try to handle these with integer-domain shuffles where we can, but for
8121 /// blends we use the floating point domain blend instructions.
8122 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8123                                        const X86Subtarget *Subtarget,
8124                                        SelectionDAG &DAG) {
8125   SDLoc DL(Op);
8126   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8127   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8128   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8129   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8130   ArrayRef<int> Mask = SVOp->getMask();
8131   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8132
8133   // Whenever we can lower this as a zext, that instruction is strictly faster
8134   // than any alternative. It also allows us to fold memory operands into the
8135   // shuffle in many cases.
8136   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8137                                                          Mask, Subtarget, DAG))
8138     return ZExt;
8139
8140   int NumV2Elements =
8141       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8142
8143   if (NumV2Elements == 0) {
8144     // Check for being able to broadcast a single element.
8145     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8146                                                           Mask, Subtarget, DAG))
8147       return Broadcast;
8148
8149     // Straight shuffle of a single input vector. For everything from SSE2
8150     // onward this has a single fast instruction with no scary immediates.
8151     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8152     // but we aren't actually going to use the UNPCK instruction because doing
8153     // so prevents folding a load into this instruction or making a copy.
8154     const int UnpackLoMask[] = {0, 0, 1, 1};
8155     const int UnpackHiMask[] = {2, 2, 3, 3};
8156     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8157       Mask = UnpackLoMask;
8158     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8159       Mask = UnpackHiMask;
8160
8161     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8162                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8163   }
8164
8165   // Try to use shift instructions.
8166   if (SDValue Shift =
8167           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8168     return Shift;
8169
8170   // There are special ways we can lower some single-element blends.
8171   if (NumV2Elements == 1)
8172     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8173                                                          Mask, Subtarget, DAG))
8174       return V;
8175
8176   // We have different paths for blend lowering, but they all must use the
8177   // *exact* same predicate.
8178   bool IsBlendSupported = Subtarget->hasSSE41();
8179   if (IsBlendSupported)
8180     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8181                                                   Subtarget, DAG))
8182       return Blend;
8183
8184   if (SDValue Masked =
8185           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8186     return Masked;
8187
8188   // Use dedicated unpack instructions for masks that match their pattern.
8189   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8190     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8191   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8192     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8193   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8194     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8195   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8196     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8197
8198   // Try to use byte rotation instructions.
8199   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8200   if (Subtarget->hasSSSE3())
8201     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8202             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8203       return Rotate;
8204
8205   // If we have direct support for blends, we should lower by decomposing into
8206   // a permute. That will be faster than the domain cross.
8207   if (IsBlendSupported)
8208     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8209                                                       Mask, DAG);
8210
8211   // Try to lower by permuting the inputs into an unpack instruction.
8212   if (SDValue Unpack =
8213           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8214     return Unpack;
8215
8216   // We implement this with SHUFPS because it can blend from two vectors.
8217   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8218   // up the inputs, bypassing domain shift penalties that we would encur if we
8219   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8220   // relevant.
8221   return DAG.getBitcast(
8222       MVT::v4i32,
8223       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8224                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8225 }
8226
8227 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8228 /// shuffle lowering, and the most complex part.
8229 ///
8230 /// The lowering strategy is to try to form pairs of input lanes which are
8231 /// targeted at the same half of the final vector, and then use a dword shuffle
8232 /// to place them onto the right half, and finally unpack the paired lanes into
8233 /// their final position.
8234 ///
8235 /// The exact breakdown of how to form these dword pairs and align them on the
8236 /// correct sides is really tricky. See the comments within the function for
8237 /// more of the details.
8238 ///
8239 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8240 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8241 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8242 /// vector, form the analogous 128-bit 8-element Mask.
8243 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8244     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8245     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8246   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8247   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8248
8249   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8250   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8251   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8252
8253   SmallVector<int, 4> LoInputs;
8254   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8255                [](int M) { return M >= 0; });
8256   std::sort(LoInputs.begin(), LoInputs.end());
8257   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8258   SmallVector<int, 4> HiInputs;
8259   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8260                [](int M) { return M >= 0; });
8261   std::sort(HiInputs.begin(), HiInputs.end());
8262   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8263   int NumLToL =
8264       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8265   int NumHToL = LoInputs.size() - NumLToL;
8266   int NumLToH =
8267       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8268   int NumHToH = HiInputs.size() - NumLToH;
8269   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8270   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8271   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8272   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8273
8274   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8275   // such inputs we can swap two of the dwords across the half mark and end up
8276   // with <=2 inputs to each half in each half. Once there, we can fall through
8277   // to the generic code below. For example:
8278   //
8279   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8280   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8281   //
8282   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8283   // and an existing 2-into-2 on the other half. In this case we may have to
8284   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8285   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8286   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8287   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8288   // half than the one we target for fixing) will be fixed when we re-enter this
8289   // path. We will also combine away any sequence of PSHUFD instructions that
8290   // result into a single instruction. Here is an example of the tricky case:
8291   //
8292   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8293   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8294   //
8295   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8296   //
8297   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8298   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8299   //
8300   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8301   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8302   //
8303   // The result is fine to be handled by the generic logic.
8304   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8305                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8306                           int AOffset, int BOffset) {
8307     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8308            "Must call this with A having 3 or 1 inputs from the A half.");
8309     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8310            "Must call this with B having 1 or 3 inputs from the B half.");
8311     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8312            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8313
8314     // Compute the index of dword with only one word among the three inputs in
8315     // a half by taking the sum of the half with three inputs and subtracting
8316     // the sum of the actual three inputs. The difference is the remaining
8317     // slot.
8318     int ADWord, BDWord;
8319     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8320     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8321     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8322     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8323     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8324     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8325     int TripleNonInputIdx =
8326         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8327     TripleDWord = TripleNonInputIdx / 2;
8328
8329     // We use xor with one to compute the adjacent DWord to whichever one the
8330     // OneInput is in.
8331     OneInputDWord = (OneInput / 2) ^ 1;
8332
8333     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8334     // and BToA inputs. If there is also such a problem with the BToB and AToB
8335     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8336     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8337     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8338     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8339       // Compute how many inputs will be flipped by swapping these DWords. We
8340       // need
8341       // to balance this to ensure we don't form a 3-1 shuffle in the other
8342       // half.
8343       int NumFlippedAToBInputs =
8344           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8345           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8346       int NumFlippedBToBInputs =
8347           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8348           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8349       if ((NumFlippedAToBInputs == 1 &&
8350            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8351           (NumFlippedBToBInputs == 1 &&
8352            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8353         // We choose whether to fix the A half or B half based on whether that
8354         // half has zero flipped inputs. At zero, we may not be able to fix it
8355         // with that half. We also bias towards fixing the B half because that
8356         // will more commonly be the high half, and we have to bias one way.
8357         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8358                                                        ArrayRef<int> Inputs) {
8359           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8360           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8361                                          PinnedIdx ^ 1) != Inputs.end();
8362           // Determine whether the free index is in the flipped dword or the
8363           // unflipped dword based on where the pinned index is. We use this bit
8364           // in an xor to conditionally select the adjacent dword.
8365           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8366           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8367                                              FixFreeIdx) != Inputs.end();
8368           if (IsFixIdxInput == IsFixFreeIdxInput)
8369             FixFreeIdx += 1;
8370           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8371                                         FixFreeIdx) != Inputs.end();
8372           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8373                  "We need to be changing the number of flipped inputs!");
8374           int PSHUFHalfMask[] = {0, 1, 2, 3};
8375           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8376           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8377                           MVT::v8i16, V,
8378                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8379
8380           for (int &M : Mask)
8381             if (M != -1 && M == FixIdx)
8382               M = FixFreeIdx;
8383             else if (M != -1 && M == FixFreeIdx)
8384               M = FixIdx;
8385         };
8386         if (NumFlippedBToBInputs != 0) {
8387           int BPinnedIdx =
8388               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8389           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8390         } else {
8391           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8392           int APinnedIdx =
8393               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8394           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8395         }
8396       }
8397     }
8398
8399     int PSHUFDMask[] = {0, 1, 2, 3};
8400     PSHUFDMask[ADWord] = BDWord;
8401     PSHUFDMask[BDWord] = ADWord;
8402     V = DAG.getBitcast(
8403         VT,
8404         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8405                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8406
8407     // Adjust the mask to match the new locations of A and B.
8408     for (int &M : Mask)
8409       if (M != -1 && M/2 == ADWord)
8410         M = 2 * BDWord + M % 2;
8411       else if (M != -1 && M/2 == BDWord)
8412         M = 2 * ADWord + M % 2;
8413
8414     // Recurse back into this routine to re-compute state now that this isn't
8415     // a 3 and 1 problem.
8416     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8417                                                      DAG);
8418   };
8419   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8420     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8421   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8422     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8423
8424   // At this point there are at most two inputs to the low and high halves from
8425   // each half. That means the inputs can always be grouped into dwords and
8426   // those dwords can then be moved to the correct half with a dword shuffle.
8427   // We use at most one low and one high word shuffle to collect these paired
8428   // inputs into dwords, and finally a dword shuffle to place them.
8429   int PSHUFLMask[4] = {-1, -1, -1, -1};
8430   int PSHUFHMask[4] = {-1, -1, -1, -1};
8431   int PSHUFDMask[4] = {-1, -1, -1, -1};
8432
8433   // First fix the masks for all the inputs that are staying in their
8434   // original halves. This will then dictate the targets of the cross-half
8435   // shuffles.
8436   auto fixInPlaceInputs =
8437       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8438                     MutableArrayRef<int> SourceHalfMask,
8439                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8440     if (InPlaceInputs.empty())
8441       return;
8442     if (InPlaceInputs.size() == 1) {
8443       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8444           InPlaceInputs[0] - HalfOffset;
8445       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8446       return;
8447     }
8448     if (IncomingInputs.empty()) {
8449       // Just fix all of the in place inputs.
8450       for (int Input : InPlaceInputs) {
8451         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8452         PSHUFDMask[Input / 2] = Input / 2;
8453       }
8454       return;
8455     }
8456
8457     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8458     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8459         InPlaceInputs[0] - HalfOffset;
8460     // Put the second input next to the first so that they are packed into
8461     // a dword. We find the adjacent index by toggling the low bit.
8462     int AdjIndex = InPlaceInputs[0] ^ 1;
8463     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8464     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8465     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8466   };
8467   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8468   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8469
8470   // Now gather the cross-half inputs and place them into a free dword of
8471   // their target half.
8472   // FIXME: This operation could almost certainly be simplified dramatically to
8473   // look more like the 3-1 fixing operation.
8474   auto moveInputsToRightHalf = [&PSHUFDMask](
8475       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8476       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8477       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8478       int DestOffset) {
8479     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8480       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8481     };
8482     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8483                                                int Word) {
8484       int LowWord = Word & ~1;
8485       int HighWord = Word | 1;
8486       return isWordClobbered(SourceHalfMask, LowWord) ||
8487              isWordClobbered(SourceHalfMask, HighWord);
8488     };
8489
8490     if (IncomingInputs.empty())
8491       return;
8492
8493     if (ExistingInputs.empty()) {
8494       // Map any dwords with inputs from them into the right half.
8495       for (int Input : IncomingInputs) {
8496         // If the source half mask maps over the inputs, turn those into
8497         // swaps and use the swapped lane.
8498         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8499           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8500             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8501                 Input - SourceOffset;
8502             // We have to swap the uses in our half mask in one sweep.
8503             for (int &M : HalfMask)
8504               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8505                 M = Input;
8506               else if (M == Input)
8507                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8508           } else {
8509             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8510                        Input - SourceOffset &&
8511                    "Previous placement doesn't match!");
8512           }
8513           // Note that this correctly re-maps both when we do a swap and when
8514           // we observe the other side of the swap above. We rely on that to
8515           // avoid swapping the members of the input list directly.
8516           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8517         }
8518
8519         // Map the input's dword into the correct half.
8520         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8521           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8522         else
8523           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8524                      Input / 2 &&
8525                  "Previous placement doesn't match!");
8526       }
8527
8528       // And just directly shift any other-half mask elements to be same-half
8529       // as we will have mirrored the dword containing the element into the
8530       // same position within that half.
8531       for (int &M : HalfMask)
8532         if (M >= SourceOffset && M < SourceOffset + 4) {
8533           M = M - SourceOffset + DestOffset;
8534           assert(M >= 0 && "This should never wrap below zero!");
8535         }
8536       return;
8537     }
8538
8539     // Ensure we have the input in a viable dword of its current half. This
8540     // is particularly tricky because the original position may be clobbered
8541     // by inputs being moved and *staying* in that half.
8542     if (IncomingInputs.size() == 1) {
8543       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8544         int InputFixed = std::find(std::begin(SourceHalfMask),
8545                                    std::end(SourceHalfMask), -1) -
8546                          std::begin(SourceHalfMask) + SourceOffset;
8547         SourceHalfMask[InputFixed - SourceOffset] =
8548             IncomingInputs[0] - SourceOffset;
8549         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8550                      InputFixed);
8551         IncomingInputs[0] = InputFixed;
8552       }
8553     } else if (IncomingInputs.size() == 2) {
8554       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8555           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8556         // We have two non-adjacent or clobbered inputs we need to extract from
8557         // the source half. To do this, we need to map them into some adjacent
8558         // dword slot in the source mask.
8559         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8560                               IncomingInputs[1] - SourceOffset};
8561
8562         // If there is a free slot in the source half mask adjacent to one of
8563         // the inputs, place the other input in it. We use (Index XOR 1) to
8564         // compute an adjacent index.
8565         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8566             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8567           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8568           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8569           InputsFixed[1] = InputsFixed[0] ^ 1;
8570         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8571                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8572           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8573           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8574           InputsFixed[0] = InputsFixed[1] ^ 1;
8575         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8576                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8577           // The two inputs are in the same DWord but it is clobbered and the
8578           // adjacent DWord isn't used at all. Move both inputs to the free
8579           // slot.
8580           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8581           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8582           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8583           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8584         } else {
8585           // The only way we hit this point is if there is no clobbering
8586           // (because there are no off-half inputs to this half) and there is no
8587           // free slot adjacent to one of the inputs. In this case, we have to
8588           // swap an input with a non-input.
8589           for (int i = 0; i < 4; ++i)
8590             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8591                    "We can't handle any clobbers here!");
8592           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8593                  "Cannot have adjacent inputs here!");
8594
8595           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8596           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8597
8598           // We also have to update the final source mask in this case because
8599           // it may need to undo the above swap.
8600           for (int &M : FinalSourceHalfMask)
8601             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8602               M = InputsFixed[1] + SourceOffset;
8603             else if (M == InputsFixed[1] + SourceOffset)
8604               M = (InputsFixed[0] ^ 1) + SourceOffset;
8605
8606           InputsFixed[1] = InputsFixed[0] ^ 1;
8607         }
8608
8609         // Point everything at the fixed inputs.
8610         for (int &M : HalfMask)
8611           if (M == IncomingInputs[0])
8612             M = InputsFixed[0] + SourceOffset;
8613           else if (M == IncomingInputs[1])
8614             M = InputsFixed[1] + SourceOffset;
8615
8616         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8617         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8618       }
8619     } else {
8620       llvm_unreachable("Unhandled input size!");
8621     }
8622
8623     // Now hoist the DWord down to the right half.
8624     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8625     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8626     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8627     for (int &M : HalfMask)
8628       for (int Input : IncomingInputs)
8629         if (M == Input)
8630           M = FreeDWord * 2 + Input % 2;
8631   };
8632   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8633                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8634   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8635                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8636
8637   // Now enact all the shuffles we've computed to move the inputs into their
8638   // target half.
8639   if (!isNoopShuffleMask(PSHUFLMask))
8640     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8641                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8642   if (!isNoopShuffleMask(PSHUFHMask))
8643     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8644                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8645   if (!isNoopShuffleMask(PSHUFDMask))
8646     V = DAG.getBitcast(
8647         VT,
8648         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8649                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8650
8651   // At this point, each half should contain all its inputs, and we can then
8652   // just shuffle them into their final position.
8653   assert(std::count_if(LoMask.begin(), LoMask.end(),
8654                        [](int M) { return M >= 4; }) == 0 &&
8655          "Failed to lift all the high half inputs to the low mask!");
8656   assert(std::count_if(HiMask.begin(), HiMask.end(),
8657                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8658          "Failed to lift all the low half inputs to the high mask!");
8659
8660   // Do a half shuffle for the low mask.
8661   if (!isNoopShuffleMask(LoMask))
8662     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8663                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8664
8665   // Do a half shuffle with the high mask after shifting its values down.
8666   for (int &M : HiMask)
8667     if (M >= 0)
8668       M -= 4;
8669   if (!isNoopShuffleMask(HiMask))
8670     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8671                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8672
8673   return V;
8674 }
8675
8676 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8677 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8678                                           SDValue V2, ArrayRef<int> Mask,
8679                                           SelectionDAG &DAG, bool &V1InUse,
8680                                           bool &V2InUse) {
8681   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8682   SDValue V1Mask[16];
8683   SDValue V2Mask[16];
8684   V1InUse = false;
8685   V2InUse = false;
8686
8687   int Size = Mask.size();
8688   int Scale = 16 / Size;
8689   for (int i = 0; i < 16; ++i) {
8690     if (Mask[i / Scale] == -1) {
8691       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8692     } else {
8693       const int ZeroMask = 0x80;
8694       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8695                                           : ZeroMask;
8696       int V2Idx = Mask[i / Scale] < Size
8697                       ? ZeroMask
8698                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8699       if (Zeroable[i / Scale])
8700         V1Idx = V2Idx = ZeroMask;
8701       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8702       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8703       V1InUse |= (ZeroMask != V1Idx);
8704       V2InUse |= (ZeroMask != V2Idx);
8705     }
8706   }
8707
8708   if (V1InUse)
8709     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8710                      DAG.getBitcast(MVT::v16i8, V1),
8711                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8712   if (V2InUse)
8713     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8714                      DAG.getBitcast(MVT::v16i8, V2),
8715                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8716
8717   // If we need shuffled inputs from both, blend the two.
8718   SDValue V;
8719   if (V1InUse && V2InUse)
8720     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8721   else
8722     V = V1InUse ? V1 : V2;
8723
8724   // Cast the result back to the correct type.
8725   return DAG.getBitcast(VT, V);
8726 }
8727
8728 /// \brief Generic lowering of 8-lane i16 shuffles.
8729 ///
8730 /// This handles both single-input shuffles and combined shuffle/blends with
8731 /// two inputs. The single input shuffles are immediately delegated to
8732 /// a dedicated lowering routine.
8733 ///
8734 /// The blends are lowered in one of three fundamental ways. If there are few
8735 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8736 /// of the input is significantly cheaper when lowered as an interleaving of
8737 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8738 /// halves of the inputs separately (making them have relatively few inputs)
8739 /// and then concatenate them.
8740 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8741                                        const X86Subtarget *Subtarget,
8742                                        SelectionDAG &DAG) {
8743   SDLoc DL(Op);
8744   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8745   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8746   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8747   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8748   ArrayRef<int> OrigMask = SVOp->getMask();
8749   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8750                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8751   MutableArrayRef<int> Mask(MaskStorage);
8752
8753   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8754
8755   // Whenever we can lower this as a zext, that instruction is strictly faster
8756   // than any alternative.
8757   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8758           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8759     return ZExt;
8760
8761   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8762   (void)isV1;
8763   auto isV2 = [](int M) { return M >= 8; };
8764
8765   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8766
8767   if (NumV2Inputs == 0) {
8768     // Check for being able to broadcast a single element.
8769     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8770                                                           Mask, Subtarget, DAG))
8771       return Broadcast;
8772
8773     // Try to use shift instructions.
8774     if (SDValue Shift =
8775             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8776       return Shift;
8777
8778     // Use dedicated unpack instructions for masks that match their pattern.
8779     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8780       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8781     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8782       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8783
8784     // Try to use byte rotation instructions.
8785     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8786                                                         Mask, Subtarget, DAG))
8787       return Rotate;
8788
8789     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8790                                                      Subtarget, DAG);
8791   }
8792
8793   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8794          "All single-input shuffles should be canonicalized to be V1-input "
8795          "shuffles.");
8796
8797   // Try to use shift instructions.
8798   if (SDValue Shift =
8799           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8800     return Shift;
8801
8802   // See if we can use SSE4A Extraction / Insertion.
8803   if (Subtarget->hasSSE4A())
8804     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8805       return V;
8806
8807   // There are special ways we can lower some single-element blends.
8808   if (NumV2Inputs == 1)
8809     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8810                                                          Mask, Subtarget, DAG))
8811       return V;
8812
8813   // We have different paths for blend lowering, but they all must use the
8814   // *exact* same predicate.
8815   bool IsBlendSupported = Subtarget->hasSSE41();
8816   if (IsBlendSupported)
8817     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8818                                                   Subtarget, DAG))
8819       return Blend;
8820
8821   if (SDValue Masked =
8822           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8823     return Masked;
8824
8825   // Use dedicated unpack instructions for masks that match their pattern.
8826   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8827     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8828   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8829     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8830
8831   // Try to use byte rotation instructions.
8832   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8833           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8834     return Rotate;
8835
8836   if (SDValue BitBlend =
8837           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8838     return BitBlend;
8839
8840   if (SDValue Unpack =
8841           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8842     return Unpack;
8843
8844   // If we can't directly blend but can use PSHUFB, that will be better as it
8845   // can both shuffle and set up the inefficient blend.
8846   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8847     bool V1InUse, V2InUse;
8848     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8849                                       V1InUse, V2InUse);
8850   }
8851
8852   // We can always bit-blend if we have to so the fallback strategy is to
8853   // decompose into single-input permutes and blends.
8854   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8855                                                       Mask, DAG);
8856 }
8857
8858 /// \brief Check whether a compaction lowering can be done by dropping even
8859 /// elements and compute how many times even elements must be dropped.
8860 ///
8861 /// This handles shuffles which take every Nth element where N is a power of
8862 /// two. Example shuffle masks:
8863 ///
8864 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8865 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8866 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8867 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8868 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8869 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8870 ///
8871 /// Any of these lanes can of course be undef.
8872 ///
8873 /// This routine only supports N <= 3.
8874 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8875 /// for larger N.
8876 ///
8877 /// \returns N above, or the number of times even elements must be dropped if
8878 /// there is such a number. Otherwise returns zero.
8879 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8880   // Figure out whether we're looping over two inputs or just one.
8881   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8882
8883   // The modulus for the shuffle vector entries is based on whether this is
8884   // a single input or not.
8885   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8886   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8887          "We should only be called with masks with a power-of-2 size!");
8888
8889   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8890
8891   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8892   // and 2^3 simultaneously. This is because we may have ambiguity with
8893   // partially undef inputs.
8894   bool ViableForN[3] = {true, true, true};
8895
8896   for (int i = 0, e = Mask.size(); i < e; ++i) {
8897     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8898     // want.
8899     if (Mask[i] == -1)
8900       continue;
8901
8902     bool IsAnyViable = false;
8903     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8904       if (ViableForN[j]) {
8905         uint64_t N = j + 1;
8906
8907         // The shuffle mask must be equal to (i * 2^N) % M.
8908         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8909           IsAnyViable = true;
8910         else
8911           ViableForN[j] = false;
8912       }
8913     // Early exit if we exhaust the possible powers of two.
8914     if (!IsAnyViable)
8915       break;
8916   }
8917
8918   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8919     if (ViableForN[j])
8920       return j + 1;
8921
8922   // Return 0 as there is no viable power of two.
8923   return 0;
8924 }
8925
8926 /// \brief Generic lowering of v16i8 shuffles.
8927 ///
8928 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8929 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8930 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8931 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8932 /// back together.
8933 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8934                                        const X86Subtarget *Subtarget,
8935                                        SelectionDAG &DAG) {
8936   SDLoc DL(Op);
8937   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8938   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8939   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8940   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8941   ArrayRef<int> Mask = SVOp->getMask();
8942   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8943
8944   // Try to use shift instructions.
8945   if (SDValue Shift =
8946           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8947     return Shift;
8948
8949   // Try to use byte rotation instructions.
8950   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8951           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8952     return Rotate;
8953
8954   // Try to use a zext lowering.
8955   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8956           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8957     return ZExt;
8958
8959   // See if we can use SSE4A Extraction / Insertion.
8960   if (Subtarget->hasSSE4A())
8961     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8962       return V;
8963
8964   int NumV2Elements =
8965       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8966
8967   // For single-input shuffles, there are some nicer lowering tricks we can use.
8968   if (NumV2Elements == 0) {
8969     // Check for being able to broadcast a single element.
8970     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8971                                                           Mask, Subtarget, DAG))
8972       return Broadcast;
8973
8974     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8975     // Notably, this handles splat and partial-splat shuffles more efficiently.
8976     // However, it only makes sense if the pre-duplication shuffle simplifies
8977     // things significantly. Currently, this means we need to be able to
8978     // express the pre-duplication shuffle as an i16 shuffle.
8979     //
8980     // FIXME: We should check for other patterns which can be widened into an
8981     // i16 shuffle as well.
8982     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8983       for (int i = 0; i < 16; i += 2)
8984         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8985           return false;
8986
8987       return true;
8988     };
8989     auto tryToWidenViaDuplication = [&]() -> SDValue {
8990       if (!canWidenViaDuplication(Mask))
8991         return SDValue();
8992       SmallVector<int, 4> LoInputs;
8993       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8994                    [](int M) { return M >= 0 && M < 8; });
8995       std::sort(LoInputs.begin(), LoInputs.end());
8996       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8997                      LoInputs.end());
8998       SmallVector<int, 4> HiInputs;
8999       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
9000                    [](int M) { return M >= 8; });
9001       std::sort(HiInputs.begin(), HiInputs.end());
9002       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
9003                      HiInputs.end());
9004
9005       bool TargetLo = LoInputs.size() >= HiInputs.size();
9006       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
9007       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
9008
9009       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
9010       SmallDenseMap<int, int, 8> LaneMap;
9011       for (int I : InPlaceInputs) {
9012         PreDupI16Shuffle[I/2] = I/2;
9013         LaneMap[I] = I;
9014       }
9015       int j = TargetLo ? 0 : 4, je = j + 4;
9016       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
9017         // Check if j is already a shuffle of this input. This happens when
9018         // there are two adjacent bytes after we move the low one.
9019         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
9020           // If we haven't yet mapped the input, search for a slot into which
9021           // we can map it.
9022           while (j < je && PreDupI16Shuffle[j] != -1)
9023             ++j;
9024
9025           if (j == je)
9026             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9027             return SDValue();
9028
9029           // Map this input with the i16 shuffle.
9030           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9031         }
9032
9033         // Update the lane map based on the mapping we ended up with.
9034         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9035       }
9036       V1 = DAG.getBitcast(
9037           MVT::v16i8,
9038           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9039                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9040
9041       // Unpack the bytes to form the i16s that will be shuffled into place.
9042       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9043                        MVT::v16i8, V1, V1);
9044
9045       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9046       for (int i = 0; i < 16; ++i)
9047         if (Mask[i] != -1) {
9048           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9049           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9050           if (PostDupI16Shuffle[i / 2] == -1)
9051             PostDupI16Shuffle[i / 2] = MappedMask;
9052           else
9053             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9054                    "Conflicting entrties in the original shuffle!");
9055         }
9056       return DAG.getBitcast(
9057           MVT::v16i8,
9058           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9059                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9060     };
9061     if (SDValue V = tryToWidenViaDuplication())
9062       return V;
9063   }
9064
9065   // Use dedicated unpack instructions for masks that match their pattern.
9066   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9067                                          0, 16, 1, 17, 2, 18, 3, 19,
9068                                          // High half.
9069                                          4, 20, 5, 21, 6, 22, 7, 23}))
9070     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9071   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9072                                          8, 24, 9, 25, 10, 26, 11, 27,
9073                                          // High half.
9074                                          12, 28, 13, 29, 14, 30, 15, 31}))
9075     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9076
9077   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9078   // with PSHUFB. It is important to do this before we attempt to generate any
9079   // blends but after all of the single-input lowerings. If the single input
9080   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9081   // want to preserve that and we can DAG combine any longer sequences into
9082   // a PSHUFB in the end. But once we start blending from multiple inputs,
9083   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9084   // and there are *very* few patterns that would actually be faster than the
9085   // PSHUFB approach because of its ability to zero lanes.
9086   //
9087   // FIXME: The only exceptions to the above are blends which are exact
9088   // interleavings with direct instructions supporting them. We currently don't
9089   // handle those well here.
9090   if (Subtarget->hasSSSE3()) {
9091     bool V1InUse = false;
9092     bool V2InUse = false;
9093
9094     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9095                                                 DAG, V1InUse, V2InUse);
9096
9097     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9098     // do so. This avoids using them to handle blends-with-zero which is
9099     // important as a single pshufb is significantly faster for that.
9100     if (V1InUse && V2InUse) {
9101       if (Subtarget->hasSSE41())
9102         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9103                                                       Mask, Subtarget, DAG))
9104           return Blend;
9105
9106       // We can use an unpack to do the blending rather than an or in some
9107       // cases. Even though the or may be (very minorly) more efficient, we
9108       // preference this lowering because there are common cases where part of
9109       // the complexity of the shuffles goes away when we do the final blend as
9110       // an unpack.
9111       // FIXME: It might be worth trying to detect if the unpack-feeding
9112       // shuffles will both be pshufb, in which case we shouldn't bother with
9113       // this.
9114       if (SDValue Unpack =
9115               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9116         return Unpack;
9117     }
9118
9119     return PSHUFB;
9120   }
9121
9122   // There are special ways we can lower some single-element blends.
9123   if (NumV2Elements == 1)
9124     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9125                                                          Mask, Subtarget, DAG))
9126       return V;
9127
9128   if (SDValue BitBlend =
9129           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9130     return BitBlend;
9131
9132   // Check whether a compaction lowering can be done. This handles shuffles
9133   // which take every Nth element for some even N. See the helper function for
9134   // details.
9135   //
9136   // We special case these as they can be particularly efficiently handled with
9137   // the PACKUSB instruction on x86 and they show up in common patterns of
9138   // rearranging bytes to truncate wide elements.
9139   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9140     // NumEvenDrops is the power of two stride of the elements. Another way of
9141     // thinking about it is that we need to drop the even elements this many
9142     // times to get the original input.
9143     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9144
9145     // First we need to zero all the dropped bytes.
9146     assert(NumEvenDrops <= 3 &&
9147            "No support for dropping even elements more than 3 times.");
9148     // We use the mask type to pick which bytes are preserved based on how many
9149     // elements are dropped.
9150     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9151     SDValue ByteClearMask = DAG.getBitcast(
9152         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9153     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9154     if (!IsSingleInput)
9155       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9156
9157     // Now pack things back together.
9158     V1 = DAG.getBitcast(MVT::v8i16, V1);
9159     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9160     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9161     for (int i = 1; i < NumEvenDrops; ++i) {
9162       Result = DAG.getBitcast(MVT::v8i16, Result);
9163       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9164     }
9165
9166     return Result;
9167   }
9168
9169   // Handle multi-input cases by blending single-input shuffles.
9170   if (NumV2Elements > 0)
9171     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9172                                                       Mask, DAG);
9173
9174   // The fallback path for single-input shuffles widens this into two v8i16
9175   // vectors with unpacks, shuffles those, and then pulls them back together
9176   // with a pack.
9177   SDValue V = V1;
9178
9179   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9180   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9181   for (int i = 0; i < 16; ++i)
9182     if (Mask[i] >= 0)
9183       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9184
9185   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9186
9187   SDValue VLoHalf, VHiHalf;
9188   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9189   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9190   // i16s.
9191   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9192                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9193       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9194                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9195     // Use a mask to drop the high bytes.
9196     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9197     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9198                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9199
9200     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9201     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9202
9203     // Squash the masks to point directly into VLoHalf.
9204     for (int &M : LoBlendMask)
9205       if (M >= 0)
9206         M /= 2;
9207     for (int &M : HiBlendMask)
9208       if (M >= 0)
9209         M /= 2;
9210   } else {
9211     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9212     // VHiHalf so that we can blend them as i16s.
9213     VLoHalf = DAG.getBitcast(
9214         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9215     VHiHalf = DAG.getBitcast(
9216         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9217   }
9218
9219   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9220   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9221
9222   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9223 }
9224
9225 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9226 ///
9227 /// This routine breaks down the specific type of 128-bit shuffle and
9228 /// dispatches to the lowering routines accordingly.
9229 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9230                                         MVT VT, const X86Subtarget *Subtarget,
9231                                         SelectionDAG &DAG) {
9232   switch (VT.SimpleTy) {
9233   case MVT::v2i64:
9234     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9235   case MVT::v2f64:
9236     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9237   case MVT::v4i32:
9238     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9239   case MVT::v4f32:
9240     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9241   case MVT::v8i16:
9242     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9243   case MVT::v16i8:
9244     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9245
9246   default:
9247     llvm_unreachable("Unimplemented!");
9248   }
9249 }
9250
9251 /// \brief Helper function to test whether a shuffle mask could be
9252 /// simplified by widening the elements being shuffled.
9253 ///
9254 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9255 /// leaves it in an unspecified state.
9256 ///
9257 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9258 /// shuffle masks. The latter have the special property of a '-2' representing
9259 /// a zero-ed lane of a vector.
9260 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9261                                     SmallVectorImpl<int> &WidenedMask) {
9262   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9263     // If both elements are undef, its trivial.
9264     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9265       WidenedMask.push_back(SM_SentinelUndef);
9266       continue;
9267     }
9268
9269     // Check for an undef mask and a mask value properly aligned to fit with
9270     // a pair of values. If we find such a case, use the non-undef mask's value.
9271     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9272       WidenedMask.push_back(Mask[i + 1] / 2);
9273       continue;
9274     }
9275     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9276       WidenedMask.push_back(Mask[i] / 2);
9277       continue;
9278     }
9279
9280     // When zeroing, we need to spread the zeroing across both lanes to widen.
9281     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9282       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9283           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9284         WidenedMask.push_back(SM_SentinelZero);
9285         continue;
9286       }
9287       return false;
9288     }
9289
9290     // Finally check if the two mask values are adjacent and aligned with
9291     // a pair.
9292     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9293       WidenedMask.push_back(Mask[i] / 2);
9294       continue;
9295     }
9296
9297     // Otherwise we can't safely widen the elements used in this shuffle.
9298     return false;
9299   }
9300   assert(WidenedMask.size() == Mask.size() / 2 &&
9301          "Incorrect size of mask after widening the elements!");
9302
9303   return true;
9304 }
9305
9306 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9307 ///
9308 /// This routine just extracts two subvectors, shuffles them independently, and
9309 /// then concatenates them back together. This should work effectively with all
9310 /// AVX vector shuffle types.
9311 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9312                                           SDValue V2, ArrayRef<int> Mask,
9313                                           SelectionDAG &DAG) {
9314   assert(VT.getSizeInBits() >= 256 &&
9315          "Only for 256-bit or wider vector shuffles!");
9316   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9317   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9318
9319   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9320   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9321
9322   int NumElements = VT.getVectorNumElements();
9323   int SplitNumElements = NumElements / 2;
9324   MVT ScalarVT = VT.getScalarType();
9325   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9326
9327   // Rather than splitting build-vectors, just build two narrower build
9328   // vectors. This helps shuffling with splats and zeros.
9329   auto SplitVector = [&](SDValue V) {
9330     while (V.getOpcode() == ISD::BITCAST)
9331       V = V->getOperand(0);
9332
9333     MVT OrigVT = V.getSimpleValueType();
9334     int OrigNumElements = OrigVT.getVectorNumElements();
9335     int OrigSplitNumElements = OrigNumElements / 2;
9336     MVT OrigScalarVT = OrigVT.getScalarType();
9337     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9338
9339     SDValue LoV, HiV;
9340
9341     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9342     if (!BV) {
9343       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9344                         DAG.getIntPtrConstant(0, DL));
9345       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9346                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9347     } else {
9348
9349       SmallVector<SDValue, 16> LoOps, HiOps;
9350       for (int i = 0; i < OrigSplitNumElements; ++i) {
9351         LoOps.push_back(BV->getOperand(i));
9352         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9353       }
9354       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9355       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9356     }
9357     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9358                           DAG.getBitcast(SplitVT, HiV));
9359   };
9360
9361   SDValue LoV1, HiV1, LoV2, HiV2;
9362   std::tie(LoV1, HiV1) = SplitVector(V1);
9363   std::tie(LoV2, HiV2) = SplitVector(V2);
9364
9365   // Now create two 4-way blends of these half-width vectors.
9366   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9367     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9368     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9369     for (int i = 0; i < SplitNumElements; ++i) {
9370       int M = HalfMask[i];
9371       if (M >= NumElements) {
9372         if (M >= NumElements + SplitNumElements)
9373           UseHiV2 = true;
9374         else
9375           UseLoV2 = true;
9376         V2BlendMask.push_back(M - NumElements);
9377         V1BlendMask.push_back(-1);
9378         BlendMask.push_back(SplitNumElements + i);
9379       } else if (M >= 0) {
9380         if (M >= SplitNumElements)
9381           UseHiV1 = true;
9382         else
9383           UseLoV1 = true;
9384         V2BlendMask.push_back(-1);
9385         V1BlendMask.push_back(M);
9386         BlendMask.push_back(i);
9387       } else {
9388         V2BlendMask.push_back(-1);
9389         V1BlendMask.push_back(-1);
9390         BlendMask.push_back(-1);
9391       }
9392     }
9393
9394     // Because the lowering happens after all combining takes place, we need to
9395     // manually combine these blend masks as much as possible so that we create
9396     // a minimal number of high-level vector shuffle nodes.
9397
9398     // First try just blending the halves of V1 or V2.
9399     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9400       return DAG.getUNDEF(SplitVT);
9401     if (!UseLoV2 && !UseHiV2)
9402       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9403     if (!UseLoV1 && !UseHiV1)
9404       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9405
9406     SDValue V1Blend, V2Blend;
9407     if (UseLoV1 && UseHiV1) {
9408       V1Blend =
9409         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9410     } else {
9411       // We only use half of V1 so map the usage down into the final blend mask.
9412       V1Blend = UseLoV1 ? LoV1 : HiV1;
9413       for (int i = 0; i < SplitNumElements; ++i)
9414         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9415           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9416     }
9417     if (UseLoV2 && UseHiV2) {
9418       V2Blend =
9419         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9420     } else {
9421       // We only use half of V2 so map the usage down into the final blend mask.
9422       V2Blend = UseLoV2 ? LoV2 : HiV2;
9423       for (int i = 0; i < SplitNumElements; ++i)
9424         if (BlendMask[i] >= SplitNumElements)
9425           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9426     }
9427     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9428   };
9429   SDValue Lo = HalfBlend(LoMask);
9430   SDValue Hi = HalfBlend(HiMask);
9431   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9432 }
9433
9434 /// \brief Either split a vector in halves or decompose the shuffles and the
9435 /// blend.
9436 ///
9437 /// This is provided as a good fallback for many lowerings of non-single-input
9438 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9439 /// between splitting the shuffle into 128-bit components and stitching those
9440 /// back together vs. extracting the single-input shuffles and blending those
9441 /// results.
9442 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9443                                                 SDValue V2, ArrayRef<int> Mask,
9444                                                 SelectionDAG &DAG) {
9445   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9446                                             "lower single-input shuffles as it "
9447                                             "could then recurse on itself.");
9448   int Size = Mask.size();
9449
9450   // If this can be modeled as a broadcast of two elements followed by a blend,
9451   // prefer that lowering. This is especially important because broadcasts can
9452   // often fold with memory operands.
9453   auto DoBothBroadcast = [&] {
9454     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9455     for (int M : Mask)
9456       if (M >= Size) {
9457         if (V2BroadcastIdx == -1)
9458           V2BroadcastIdx = M - Size;
9459         else if (M - Size != V2BroadcastIdx)
9460           return false;
9461       } else if (M >= 0) {
9462         if (V1BroadcastIdx == -1)
9463           V1BroadcastIdx = M;
9464         else if (M != V1BroadcastIdx)
9465           return false;
9466       }
9467     return true;
9468   };
9469   if (DoBothBroadcast())
9470     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9471                                                       DAG);
9472
9473   // If the inputs all stem from a single 128-bit lane of each input, then we
9474   // split them rather than blending because the split will decompose to
9475   // unusually few instructions.
9476   int LaneCount = VT.getSizeInBits() / 128;
9477   int LaneSize = Size / LaneCount;
9478   SmallBitVector LaneInputs[2];
9479   LaneInputs[0].resize(LaneCount, false);
9480   LaneInputs[1].resize(LaneCount, false);
9481   for (int i = 0; i < Size; ++i)
9482     if (Mask[i] >= 0)
9483       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9484   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9485     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9486
9487   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9488   // that the decomposed single-input shuffles don't end up here.
9489   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9490 }
9491
9492 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9493 /// a permutation and blend of those lanes.
9494 ///
9495 /// This essentially blends the out-of-lane inputs to each lane into the lane
9496 /// from a permuted copy of the vector. This lowering strategy results in four
9497 /// instructions in the worst case for a single-input cross lane shuffle which
9498 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9499 /// of. Special cases for each particular shuffle pattern should be handled
9500 /// prior to trying this lowering.
9501 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9502                                                        SDValue V1, SDValue V2,
9503                                                        ArrayRef<int> Mask,
9504                                                        SelectionDAG &DAG) {
9505   // FIXME: This should probably be generalized for 512-bit vectors as well.
9506   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9507   int LaneSize = Mask.size() / 2;
9508
9509   // If there are only inputs from one 128-bit lane, splitting will in fact be
9510   // less expensive. The flags track whether the given lane contains an element
9511   // that crosses to another lane.
9512   bool LaneCrossing[2] = {false, false};
9513   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9514     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9515       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9516   if (!LaneCrossing[0] || !LaneCrossing[1])
9517     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9518
9519   if (isSingleInputShuffleMask(Mask)) {
9520     SmallVector<int, 32> FlippedBlendMask;
9521     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9522       FlippedBlendMask.push_back(
9523           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9524                                   ? Mask[i]
9525                                   : Mask[i] % LaneSize +
9526                                         (i / LaneSize) * LaneSize + Size));
9527
9528     // Flip the vector, and blend the results which should now be in-lane. The
9529     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9530     // 5 for the high source. The value 3 selects the high half of source 2 and
9531     // the value 2 selects the low half of source 2. We only use source 2 to
9532     // allow folding it into a memory operand.
9533     unsigned PERMMask = 3 | 2 << 4;
9534     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9535                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9536     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9537   }
9538
9539   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9540   // will be handled by the above logic and a blend of the results, much like
9541   // other patterns in AVX.
9542   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9543 }
9544
9545 /// \brief Handle lowering 2-lane 128-bit shuffles.
9546 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9547                                         SDValue V2, ArrayRef<int> Mask,
9548                                         const X86Subtarget *Subtarget,
9549                                         SelectionDAG &DAG) {
9550   // TODO: If minimizing size and one of the inputs is a zero vector and the
9551   // the zero vector has only one use, we could use a VPERM2X128 to save the
9552   // instruction bytes needed to explicitly generate the zero vector.
9553
9554   // Blends are faster and handle all the non-lane-crossing cases.
9555   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9556                                                 Subtarget, DAG))
9557     return Blend;
9558
9559   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9560   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9561
9562   // If either input operand is a zero vector, use VPERM2X128 because its mask
9563   // allows us to replace the zero input with an implicit zero.
9564   if (!IsV1Zero && !IsV2Zero) {
9565     // Check for patterns which can be matched with a single insert of a 128-bit
9566     // subvector.
9567     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9568     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9569       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9570                                    VT.getVectorNumElements() / 2);
9571       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9572                                 DAG.getIntPtrConstant(0, DL));
9573       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9574                                 OnlyUsesV1 ? V1 : V2,
9575                                 DAG.getIntPtrConstant(0, DL));
9576       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9577     }
9578   }
9579
9580   // Otherwise form a 128-bit permutation. After accounting for undefs,
9581   // convert the 64-bit shuffle mask selection values into 128-bit
9582   // selection bits by dividing the indexes by 2 and shifting into positions
9583   // defined by a vperm2*128 instruction's immediate control byte.
9584
9585   // The immediate permute control byte looks like this:
9586   //    [1:0] - select 128 bits from sources for low half of destination
9587   //    [2]   - ignore
9588   //    [3]   - zero low half of destination
9589   //    [5:4] - select 128 bits from sources for high half of destination
9590   //    [6]   - ignore
9591   //    [7]   - zero high half of destination
9592
9593   int MaskLO = Mask[0];
9594   if (MaskLO == SM_SentinelUndef)
9595     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9596
9597   int MaskHI = Mask[2];
9598   if (MaskHI == SM_SentinelUndef)
9599     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9600
9601   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9602
9603   // If either input is a zero vector, replace it with an undef input.
9604   // Shuffle mask values <  4 are selecting elements of V1.
9605   // Shuffle mask values >= 4 are selecting elements of V2.
9606   // Adjust each half of the permute mask by clearing the half that was
9607   // selecting the zero vector and setting the zero mask bit.
9608   if (IsV1Zero) {
9609     V1 = DAG.getUNDEF(VT);
9610     if (MaskLO < 4)
9611       PermMask = (PermMask & 0xf0) | 0x08;
9612     if (MaskHI < 4)
9613       PermMask = (PermMask & 0x0f) | 0x80;
9614   }
9615   if (IsV2Zero) {
9616     V2 = DAG.getUNDEF(VT);
9617     if (MaskLO >= 4)
9618       PermMask = (PermMask & 0xf0) | 0x08;
9619     if (MaskHI >= 4)
9620       PermMask = (PermMask & 0x0f) | 0x80;
9621   }
9622
9623   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9624                      DAG.getConstant(PermMask, DL, MVT::i8));
9625 }
9626
9627 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9628 /// shuffling each lane.
9629 ///
9630 /// This will only succeed when the result of fixing the 128-bit lanes results
9631 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9632 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9633 /// the lane crosses early and then use simpler shuffles within each lane.
9634 ///
9635 /// FIXME: It might be worthwhile at some point to support this without
9636 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9637 /// in x86 only floating point has interesting non-repeating shuffles, and even
9638 /// those are still *marginally* more expensive.
9639 static SDValue lowerVectorShuffleByMerging128BitLanes(
9640     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9641     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9642   assert(!isSingleInputShuffleMask(Mask) &&
9643          "This is only useful with multiple inputs.");
9644
9645   int Size = Mask.size();
9646   int LaneSize = 128 / VT.getScalarSizeInBits();
9647   int NumLanes = Size / LaneSize;
9648   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9649
9650   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9651   // check whether the in-128-bit lane shuffles share a repeating pattern.
9652   SmallVector<int, 4> Lanes;
9653   Lanes.resize(NumLanes, -1);
9654   SmallVector<int, 4> InLaneMask;
9655   InLaneMask.resize(LaneSize, -1);
9656   for (int i = 0; i < Size; ++i) {
9657     if (Mask[i] < 0)
9658       continue;
9659
9660     int j = i / LaneSize;
9661
9662     if (Lanes[j] < 0) {
9663       // First entry we've seen for this lane.
9664       Lanes[j] = Mask[i] / LaneSize;
9665     } else if (Lanes[j] != Mask[i] / LaneSize) {
9666       // This doesn't match the lane selected previously!
9667       return SDValue();
9668     }
9669
9670     // Check that within each lane we have a consistent shuffle mask.
9671     int k = i % LaneSize;
9672     if (InLaneMask[k] < 0) {
9673       InLaneMask[k] = Mask[i] % LaneSize;
9674     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9675       // This doesn't fit a repeating in-lane mask.
9676       return SDValue();
9677     }
9678   }
9679
9680   // First shuffle the lanes into place.
9681   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9682                                 VT.getSizeInBits() / 64);
9683   SmallVector<int, 8> LaneMask;
9684   LaneMask.resize(NumLanes * 2, -1);
9685   for (int i = 0; i < NumLanes; ++i)
9686     if (Lanes[i] >= 0) {
9687       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9688       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9689     }
9690
9691   V1 = DAG.getBitcast(LaneVT, V1);
9692   V2 = DAG.getBitcast(LaneVT, V2);
9693   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9694
9695   // Cast it back to the type we actually want.
9696   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9697
9698   // Now do a simple shuffle that isn't lane crossing.
9699   SmallVector<int, 8> NewMask;
9700   NewMask.resize(Size, -1);
9701   for (int i = 0; i < Size; ++i)
9702     if (Mask[i] >= 0)
9703       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9704   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9705          "Must not introduce lane crosses at this point!");
9706
9707   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9708 }
9709
9710 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9711 /// given mask.
9712 ///
9713 /// This returns true if the elements from a particular input are already in the
9714 /// slot required by the given mask and require no permutation.
9715 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9716   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9717   int Size = Mask.size();
9718   for (int i = 0; i < Size; ++i)
9719     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9720       return false;
9721
9722   return true;
9723 }
9724
9725 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9726                                             ArrayRef<int> Mask, SDValue V1,
9727                                             SDValue V2, SelectionDAG &DAG) {
9728
9729   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9730   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9731   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9732   int NumElts = VT.getVectorNumElements();
9733   bool ShufpdMask = true;
9734   bool CommutableMask = true;
9735   unsigned Immediate = 0;
9736   for (int i = 0; i < NumElts; ++i) {
9737     if (Mask[i] < 0)
9738       continue;
9739     int Val = (i & 6) + NumElts * (i & 1);
9740     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9741     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9742       ShufpdMask = false;
9743     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9744       CommutableMask = false;
9745     Immediate |= (Mask[i] % 2) << i;
9746   }
9747   if (ShufpdMask)
9748     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9749                        DAG.getConstant(Immediate, DL, MVT::i8));
9750   if (CommutableMask)
9751     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9752                        DAG.getConstant(Immediate, DL, MVT::i8));
9753   return SDValue();
9754 }
9755
9756 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9757 ///
9758 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9759 /// isn't available.
9760 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9761                                        const X86Subtarget *Subtarget,
9762                                        SelectionDAG &DAG) {
9763   SDLoc DL(Op);
9764   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9765   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9766   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9767   ArrayRef<int> Mask = SVOp->getMask();
9768   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9769
9770   SmallVector<int, 4> WidenedMask;
9771   if (canWidenShuffleElements(Mask, WidenedMask))
9772     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9773                                     DAG);
9774
9775   if (isSingleInputShuffleMask(Mask)) {
9776     // Check for being able to broadcast a single element.
9777     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9778                                                           Mask, Subtarget, DAG))
9779       return Broadcast;
9780
9781     // Use low duplicate instructions for masks that match their pattern.
9782     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9783       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9784
9785     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9786       // Non-half-crossing single input shuffles can be lowerid with an
9787       // interleaved permutation.
9788       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9789                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9790       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9791                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9792     }
9793
9794     // With AVX2 we have direct support for this permutation.
9795     if (Subtarget->hasAVX2())
9796       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9797                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9798
9799     // Otherwise, fall back.
9800     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9801                                                    DAG);
9802   }
9803
9804   // X86 has dedicated unpack instructions that can handle specific blend
9805   // operations: UNPCKH and UNPCKL.
9806   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9807     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9808   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9809     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9810   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9811     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9812   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9813     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9814
9815   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9816                                                 Subtarget, DAG))
9817     return Blend;
9818
9819   // Check if the blend happens to exactly fit that of SHUFPD.
9820   if (SDValue Op =
9821       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9822     return Op;
9823
9824   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9825   // shuffle. However, if we have AVX2 and either inputs are already in place,
9826   // we will be able to shuffle even across lanes the other input in a single
9827   // instruction so skip this pattern.
9828   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9829                                  isShuffleMaskInputInPlace(1, Mask))))
9830     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9831             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9832       return Result;
9833
9834   // If we have AVX2 then we always want to lower with a blend because an v4 we
9835   // can fully permute the elements.
9836   if (Subtarget->hasAVX2())
9837     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9838                                                       Mask, DAG);
9839
9840   // Otherwise fall back on generic lowering.
9841   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9842 }
9843
9844 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9845 ///
9846 /// This routine is only called when we have AVX2 and thus a reasonable
9847 /// instruction set for v4i64 shuffling..
9848 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9849                                        const X86Subtarget *Subtarget,
9850                                        SelectionDAG &DAG) {
9851   SDLoc DL(Op);
9852   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9853   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9854   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9855   ArrayRef<int> Mask = SVOp->getMask();
9856   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9857   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9858
9859   SmallVector<int, 4> WidenedMask;
9860   if (canWidenShuffleElements(Mask, WidenedMask))
9861     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9862                                     DAG);
9863
9864   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9865                                                 Subtarget, DAG))
9866     return Blend;
9867
9868   // Check for being able to broadcast a single element.
9869   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9870                                                         Mask, Subtarget, DAG))
9871     return Broadcast;
9872
9873   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9874   // use lower latency instructions that will operate on both 128-bit lanes.
9875   SmallVector<int, 2> RepeatedMask;
9876   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9877     if (isSingleInputShuffleMask(Mask)) {
9878       int PSHUFDMask[] = {-1, -1, -1, -1};
9879       for (int i = 0; i < 2; ++i)
9880         if (RepeatedMask[i] >= 0) {
9881           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9882           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9883         }
9884       return DAG.getBitcast(
9885           MVT::v4i64,
9886           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9887                       DAG.getBitcast(MVT::v8i32, V1),
9888                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9889     }
9890   }
9891
9892   // AVX2 provides a direct instruction for permuting a single input across
9893   // lanes.
9894   if (isSingleInputShuffleMask(Mask))
9895     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9896                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9897
9898   // Try to use shift instructions.
9899   if (SDValue Shift =
9900           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9901     return Shift;
9902
9903   // Use dedicated unpack instructions for masks that match their pattern.
9904   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9905     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9906   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9907     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9908   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9909     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9910   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9911     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9912
9913   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9914   // shuffle. However, if we have AVX2 and either inputs are already in place,
9915   // we will be able to shuffle even across lanes the other input in a single
9916   // instruction so skip this pattern.
9917   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9918                                  isShuffleMaskInputInPlace(1, Mask))))
9919     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9920             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9921       return Result;
9922
9923   // Otherwise fall back on generic blend lowering.
9924   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9925                                                     Mask, DAG);
9926 }
9927
9928 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9929 ///
9930 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9931 /// isn't available.
9932 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9933                                        const X86Subtarget *Subtarget,
9934                                        SelectionDAG &DAG) {
9935   SDLoc DL(Op);
9936   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9937   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9938   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9939   ArrayRef<int> Mask = SVOp->getMask();
9940   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9941
9942   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9943                                                 Subtarget, DAG))
9944     return Blend;
9945
9946   // Check for being able to broadcast a single element.
9947   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9948                                                         Mask, Subtarget, DAG))
9949     return Broadcast;
9950
9951   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9952   // options to efficiently lower the shuffle.
9953   SmallVector<int, 4> RepeatedMask;
9954   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9955     assert(RepeatedMask.size() == 4 &&
9956            "Repeated masks must be half the mask width!");
9957
9958     // Use even/odd duplicate instructions for masks that match their pattern.
9959     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9960       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9961     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9962       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9963
9964     if (isSingleInputShuffleMask(Mask))
9965       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9966                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9967
9968     // Use dedicated unpack instructions for masks that match their pattern.
9969     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9970       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9971     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9972       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9973     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9974       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9975     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9976       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9977
9978     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9979     // have already handled any direct blends. We also need to squash the
9980     // repeated mask into a simulated v4f32 mask.
9981     for (int i = 0; i < 4; ++i)
9982       if (RepeatedMask[i] >= 8)
9983         RepeatedMask[i] -= 4;
9984     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9985   }
9986
9987   // If we have a single input shuffle with different shuffle patterns in the
9988   // two 128-bit lanes use the variable mask to VPERMILPS.
9989   if (isSingleInputShuffleMask(Mask)) {
9990     SDValue VPermMask[8];
9991     for (int i = 0; i < 8; ++i)
9992       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9993                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9994     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9995       return DAG.getNode(
9996           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9997           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9998
9999     if (Subtarget->hasAVX2())
10000       return DAG.getNode(
10001           X86ISD::VPERMV, DL, MVT::v8f32,
10002           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
10003                                                  MVT::v8i32, VPermMask)),
10004           V1);
10005
10006     // Otherwise, fall back.
10007     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
10008                                                    DAG);
10009   }
10010
10011   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10012   // shuffle.
10013   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10014           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
10015     return Result;
10016
10017   // If we have AVX2 then we always want to lower with a blend because at v8 we
10018   // can fully permute the elements.
10019   if (Subtarget->hasAVX2())
10020     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
10021                                                       Mask, DAG);
10022
10023   // Otherwise fall back on generic lowering.
10024   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10025 }
10026
10027 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10028 ///
10029 /// This routine is only called when we have AVX2 and thus a reasonable
10030 /// instruction set for v8i32 shuffling..
10031 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10032                                        const X86Subtarget *Subtarget,
10033                                        SelectionDAG &DAG) {
10034   SDLoc DL(Op);
10035   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10036   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10037   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10038   ArrayRef<int> Mask = SVOp->getMask();
10039   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10040   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10041
10042   // Whenever we can lower this as a zext, that instruction is strictly faster
10043   // than any alternative. It also allows us to fold memory operands into the
10044   // shuffle in many cases.
10045   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10046                                                          Mask, Subtarget, DAG))
10047     return ZExt;
10048
10049   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10050                                                 Subtarget, DAG))
10051     return Blend;
10052
10053   // Check for being able to broadcast a single element.
10054   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10055                                                         Mask, Subtarget, DAG))
10056     return Broadcast;
10057
10058   // If the shuffle mask is repeated in each 128-bit lane we can use more
10059   // efficient instructions that mirror the shuffles across the two 128-bit
10060   // lanes.
10061   SmallVector<int, 4> RepeatedMask;
10062   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10063     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10064     if (isSingleInputShuffleMask(Mask))
10065       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10066                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10067
10068     // Use dedicated unpack instructions for masks that match their pattern.
10069     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10070       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10071     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10072       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10073     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10074       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10075     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10076       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10077   }
10078
10079   // Try to use shift instructions.
10080   if (SDValue Shift =
10081           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10082     return Shift;
10083
10084   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10085           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10086     return Rotate;
10087
10088   // If the shuffle patterns aren't repeated but it is a single input, directly
10089   // generate a cross-lane VPERMD instruction.
10090   if (isSingleInputShuffleMask(Mask)) {
10091     SDValue VPermMask[8];
10092     for (int i = 0; i < 8; ++i)
10093       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10094                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10095     return DAG.getNode(
10096         X86ISD::VPERMV, DL, MVT::v8i32,
10097         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10098   }
10099
10100   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10101   // shuffle.
10102   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10103           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10104     return Result;
10105
10106   // Otherwise fall back on generic blend lowering.
10107   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10108                                                     Mask, DAG);
10109 }
10110
10111 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10112 ///
10113 /// This routine is only called when we have AVX2 and thus a reasonable
10114 /// instruction set for v16i16 shuffling..
10115 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10116                                         const X86Subtarget *Subtarget,
10117                                         SelectionDAG &DAG) {
10118   SDLoc DL(Op);
10119   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10120   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10121   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10122   ArrayRef<int> Mask = SVOp->getMask();
10123   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10124   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10125
10126   // Whenever we can lower this as a zext, that instruction is strictly faster
10127   // than any alternative. It also allows us to fold memory operands into the
10128   // shuffle in many cases.
10129   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10130                                                          Mask, Subtarget, DAG))
10131     return ZExt;
10132
10133   // Check for being able to broadcast a single element.
10134   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10135                                                         Mask, Subtarget, DAG))
10136     return Broadcast;
10137
10138   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10139                                                 Subtarget, DAG))
10140     return Blend;
10141
10142   // Use dedicated unpack instructions for masks that match their pattern.
10143   if (isShuffleEquivalent(V1, V2, Mask,
10144                           {// First 128-bit lane:
10145                            0, 16, 1, 17, 2, 18, 3, 19,
10146                            // Second 128-bit lane:
10147                            8, 24, 9, 25, 10, 26, 11, 27}))
10148     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10149   if (isShuffleEquivalent(V1, V2, Mask,
10150                           {// First 128-bit lane:
10151                            4, 20, 5, 21, 6, 22, 7, 23,
10152                            // Second 128-bit lane:
10153                            12, 28, 13, 29, 14, 30, 15, 31}))
10154     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10155
10156   // Try to use shift instructions.
10157   if (SDValue Shift =
10158           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10159     return Shift;
10160
10161   // Try to use byte rotation instructions.
10162   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10163           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10164     return Rotate;
10165
10166   if (isSingleInputShuffleMask(Mask)) {
10167     // There are no generalized cross-lane shuffle operations available on i16
10168     // element types.
10169     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10170       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10171                                                      Mask, DAG);
10172
10173     SmallVector<int, 8> RepeatedMask;
10174     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10175       // As this is a single-input shuffle, the repeated mask should be
10176       // a strictly valid v8i16 mask that we can pass through to the v8i16
10177       // lowering to handle even the v16 case.
10178       return lowerV8I16GeneralSingleInputVectorShuffle(
10179           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10180     }
10181
10182     SDValue PSHUFBMask[32];
10183     for (int i = 0; i < 16; ++i) {
10184       if (Mask[i] == -1) {
10185         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10186         continue;
10187       }
10188
10189       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10190       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10191       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10192       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10193     }
10194     return DAG.getBitcast(MVT::v16i16,
10195                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10196                                       DAG.getBitcast(MVT::v32i8, V1),
10197                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10198                                                   MVT::v32i8, PSHUFBMask)));
10199   }
10200
10201   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10202   // shuffle.
10203   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10204           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10205     return Result;
10206
10207   // Otherwise fall back on generic lowering.
10208   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10209 }
10210
10211 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10212 ///
10213 /// This routine is only called when we have AVX2 and thus a reasonable
10214 /// instruction set for v32i8 shuffling..
10215 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10216                                        const X86Subtarget *Subtarget,
10217                                        SelectionDAG &DAG) {
10218   SDLoc DL(Op);
10219   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10220   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10221   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10222   ArrayRef<int> Mask = SVOp->getMask();
10223   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10224   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10225
10226   // Whenever we can lower this as a zext, that instruction is strictly faster
10227   // than any alternative. It also allows us to fold memory operands into the
10228   // shuffle in many cases.
10229   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10230                                                          Mask, Subtarget, DAG))
10231     return ZExt;
10232
10233   // Check for being able to broadcast a single element.
10234   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10235                                                         Mask, Subtarget, DAG))
10236     return Broadcast;
10237
10238   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10239                                                 Subtarget, DAG))
10240     return Blend;
10241
10242   // Use dedicated unpack instructions for masks that match their pattern.
10243   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10244   // 256-bit lanes.
10245   if (isShuffleEquivalent(
10246           V1, V2, Mask,
10247           {// First 128-bit lane:
10248            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10249            // Second 128-bit lane:
10250            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10251     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10252   if (isShuffleEquivalent(
10253           V1, V2, Mask,
10254           {// First 128-bit lane:
10255            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10256            // Second 128-bit lane:
10257            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10258     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10259
10260   // Try to use shift instructions.
10261   if (SDValue Shift =
10262           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10263     return Shift;
10264
10265   // Try to use byte rotation instructions.
10266   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10267           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10268     return Rotate;
10269
10270   if (isSingleInputShuffleMask(Mask)) {
10271     // There are no generalized cross-lane shuffle operations available on i8
10272     // element types.
10273     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10274       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10275                                                      Mask, DAG);
10276
10277     SDValue PSHUFBMask[32];
10278     for (int i = 0; i < 32; ++i)
10279       PSHUFBMask[i] =
10280           Mask[i] < 0
10281               ? DAG.getUNDEF(MVT::i8)
10282               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10283                                 MVT::i8);
10284
10285     return DAG.getNode(
10286         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10287         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10288   }
10289
10290   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10291   // shuffle.
10292   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10293           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10294     return Result;
10295
10296   // Otherwise fall back on generic lowering.
10297   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10298 }
10299
10300 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10301 ///
10302 /// This routine either breaks down the specific type of a 256-bit x86 vector
10303 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10304 /// together based on the available instructions.
10305 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10306                                         MVT VT, const X86Subtarget *Subtarget,
10307                                         SelectionDAG &DAG) {
10308   SDLoc DL(Op);
10309   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10310   ArrayRef<int> Mask = SVOp->getMask();
10311
10312   // If we have a single input to the zero element, insert that into V1 if we
10313   // can do so cheaply.
10314   int NumElts = VT.getVectorNumElements();
10315   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10316     return M >= NumElts;
10317   });
10318
10319   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10320     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10321                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10322       return Insertion;
10323
10324   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10325   // check for those subtargets here and avoid much of the subtarget querying in
10326   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10327   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10328   // floating point types there eventually, just immediately cast everything to
10329   // a float and operate entirely in that domain.
10330   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10331     int ElementBits = VT.getScalarSizeInBits();
10332     if (ElementBits < 32)
10333       // No floating point type available, decompose into 128-bit vectors.
10334       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10335
10336     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10337                                 VT.getVectorNumElements());
10338     V1 = DAG.getBitcast(FpVT, V1);
10339     V2 = DAG.getBitcast(FpVT, V2);
10340     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10341   }
10342
10343   switch (VT.SimpleTy) {
10344   case MVT::v4f64:
10345     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10346   case MVT::v4i64:
10347     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10348   case MVT::v8f32:
10349     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10350   case MVT::v8i32:
10351     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10352   case MVT::v16i16:
10353     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10354   case MVT::v32i8:
10355     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10356
10357   default:
10358     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10359   }
10360 }
10361
10362 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10363 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10364                                        const X86Subtarget *Subtarget,
10365                                        SelectionDAG &DAG) {
10366   SDLoc DL(Op);
10367   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10368   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10369   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10370   ArrayRef<int> Mask = SVOp->getMask();
10371   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10372
10373   // X86 has dedicated unpack instructions that can handle specific blend
10374   // operations: UNPCKH and UNPCKL.
10375   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10376     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10377   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10378     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10379
10380   // FIXME: Implement direct support for this type!
10381   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10382 }
10383
10384 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10385 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10386                                        const X86Subtarget *Subtarget,
10387                                        SelectionDAG &DAG) {
10388   SDLoc DL(Op);
10389   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10390   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10391   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10392   ArrayRef<int> Mask = SVOp->getMask();
10393   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10394
10395   // Use dedicated unpack instructions for masks that match their pattern.
10396   if (isShuffleEquivalent(V1, V2, Mask,
10397                           {// First 128-bit lane.
10398                            0, 16, 1, 17, 4, 20, 5, 21,
10399                            // Second 128-bit lane.
10400                            8, 24, 9, 25, 12, 28, 13, 29}))
10401     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10402   if (isShuffleEquivalent(V1, V2, Mask,
10403                           {// First 128-bit lane.
10404                            2, 18, 3, 19, 6, 22, 7, 23,
10405                            // Second 128-bit lane.
10406                            10, 26, 11, 27, 14, 30, 15, 31}))
10407     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10408
10409   // FIXME: Implement direct support for this type!
10410   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10411 }
10412
10413 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10414 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10415                                        const X86Subtarget *Subtarget,
10416                                        SelectionDAG &DAG) {
10417   SDLoc DL(Op);
10418   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10419   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10420   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10421   ArrayRef<int> Mask = SVOp->getMask();
10422   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10423
10424   // X86 has dedicated unpack instructions that can handle specific blend
10425   // operations: UNPCKH and UNPCKL.
10426   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10427     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10428   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10429     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10430
10431   // FIXME: Implement direct support for this type!
10432   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10433 }
10434
10435 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10436 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10437                                        const X86Subtarget *Subtarget,
10438                                        SelectionDAG &DAG) {
10439   SDLoc DL(Op);
10440   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10441   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10442   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10443   ArrayRef<int> Mask = SVOp->getMask();
10444   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10445
10446   // Use dedicated unpack instructions for masks that match their pattern.
10447   if (isShuffleEquivalent(V1, V2, Mask,
10448                           {// First 128-bit lane.
10449                            0, 16, 1, 17, 4, 20, 5, 21,
10450                            // Second 128-bit lane.
10451                            8, 24, 9, 25, 12, 28, 13, 29}))
10452     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10453   if (isShuffleEquivalent(V1, V2, Mask,
10454                           {// First 128-bit lane.
10455                            2, 18, 3, 19, 6, 22, 7, 23,
10456                            // Second 128-bit lane.
10457                            10, 26, 11, 27, 14, 30, 15, 31}))
10458     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10459
10460   // FIXME: Implement direct support for this type!
10461   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10462 }
10463
10464 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10465 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10466                                         const X86Subtarget *Subtarget,
10467                                         SelectionDAG &DAG) {
10468   SDLoc DL(Op);
10469   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10470   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10471   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10472   ArrayRef<int> Mask = SVOp->getMask();
10473   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10474   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10475
10476   // FIXME: Implement direct support for this type!
10477   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10478 }
10479
10480 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10481 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10482                                        const X86Subtarget *Subtarget,
10483                                        SelectionDAG &DAG) {
10484   SDLoc DL(Op);
10485   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10486   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10487   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10488   ArrayRef<int> Mask = SVOp->getMask();
10489   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10490   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10491
10492   // FIXME: Implement direct support for this type!
10493   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10494 }
10495
10496 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10497 ///
10498 /// This routine either breaks down the specific type of a 512-bit x86 vector
10499 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10500 /// together based on the available instructions.
10501 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10502                                         MVT VT, const X86Subtarget *Subtarget,
10503                                         SelectionDAG &DAG) {
10504   SDLoc DL(Op);
10505   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10506   ArrayRef<int> Mask = SVOp->getMask();
10507   assert(Subtarget->hasAVX512() &&
10508          "Cannot lower 512-bit vectors w/ basic ISA!");
10509
10510   // Check for being able to broadcast a single element.
10511   if (SDValue Broadcast =
10512           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10513     return Broadcast;
10514
10515   // Dispatch to each element type for lowering. If we don't have supprot for
10516   // specific element type shuffles at 512 bits, immediately split them and
10517   // lower them. Each lowering routine of a given type is allowed to assume that
10518   // the requisite ISA extensions for that element type are available.
10519   switch (VT.SimpleTy) {
10520   case MVT::v8f64:
10521     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10522   case MVT::v16f32:
10523     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10524   case MVT::v8i64:
10525     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10526   case MVT::v16i32:
10527     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10528   case MVT::v32i16:
10529     if (Subtarget->hasBWI())
10530       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10531     break;
10532   case MVT::v64i8:
10533     if (Subtarget->hasBWI())
10534       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10535     break;
10536
10537   default:
10538     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10539   }
10540
10541   // Otherwise fall back on splitting.
10542   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10543 }
10544
10545 /// \brief Top-level lowering for x86 vector shuffles.
10546 ///
10547 /// This handles decomposition, canonicalization, and lowering of all x86
10548 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10549 /// above in helper routines. The canonicalization attempts to widen shuffles
10550 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10551 /// s.t. only one of the two inputs needs to be tested, etc.
10552 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10553                                   SelectionDAG &DAG) {
10554   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10555   ArrayRef<int> Mask = SVOp->getMask();
10556   SDValue V1 = Op.getOperand(0);
10557   SDValue V2 = Op.getOperand(1);
10558   MVT VT = Op.getSimpleValueType();
10559   int NumElements = VT.getVectorNumElements();
10560   SDLoc dl(Op);
10561
10562   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10563
10564   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10565   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10566   if (V1IsUndef && V2IsUndef)
10567     return DAG.getUNDEF(VT);
10568
10569   // When we create a shuffle node we put the UNDEF node to second operand,
10570   // but in some cases the first operand may be transformed to UNDEF.
10571   // In this case we should just commute the node.
10572   if (V1IsUndef)
10573     return DAG.getCommutedVectorShuffle(*SVOp);
10574
10575   // Check for non-undef masks pointing at an undef vector and make the masks
10576   // undef as well. This makes it easier to match the shuffle based solely on
10577   // the mask.
10578   if (V2IsUndef)
10579     for (int M : Mask)
10580       if (M >= NumElements) {
10581         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10582         for (int &M : NewMask)
10583           if (M >= NumElements)
10584             M = -1;
10585         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10586       }
10587
10588   // We actually see shuffles that are entirely re-arrangements of a set of
10589   // zero inputs. This mostly happens while decomposing complex shuffles into
10590   // simple ones. Directly lower these as a buildvector of zeros.
10591   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10592   if (Zeroable.all())
10593     return getZeroVector(VT, Subtarget, DAG, dl);
10594
10595   // Try to collapse shuffles into using a vector type with fewer elements but
10596   // wider element types. We cap this to not form integers or floating point
10597   // elements wider than 64 bits, but it might be interesting to form i128
10598   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10599   SmallVector<int, 16> WidenedMask;
10600   if (VT.getScalarSizeInBits() < 64 &&
10601       canWidenShuffleElements(Mask, WidenedMask)) {
10602     MVT NewEltVT = VT.isFloatingPoint()
10603                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10604                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10605     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10606     // Make sure that the new vector type is legal. For example, v2f64 isn't
10607     // legal on SSE1.
10608     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10609       V1 = DAG.getBitcast(NewVT, V1);
10610       V2 = DAG.getBitcast(NewVT, V2);
10611       return DAG.getBitcast(
10612           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10613     }
10614   }
10615
10616   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10617   for (int M : SVOp->getMask())
10618     if (M < 0)
10619       ++NumUndefElements;
10620     else if (M < NumElements)
10621       ++NumV1Elements;
10622     else
10623       ++NumV2Elements;
10624
10625   // Commute the shuffle as needed such that more elements come from V1 than
10626   // V2. This allows us to match the shuffle pattern strictly on how many
10627   // elements come from V1 without handling the symmetric cases.
10628   if (NumV2Elements > NumV1Elements)
10629     return DAG.getCommutedVectorShuffle(*SVOp);
10630
10631   // When the number of V1 and V2 elements are the same, try to minimize the
10632   // number of uses of V2 in the low half of the vector. When that is tied,
10633   // ensure that the sum of indices for V1 is equal to or lower than the sum
10634   // indices for V2. When those are equal, try to ensure that the number of odd
10635   // indices for V1 is lower than the number of odd indices for V2.
10636   if (NumV1Elements == NumV2Elements) {
10637     int LowV1Elements = 0, LowV2Elements = 0;
10638     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10639       if (M >= NumElements)
10640         ++LowV2Elements;
10641       else if (M >= 0)
10642         ++LowV1Elements;
10643     if (LowV2Elements > LowV1Elements) {
10644       return DAG.getCommutedVectorShuffle(*SVOp);
10645     } else if (LowV2Elements == LowV1Elements) {
10646       int SumV1Indices = 0, SumV2Indices = 0;
10647       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10648         if (SVOp->getMask()[i] >= NumElements)
10649           SumV2Indices += i;
10650         else if (SVOp->getMask()[i] >= 0)
10651           SumV1Indices += i;
10652       if (SumV2Indices < SumV1Indices) {
10653         return DAG.getCommutedVectorShuffle(*SVOp);
10654       } else if (SumV2Indices == SumV1Indices) {
10655         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10656         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10657           if (SVOp->getMask()[i] >= NumElements)
10658             NumV2OddIndices += i % 2;
10659           else if (SVOp->getMask()[i] >= 0)
10660             NumV1OddIndices += i % 2;
10661         if (NumV2OddIndices < NumV1OddIndices)
10662           return DAG.getCommutedVectorShuffle(*SVOp);
10663       }
10664     }
10665   }
10666
10667   // For each vector width, delegate to a specialized lowering routine.
10668   if (VT.getSizeInBits() == 128)
10669     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10670
10671   if (VT.getSizeInBits() == 256)
10672     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10673
10674   // Force AVX-512 vectors to be scalarized for now.
10675   // FIXME: Implement AVX-512 support!
10676   if (VT.getSizeInBits() == 512)
10677     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10678
10679   llvm_unreachable("Unimplemented!");
10680 }
10681
10682 // This function assumes its argument is a BUILD_VECTOR of constants or
10683 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10684 // true.
10685 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10686                                     unsigned &MaskValue) {
10687   MaskValue = 0;
10688   unsigned NumElems = BuildVector->getNumOperands();
10689   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10690   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10691   unsigned NumElemsInLane = NumElems / NumLanes;
10692
10693   // Blend for v16i16 should be symetric for the both lanes.
10694   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10695     SDValue EltCond = BuildVector->getOperand(i);
10696     SDValue SndLaneEltCond =
10697         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10698
10699     int Lane1Cond = -1, Lane2Cond = -1;
10700     if (isa<ConstantSDNode>(EltCond))
10701       Lane1Cond = !isZero(EltCond);
10702     if (isa<ConstantSDNode>(SndLaneEltCond))
10703       Lane2Cond = !isZero(SndLaneEltCond);
10704
10705     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10706       // Lane1Cond != 0, means we want the first argument.
10707       // Lane1Cond == 0, means we want the second argument.
10708       // The encoding of this argument is 0 for the first argument, 1
10709       // for the second. Therefore, invert the condition.
10710       MaskValue |= !Lane1Cond << i;
10711     else if (Lane1Cond < 0)
10712       MaskValue |= !Lane2Cond << i;
10713     else
10714       return false;
10715   }
10716   return true;
10717 }
10718
10719 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10720 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10721                                            const X86Subtarget *Subtarget,
10722                                            SelectionDAG &DAG) {
10723   SDValue Cond = Op.getOperand(0);
10724   SDValue LHS = Op.getOperand(1);
10725   SDValue RHS = Op.getOperand(2);
10726   SDLoc dl(Op);
10727   MVT VT = Op.getSimpleValueType();
10728
10729   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10730     return SDValue();
10731   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10732
10733   // Only non-legal VSELECTs reach this lowering, convert those into generic
10734   // shuffles and re-use the shuffle lowering path for blends.
10735   SmallVector<int, 32> Mask;
10736   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10737     SDValue CondElt = CondBV->getOperand(i);
10738     Mask.push_back(
10739         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10740   }
10741   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10742 }
10743
10744 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10745   // A vselect where all conditions and data are constants can be optimized into
10746   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10747   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10748       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10749       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10750     return SDValue();
10751
10752   // Try to lower this to a blend-style vector shuffle. This can handle all
10753   // constant condition cases.
10754   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10755     return BlendOp;
10756
10757   // Variable blends are only legal from SSE4.1 onward.
10758   if (!Subtarget->hasSSE41())
10759     return SDValue();
10760
10761   // Only some types will be legal on some subtargets. If we can emit a legal
10762   // VSELECT-matching blend, return Op, and but if we need to expand, return
10763   // a null value.
10764   switch (Op.getSimpleValueType().SimpleTy) {
10765   default:
10766     // Most of the vector types have blends past SSE4.1.
10767     return Op;
10768
10769   case MVT::v32i8:
10770     // The byte blends for AVX vectors were introduced only in AVX2.
10771     if (Subtarget->hasAVX2())
10772       return Op;
10773
10774     return SDValue();
10775
10776   case MVT::v8i16:
10777   case MVT::v16i16:
10778     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10779     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10780       return Op;
10781
10782     // FIXME: We should custom lower this by fixing the condition and using i8
10783     // blends.
10784     return SDValue();
10785   }
10786 }
10787
10788 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10789   MVT VT = Op.getSimpleValueType();
10790   SDLoc dl(Op);
10791
10792   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10793     return SDValue();
10794
10795   if (VT.getSizeInBits() == 8) {
10796     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10797                                   Op.getOperand(0), Op.getOperand(1));
10798     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10799                                   DAG.getValueType(VT));
10800     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10801   }
10802
10803   if (VT.getSizeInBits() == 16) {
10804     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10805     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10806     if (Idx == 0)
10807       return DAG.getNode(
10808           ISD::TRUNCATE, dl, MVT::i16,
10809           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10810                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10811                       Op.getOperand(1)));
10812     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10813                                   Op.getOperand(0), Op.getOperand(1));
10814     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10815                                   DAG.getValueType(VT));
10816     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10817   }
10818
10819   if (VT == MVT::f32) {
10820     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10821     // the result back to FR32 register. It's only worth matching if the
10822     // result has a single use which is a store or a bitcast to i32.  And in
10823     // the case of a store, it's not worth it if the index is a constant 0,
10824     // because a MOVSSmr can be used instead, which is smaller and faster.
10825     if (!Op.hasOneUse())
10826       return SDValue();
10827     SDNode *User = *Op.getNode()->use_begin();
10828     if ((User->getOpcode() != ISD::STORE ||
10829          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10830           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10831         (User->getOpcode() != ISD::BITCAST ||
10832          User->getValueType(0) != MVT::i32))
10833       return SDValue();
10834     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10835                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10836                                   Op.getOperand(1));
10837     return DAG.getBitcast(MVT::f32, Extract);
10838   }
10839
10840   if (VT == MVT::i32 || VT == MVT::i64) {
10841     // ExtractPS/pextrq works with constant index.
10842     if (isa<ConstantSDNode>(Op.getOperand(1)))
10843       return Op;
10844   }
10845   return SDValue();
10846 }
10847
10848 /// Extract one bit from mask vector, like v16i1 or v8i1.
10849 /// AVX-512 feature.
10850 SDValue
10851 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10852   SDValue Vec = Op.getOperand(0);
10853   SDLoc dl(Vec);
10854   MVT VecVT = Vec.getSimpleValueType();
10855   SDValue Idx = Op.getOperand(1);
10856   MVT EltVT = Op.getSimpleValueType();
10857
10858   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10859   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10860          "Unexpected vector type in ExtractBitFromMaskVector");
10861
10862   // variable index can't be handled in mask registers,
10863   // extend vector to VR512
10864   if (!isa<ConstantSDNode>(Idx)) {
10865     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10866     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10867     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10868                               ExtVT.getVectorElementType(), Ext, Idx);
10869     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10870   }
10871
10872   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10873   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10874   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10875     rc = getRegClassFor(MVT::v16i1);
10876   unsigned MaxSift = rc->getSize()*8 - 1;
10877   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10878                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10879   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10880                     DAG.getConstant(MaxSift, dl, MVT::i8));
10881   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10882                        DAG.getIntPtrConstant(0, dl));
10883 }
10884
10885 SDValue
10886 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10887                                            SelectionDAG &DAG) const {
10888   SDLoc dl(Op);
10889   SDValue Vec = Op.getOperand(0);
10890   MVT VecVT = Vec.getSimpleValueType();
10891   SDValue Idx = Op.getOperand(1);
10892
10893   if (Op.getSimpleValueType() == MVT::i1)
10894     return ExtractBitFromMaskVector(Op, DAG);
10895
10896   if (!isa<ConstantSDNode>(Idx)) {
10897     if (VecVT.is512BitVector() ||
10898         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10899          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10900
10901       MVT MaskEltVT =
10902         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10903       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10904                                     MaskEltVT.getSizeInBits());
10905
10906       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10907       auto PtrVT = getPointerTy(DAG.getDataLayout());
10908       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10909                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10910                                  DAG.getConstant(0, dl, PtrVT));
10911       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10912       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10913                          DAG.getConstant(0, dl, PtrVT));
10914     }
10915     return SDValue();
10916   }
10917
10918   // If this is a 256-bit vector result, first extract the 128-bit vector and
10919   // then extract the element from the 128-bit vector.
10920   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10921
10922     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10923     // Get the 128-bit vector.
10924     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10925     MVT EltVT = VecVT.getVectorElementType();
10926
10927     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10928
10929     //if (IdxVal >= NumElems/2)
10930     //  IdxVal -= NumElems/2;
10931     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10932     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10933                        DAG.getConstant(IdxVal, dl, MVT::i32));
10934   }
10935
10936   assert(VecVT.is128BitVector() && "Unexpected vector length");
10937
10938   if (Subtarget->hasSSE41())
10939     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10940       return Res;
10941
10942   MVT VT = Op.getSimpleValueType();
10943   // TODO: handle v16i8.
10944   if (VT.getSizeInBits() == 16) {
10945     SDValue Vec = Op.getOperand(0);
10946     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10947     if (Idx == 0)
10948       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10949                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10950                                      DAG.getBitcast(MVT::v4i32, Vec),
10951                                      Op.getOperand(1)));
10952     // Transform it so it match pextrw which produces a 32-bit result.
10953     MVT EltVT = MVT::i32;
10954     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10955                                   Op.getOperand(0), Op.getOperand(1));
10956     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10957                                   DAG.getValueType(VT));
10958     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10959   }
10960
10961   if (VT.getSizeInBits() == 32) {
10962     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10963     if (Idx == 0)
10964       return Op;
10965
10966     // SHUFPS the element to the lowest double word, then movss.
10967     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10968     MVT VVT = Op.getOperand(0).getSimpleValueType();
10969     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10970                                        DAG.getUNDEF(VVT), Mask);
10971     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10972                        DAG.getIntPtrConstant(0, dl));
10973   }
10974
10975   if (VT.getSizeInBits() == 64) {
10976     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10977     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10978     //        to match extract_elt for f64.
10979     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10980     if (Idx == 0)
10981       return Op;
10982
10983     // UNPCKHPD the element to the lowest double word, then movsd.
10984     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10985     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10986     int Mask[2] = { 1, -1 };
10987     MVT VVT = Op.getOperand(0).getSimpleValueType();
10988     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10989                                        DAG.getUNDEF(VVT), Mask);
10990     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10991                        DAG.getIntPtrConstant(0, dl));
10992   }
10993
10994   return SDValue();
10995 }
10996
10997 /// Insert one bit to mask vector, like v16i1 or v8i1.
10998 /// AVX-512 feature.
10999 SDValue
11000 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
11001   SDLoc dl(Op);
11002   SDValue Vec = Op.getOperand(0);
11003   SDValue Elt = Op.getOperand(1);
11004   SDValue Idx = Op.getOperand(2);
11005   MVT VecVT = Vec.getSimpleValueType();
11006
11007   if (!isa<ConstantSDNode>(Idx)) {
11008     // Non constant index. Extend source and destination,
11009     // insert element and then truncate the result.
11010     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
11011     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
11012     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
11013       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
11014       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
11015     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
11016   }
11017
11018   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11019   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
11020   if (IdxVal)
11021     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
11022                            DAG.getConstant(IdxVal, dl, MVT::i8));
11023   if (Vec.getOpcode() == ISD::UNDEF)
11024     return EltInVec;
11025   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11026 }
11027
11028 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11029                                                   SelectionDAG &DAG) const {
11030   MVT VT = Op.getSimpleValueType();
11031   MVT EltVT = VT.getVectorElementType();
11032
11033   if (EltVT == MVT::i1)
11034     return InsertBitToMaskVector(Op, DAG);
11035
11036   SDLoc dl(Op);
11037   SDValue N0 = Op.getOperand(0);
11038   SDValue N1 = Op.getOperand(1);
11039   SDValue N2 = Op.getOperand(2);
11040   if (!isa<ConstantSDNode>(N2))
11041     return SDValue();
11042   auto *N2C = cast<ConstantSDNode>(N2);
11043   unsigned IdxVal = N2C->getZExtValue();
11044
11045   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11046   // into that, and then insert the subvector back into the result.
11047   if (VT.is256BitVector() || VT.is512BitVector()) {
11048     // With a 256-bit vector, we can insert into the zero element efficiently
11049     // using a blend if we have AVX or AVX2 and the right data type.
11050     if (VT.is256BitVector() && IdxVal == 0) {
11051       // TODO: It is worthwhile to cast integer to floating point and back
11052       // and incur a domain crossing penalty if that's what we'll end up
11053       // doing anyway after extracting to a 128-bit vector.
11054       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11055           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11056         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11057         N2 = DAG.getIntPtrConstant(1, dl);
11058         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11059       }
11060     }
11061
11062     // Get the desired 128-bit vector chunk.
11063     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11064
11065     // Insert the element into the desired chunk.
11066     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11067     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11068
11069     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11070                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11071
11072     // Insert the changed part back into the bigger vector
11073     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11074   }
11075   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11076
11077   if (Subtarget->hasSSE41()) {
11078     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11079       unsigned Opc;
11080       if (VT == MVT::v8i16) {
11081         Opc = X86ISD::PINSRW;
11082       } else {
11083         assert(VT == MVT::v16i8);
11084         Opc = X86ISD::PINSRB;
11085       }
11086
11087       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11088       // argument.
11089       if (N1.getValueType() != MVT::i32)
11090         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11091       if (N2.getValueType() != MVT::i32)
11092         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11093       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11094     }
11095
11096     if (EltVT == MVT::f32) {
11097       // Bits [7:6] of the constant are the source select. This will always be
11098       //   zero here. The DAG Combiner may combine an extract_elt index into
11099       //   these bits. For example (insert (extract, 3), 2) could be matched by
11100       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11101       // Bits [5:4] of the constant are the destination select. This is the
11102       //   value of the incoming immediate.
11103       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11104       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11105
11106       const Function *F = DAG.getMachineFunction().getFunction();
11107       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11108       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11109         // If this is an insertion of 32-bits into the low 32-bits of
11110         // a vector, we prefer to generate a blend with immediate rather
11111         // than an insertps. Blends are simpler operations in hardware and so
11112         // will always have equal or better performance than insertps.
11113         // But if optimizing for size and there's a load folding opportunity,
11114         // generate insertps because blendps does not have a 32-bit memory
11115         // operand form.
11116         N2 = DAG.getIntPtrConstant(1, dl);
11117         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11118         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11119       }
11120       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11121       // Create this as a scalar to vector..
11122       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11123       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11124     }
11125
11126     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11127       // PINSR* works with constant index.
11128       return Op;
11129     }
11130   }
11131
11132   if (EltVT == MVT::i8)
11133     return SDValue();
11134
11135   if (EltVT.getSizeInBits() == 16) {
11136     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11137     // as its second argument.
11138     if (N1.getValueType() != MVT::i32)
11139       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11140     if (N2.getValueType() != MVT::i32)
11141       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11142     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11143   }
11144   return SDValue();
11145 }
11146
11147 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11148   SDLoc dl(Op);
11149   MVT OpVT = Op.getSimpleValueType();
11150
11151   // If this is a 256-bit vector result, first insert into a 128-bit
11152   // vector and then insert into the 256-bit vector.
11153   if (!OpVT.is128BitVector()) {
11154     // Insert into a 128-bit vector.
11155     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11156     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11157                                  OpVT.getVectorNumElements() / SizeFactor);
11158
11159     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11160
11161     // Insert the 128-bit vector.
11162     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11163   }
11164
11165   if (OpVT == MVT::v1i64 &&
11166       Op.getOperand(0).getValueType() == MVT::i64)
11167     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11168
11169   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11170   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11171   return DAG.getBitcast(
11172       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11173 }
11174
11175 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11176 // a simple subregister reference or explicit instructions to grab
11177 // upper bits of a vector.
11178 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11179                                       SelectionDAG &DAG) {
11180   SDLoc dl(Op);
11181   SDValue In =  Op.getOperand(0);
11182   SDValue Idx = Op.getOperand(1);
11183   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11184   MVT ResVT   = Op.getSimpleValueType();
11185   MVT InVT    = In.getSimpleValueType();
11186
11187   if (Subtarget->hasFp256()) {
11188     if (ResVT.is128BitVector() &&
11189         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11190         isa<ConstantSDNode>(Idx)) {
11191       return Extract128BitVector(In, IdxVal, DAG, dl);
11192     }
11193     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11194         isa<ConstantSDNode>(Idx)) {
11195       return Extract256BitVector(In, IdxVal, DAG, dl);
11196     }
11197   }
11198   return SDValue();
11199 }
11200
11201 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11202 // simple superregister reference or explicit instructions to insert
11203 // the upper bits of a vector.
11204 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11205                                      SelectionDAG &DAG) {
11206   if (!Subtarget->hasAVX())
11207     return SDValue();
11208
11209   SDLoc dl(Op);
11210   SDValue Vec = Op.getOperand(0);
11211   SDValue SubVec = Op.getOperand(1);
11212   SDValue Idx = Op.getOperand(2);
11213
11214   if (!isa<ConstantSDNode>(Idx))
11215     return SDValue();
11216
11217   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11218   MVT OpVT = Op.getSimpleValueType();
11219   MVT SubVecVT = SubVec.getSimpleValueType();
11220
11221   // Fold two 16-byte subvector loads into one 32-byte load:
11222   // (insert_subvector (insert_subvector undef, (load addr), 0),
11223   //                   (load addr + 16), Elts/2)
11224   // --> load32 addr
11225   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11226       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11227       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11228       !Subtarget->isUnalignedMem32Slow()) {
11229     SDValue SubVec2 = Vec.getOperand(1);
11230     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11231       if (Idx2->getZExtValue() == 0) {
11232         SDValue Ops[] = { SubVec2, SubVec };
11233         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11234           return Ld;
11235       }
11236     }
11237   }
11238
11239   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11240       SubVecVT.is128BitVector())
11241     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11242
11243   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11244     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11245
11246   if (OpVT.getVectorElementType() == MVT::i1) {
11247     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11248       return Op;
11249     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11250     SDValue Undef = DAG.getUNDEF(OpVT);
11251     unsigned NumElems = OpVT.getVectorNumElements();
11252     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11253
11254     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11255       // Zero upper bits of the Vec
11256       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11257       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11258
11259       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11260                                  SubVec, ZeroIdx);
11261       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11262       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11263     }
11264     if (IdxVal == 0) {
11265       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11266                                  SubVec, ZeroIdx);
11267       // Zero upper bits of the Vec2
11268       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11269       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11270       // Zero lower bits of the Vec
11271       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11272       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11273       // Merge them together
11274       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11275     }
11276   }
11277   return SDValue();
11278 }
11279
11280 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11281 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11282 // one of the above mentioned nodes. It has to be wrapped because otherwise
11283 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11284 // be used to form addressing mode. These wrapped nodes will be selected
11285 // into MOV32ri.
11286 SDValue
11287 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11288   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11289
11290   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11291   // global base reg.
11292   unsigned char OpFlag = 0;
11293   unsigned WrapperKind = X86ISD::Wrapper;
11294   CodeModel::Model M = DAG.getTarget().getCodeModel();
11295
11296   if (Subtarget->isPICStyleRIPRel() &&
11297       (M == CodeModel::Small || M == CodeModel::Kernel))
11298     WrapperKind = X86ISD::WrapperRIP;
11299   else if (Subtarget->isPICStyleGOT())
11300     OpFlag = X86II::MO_GOTOFF;
11301   else if (Subtarget->isPICStyleStubPIC())
11302     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11303
11304   auto PtrVT = getPointerTy(DAG.getDataLayout());
11305   SDValue Result = DAG.getTargetConstantPool(
11306       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11307   SDLoc DL(CP);
11308   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11309   // With PIC, the address is actually $g + Offset.
11310   if (OpFlag) {
11311     Result =
11312         DAG.getNode(ISD::ADD, DL, PtrVT,
11313                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11314   }
11315
11316   return Result;
11317 }
11318
11319 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11320   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11321
11322   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11323   // global base reg.
11324   unsigned char OpFlag = 0;
11325   unsigned WrapperKind = X86ISD::Wrapper;
11326   CodeModel::Model M = DAG.getTarget().getCodeModel();
11327
11328   if (Subtarget->isPICStyleRIPRel() &&
11329       (M == CodeModel::Small || M == CodeModel::Kernel))
11330     WrapperKind = X86ISD::WrapperRIP;
11331   else if (Subtarget->isPICStyleGOT())
11332     OpFlag = X86II::MO_GOTOFF;
11333   else if (Subtarget->isPICStyleStubPIC())
11334     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11335
11336   auto PtrVT = getPointerTy(DAG.getDataLayout());
11337   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11338   SDLoc DL(JT);
11339   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11340
11341   // With PIC, the address is actually $g + Offset.
11342   if (OpFlag)
11343     Result =
11344         DAG.getNode(ISD::ADD, DL, PtrVT,
11345                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11346
11347   return Result;
11348 }
11349
11350 SDValue
11351 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11352   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11353
11354   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11355   // global base reg.
11356   unsigned char OpFlag = 0;
11357   unsigned WrapperKind = X86ISD::Wrapper;
11358   CodeModel::Model M = DAG.getTarget().getCodeModel();
11359
11360   if (Subtarget->isPICStyleRIPRel() &&
11361       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11362     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11363       OpFlag = X86II::MO_GOTPCREL;
11364     WrapperKind = X86ISD::WrapperRIP;
11365   } else if (Subtarget->isPICStyleGOT()) {
11366     OpFlag = X86II::MO_GOT;
11367   } else if (Subtarget->isPICStyleStubPIC()) {
11368     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11369   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11370     OpFlag = X86II::MO_DARWIN_NONLAZY;
11371   }
11372
11373   auto PtrVT = getPointerTy(DAG.getDataLayout());
11374   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11375
11376   SDLoc DL(Op);
11377   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11378
11379   // With PIC, the address is actually $g + Offset.
11380   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11381       !Subtarget->is64Bit()) {
11382     Result =
11383         DAG.getNode(ISD::ADD, DL, PtrVT,
11384                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11385   }
11386
11387   // For symbols that require a load from a stub to get the address, emit the
11388   // load.
11389   if (isGlobalStubReference(OpFlag))
11390     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11391                          MachinePointerInfo::getGOT(), false, false, false, 0);
11392
11393   return Result;
11394 }
11395
11396 SDValue
11397 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11398   // Create the TargetBlockAddressAddress node.
11399   unsigned char OpFlags =
11400     Subtarget->ClassifyBlockAddressReference();
11401   CodeModel::Model M = DAG.getTarget().getCodeModel();
11402   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11403   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11404   SDLoc dl(Op);
11405   auto PtrVT = getPointerTy(DAG.getDataLayout());
11406   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11407
11408   if (Subtarget->isPICStyleRIPRel() &&
11409       (M == CodeModel::Small || M == CodeModel::Kernel))
11410     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11411   else
11412     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11413
11414   // With PIC, the address is actually $g + Offset.
11415   if (isGlobalRelativeToPICBase(OpFlags)) {
11416     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11417                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11418   }
11419
11420   return Result;
11421 }
11422
11423 SDValue
11424 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11425                                       int64_t Offset, SelectionDAG &DAG) const {
11426   // Create the TargetGlobalAddress node, folding in the constant
11427   // offset if it is legal.
11428   unsigned char OpFlags =
11429       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11430   CodeModel::Model M = DAG.getTarget().getCodeModel();
11431   auto PtrVT = getPointerTy(DAG.getDataLayout());
11432   SDValue Result;
11433   if (OpFlags == X86II::MO_NO_FLAG &&
11434       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11435     // A direct static reference to a global.
11436     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11437     Offset = 0;
11438   } else {
11439     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11440   }
11441
11442   if (Subtarget->isPICStyleRIPRel() &&
11443       (M == CodeModel::Small || M == CodeModel::Kernel))
11444     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11445   else
11446     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11447
11448   // With PIC, the address is actually $g + Offset.
11449   if (isGlobalRelativeToPICBase(OpFlags)) {
11450     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11451                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11452   }
11453
11454   // For globals that require a load from a stub to get the address, emit the
11455   // load.
11456   if (isGlobalStubReference(OpFlags))
11457     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11458                          MachinePointerInfo::getGOT(), false, false, false, 0);
11459
11460   // If there was a non-zero offset that we didn't fold, create an explicit
11461   // addition for it.
11462   if (Offset != 0)
11463     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11464                          DAG.getConstant(Offset, dl, PtrVT));
11465
11466   return Result;
11467 }
11468
11469 SDValue
11470 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11471   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11472   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11473   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11474 }
11475
11476 static SDValue
11477 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11478            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11479            unsigned char OperandFlags, bool LocalDynamic = false) {
11480   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11481   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11482   SDLoc dl(GA);
11483   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11484                                            GA->getValueType(0),
11485                                            GA->getOffset(),
11486                                            OperandFlags);
11487
11488   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11489                                            : X86ISD::TLSADDR;
11490
11491   if (InFlag) {
11492     SDValue Ops[] = { Chain,  TGA, *InFlag };
11493     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11494   } else {
11495     SDValue Ops[]  = { Chain, TGA };
11496     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11497   }
11498
11499   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11500   MFI->setAdjustsStack(true);
11501   MFI->setHasCalls(true);
11502
11503   SDValue Flag = Chain.getValue(1);
11504   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11505 }
11506
11507 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11508 static SDValue
11509 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11510                                 const EVT PtrVT) {
11511   SDValue InFlag;
11512   SDLoc dl(GA);  // ? function entry point might be better
11513   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11514                                    DAG.getNode(X86ISD::GlobalBaseReg,
11515                                                SDLoc(), PtrVT), InFlag);
11516   InFlag = Chain.getValue(1);
11517
11518   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11519 }
11520
11521 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11522 static SDValue
11523 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11524                                 const EVT PtrVT) {
11525   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11526                     X86::RAX, X86II::MO_TLSGD);
11527 }
11528
11529 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11530                                            SelectionDAG &DAG,
11531                                            const EVT PtrVT,
11532                                            bool is64Bit) {
11533   SDLoc dl(GA);
11534
11535   // Get the start address of the TLS block for this module.
11536   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11537       .getInfo<X86MachineFunctionInfo>();
11538   MFI->incNumLocalDynamicTLSAccesses();
11539
11540   SDValue Base;
11541   if (is64Bit) {
11542     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11543                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11544   } else {
11545     SDValue InFlag;
11546     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11547         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11548     InFlag = Chain.getValue(1);
11549     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11550                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11551   }
11552
11553   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11554   // of Base.
11555
11556   // Build x@dtpoff.
11557   unsigned char OperandFlags = X86II::MO_DTPOFF;
11558   unsigned WrapperKind = X86ISD::Wrapper;
11559   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11560                                            GA->getValueType(0),
11561                                            GA->getOffset(), OperandFlags);
11562   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11563
11564   // Add x@dtpoff with the base.
11565   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11566 }
11567
11568 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11569 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11570                                    const EVT PtrVT, TLSModel::Model model,
11571                                    bool is64Bit, bool isPIC) {
11572   SDLoc dl(GA);
11573
11574   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11575   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11576                                                          is64Bit ? 257 : 256));
11577
11578   SDValue ThreadPointer =
11579       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11580                   MachinePointerInfo(Ptr), false, false, false, 0);
11581
11582   unsigned char OperandFlags = 0;
11583   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11584   // initialexec.
11585   unsigned WrapperKind = X86ISD::Wrapper;
11586   if (model == TLSModel::LocalExec) {
11587     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11588   } else if (model == TLSModel::InitialExec) {
11589     if (is64Bit) {
11590       OperandFlags = X86II::MO_GOTTPOFF;
11591       WrapperKind = X86ISD::WrapperRIP;
11592     } else {
11593       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11594     }
11595   } else {
11596     llvm_unreachable("Unexpected model");
11597   }
11598
11599   // emit "addl x@ntpoff,%eax" (local exec)
11600   // or "addl x@indntpoff,%eax" (initial exec)
11601   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11602   SDValue TGA =
11603       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11604                                  GA->getOffset(), OperandFlags);
11605   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11606
11607   if (model == TLSModel::InitialExec) {
11608     if (isPIC && !is64Bit) {
11609       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11610                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11611                            Offset);
11612     }
11613
11614     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11615                          MachinePointerInfo::getGOT(), false, false, false, 0);
11616   }
11617
11618   // The address of the thread local variable is the add of the thread
11619   // pointer with the offset of the variable.
11620   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11621 }
11622
11623 SDValue
11624 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11625
11626   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11627   const GlobalValue *GV = GA->getGlobal();
11628   auto PtrVT = getPointerTy(DAG.getDataLayout());
11629
11630   if (Subtarget->isTargetELF()) {
11631     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11632     switch (model) {
11633       case TLSModel::GeneralDynamic:
11634         if (Subtarget->is64Bit())
11635           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11636         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11637       case TLSModel::LocalDynamic:
11638         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11639                                            Subtarget->is64Bit());
11640       case TLSModel::InitialExec:
11641       case TLSModel::LocalExec:
11642         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11643                                    DAG.getTarget().getRelocationModel() ==
11644                                        Reloc::PIC_);
11645     }
11646     llvm_unreachable("Unknown TLS model.");
11647   }
11648
11649   if (Subtarget->isTargetDarwin()) {
11650     // Darwin only has one model of TLS.  Lower to that.
11651     unsigned char OpFlag = 0;
11652     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11653                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11654
11655     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11656     // global base reg.
11657     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11658                  !Subtarget->is64Bit();
11659     if (PIC32)
11660       OpFlag = X86II::MO_TLVP_PIC_BASE;
11661     else
11662       OpFlag = X86II::MO_TLVP;
11663     SDLoc DL(Op);
11664     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11665                                                 GA->getValueType(0),
11666                                                 GA->getOffset(), OpFlag);
11667     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11668
11669     // With PIC32, the address is actually $g + Offset.
11670     if (PIC32)
11671       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11672                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11673                            Offset);
11674
11675     // Lowering the machine isd will make sure everything is in the right
11676     // location.
11677     SDValue Chain = DAG.getEntryNode();
11678     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11679     SDValue Args[] = { Chain, Offset };
11680     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11681
11682     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11683     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11684     MFI->setAdjustsStack(true);
11685
11686     // And our return value (tls address) is in the standard call return value
11687     // location.
11688     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11689     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11690   }
11691
11692   if (Subtarget->isTargetKnownWindowsMSVC() ||
11693       Subtarget->isTargetWindowsGNU()) {
11694     // Just use the implicit TLS architecture
11695     // Need to generate someting similar to:
11696     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11697     //                                  ; from TEB
11698     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11699     //   mov     rcx, qword [rdx+rcx*8]
11700     //   mov     eax, .tls$:tlsvar
11701     //   [rax+rcx] contains the address
11702     // Windows 64bit: gs:0x58
11703     // Windows 32bit: fs:__tls_array
11704
11705     SDLoc dl(GA);
11706     SDValue Chain = DAG.getEntryNode();
11707
11708     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11709     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11710     // use its literal value of 0x2C.
11711     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11712                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11713                                                              256)
11714                                         : Type::getInt32PtrTy(*DAG.getContext(),
11715                                                               257));
11716
11717     SDValue TlsArray = Subtarget->is64Bit()
11718                            ? DAG.getIntPtrConstant(0x58, dl)
11719                            : (Subtarget->isTargetWindowsGNU()
11720                                   ? DAG.getIntPtrConstant(0x2C, dl)
11721                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11722
11723     SDValue ThreadPointer =
11724         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11725                     false, false, 0);
11726
11727     SDValue res;
11728     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11729       res = ThreadPointer;
11730     } else {
11731       // Load the _tls_index variable
11732       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11733       if (Subtarget->is64Bit())
11734         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11735                              MachinePointerInfo(), MVT::i32, false, false,
11736                              false, 0);
11737       else
11738         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11739                           false, false, 0);
11740
11741       auto &DL = DAG.getDataLayout();
11742       SDValue Scale =
11743           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11744       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11745
11746       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11747     }
11748
11749     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11750                       false, 0);
11751
11752     // Get the offset of start of .tls section
11753     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11754                                              GA->getValueType(0),
11755                                              GA->getOffset(), X86II::MO_SECREL);
11756     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11757
11758     // The address of the thread local variable is the add of the thread
11759     // pointer with the offset of the variable.
11760     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11761   }
11762
11763   llvm_unreachable("TLS not implemented for this target.");
11764 }
11765
11766 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11767 /// and take a 2 x i32 value to shift plus a shift amount.
11768 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11769   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11770   MVT VT = Op.getSimpleValueType();
11771   unsigned VTBits = VT.getSizeInBits();
11772   SDLoc dl(Op);
11773   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11774   SDValue ShOpLo = Op.getOperand(0);
11775   SDValue ShOpHi = Op.getOperand(1);
11776   SDValue ShAmt  = Op.getOperand(2);
11777   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11778   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11779   // during isel.
11780   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11781                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11782   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11783                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11784                        : DAG.getConstant(0, dl, VT);
11785
11786   SDValue Tmp2, Tmp3;
11787   if (Op.getOpcode() == ISD::SHL_PARTS) {
11788     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11789     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11790   } else {
11791     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11792     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11793   }
11794
11795   // If the shift amount is larger or equal than the width of a part we can't
11796   // rely on the results of shld/shrd. Insert a test and select the appropriate
11797   // values for large shift amounts.
11798   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11799                                 DAG.getConstant(VTBits, dl, MVT::i8));
11800   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11801                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11802
11803   SDValue Hi, Lo;
11804   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11805   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11806   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11807
11808   if (Op.getOpcode() == ISD::SHL_PARTS) {
11809     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11810     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11811   } else {
11812     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11813     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11814   }
11815
11816   SDValue Ops[2] = { Lo, Hi };
11817   return DAG.getMergeValues(Ops, dl);
11818 }
11819
11820 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11821                                            SelectionDAG &DAG) const {
11822   SDValue Src = Op.getOperand(0);
11823   MVT SrcVT = Src.getSimpleValueType();
11824   MVT VT = Op.getSimpleValueType();
11825   SDLoc dl(Op);
11826
11827   if (SrcVT.isVector()) {
11828     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11829       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11830                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11831                          DAG.getUNDEF(SrcVT)));
11832     }
11833     if (SrcVT.getVectorElementType() == MVT::i1) {
11834       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11835       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11836                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11837     }
11838     return SDValue();
11839   }
11840
11841   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11842          "Unknown SINT_TO_FP to lower!");
11843
11844   // These are really Legal; return the operand so the caller accepts it as
11845   // Legal.
11846   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11847     return Op;
11848   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11849       Subtarget->is64Bit()) {
11850     return Op;
11851   }
11852
11853   unsigned Size = SrcVT.getSizeInBits()/8;
11854   MachineFunction &MF = DAG.getMachineFunction();
11855   auto PtrVT = getPointerTy(MF.getDataLayout());
11856   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11857   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11858   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11859                                StackSlot,
11860                                MachinePointerInfo::getFixedStack(SSFI),
11861                                false, false, 0);
11862   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11863 }
11864
11865 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11866                                      SDValue StackSlot,
11867                                      SelectionDAG &DAG) const {
11868   // Build the FILD
11869   SDLoc DL(Op);
11870   SDVTList Tys;
11871   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11872   if (useSSE)
11873     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11874   else
11875     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11876
11877   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11878
11879   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11880   MachineMemOperand *MMO;
11881   if (FI) {
11882     int SSFI = FI->getIndex();
11883     MMO =
11884       DAG.getMachineFunction()
11885       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11886                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11887   } else {
11888     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11889     StackSlot = StackSlot.getOperand(1);
11890   }
11891   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11892   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11893                                            X86ISD::FILD, DL,
11894                                            Tys, Ops, SrcVT, MMO);
11895
11896   if (useSSE) {
11897     Chain = Result.getValue(1);
11898     SDValue InFlag = Result.getValue(2);
11899
11900     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11901     // shouldn't be necessary except that RFP cannot be live across
11902     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11903     MachineFunction &MF = DAG.getMachineFunction();
11904     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11905     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11906     auto PtrVT = getPointerTy(MF.getDataLayout());
11907     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11908     Tys = DAG.getVTList(MVT::Other);
11909     SDValue Ops[] = {
11910       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11911     };
11912     MachineMemOperand *MMO =
11913       DAG.getMachineFunction()
11914       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11915                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11916
11917     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11918                                     Ops, Op.getValueType(), MMO);
11919     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11920                          MachinePointerInfo::getFixedStack(SSFI),
11921                          false, false, false, 0);
11922   }
11923
11924   return Result;
11925 }
11926
11927 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11928 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11929                                                SelectionDAG &DAG) const {
11930   // This algorithm is not obvious. Here it is what we're trying to output:
11931   /*
11932      movq       %rax,  %xmm0
11933      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11934      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11935      #ifdef __SSE3__
11936        haddpd   %xmm0, %xmm0
11937      #else
11938        pshufd   $0x4e, %xmm0, %xmm1
11939        addpd    %xmm1, %xmm0
11940      #endif
11941   */
11942
11943   SDLoc dl(Op);
11944   LLVMContext *Context = DAG.getContext();
11945
11946   // Build some magic constants.
11947   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11948   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11949   auto PtrVT = getPointerTy(DAG.getDataLayout());
11950   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11951
11952   SmallVector<Constant*,2> CV1;
11953   CV1.push_back(
11954     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11955                                       APInt(64, 0x4330000000000000ULL))));
11956   CV1.push_back(
11957     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11958                                       APInt(64, 0x4530000000000000ULL))));
11959   Constant *C1 = ConstantVector::get(CV1);
11960   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11961
11962   // Load the 64-bit value into an XMM register.
11963   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11964                             Op.getOperand(0));
11965   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11966                               MachinePointerInfo::getConstantPool(),
11967                               false, false, false, 16);
11968   SDValue Unpck1 =
11969       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11970
11971   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11972                               MachinePointerInfo::getConstantPool(),
11973                               false, false, false, 16);
11974   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11975   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11976   SDValue Result;
11977
11978   if (Subtarget->hasSSE3()) {
11979     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11980     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11981   } else {
11982     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11983     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11984                                            S2F, 0x4E, DAG);
11985     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11986                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11987   }
11988
11989   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11990                      DAG.getIntPtrConstant(0, dl));
11991 }
11992
11993 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11994 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11995                                                SelectionDAG &DAG) const {
11996   SDLoc dl(Op);
11997   // FP constant to bias correct the final result.
11998   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11999                                    MVT::f64);
12000
12001   // Load the 32-bit value into an XMM register.
12002   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
12003                              Op.getOperand(0));
12004
12005   // Zero out the upper parts of the register.
12006   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
12007
12008   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12009                      DAG.getBitcast(MVT::v2f64, Load),
12010                      DAG.getIntPtrConstant(0, dl));
12011
12012   // Or the load with the bias.
12013   SDValue Or = DAG.getNode(
12014       ISD::OR, dl, MVT::v2i64,
12015       DAG.getBitcast(MVT::v2i64,
12016                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
12017       DAG.getBitcast(MVT::v2i64,
12018                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
12019   Or =
12020       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
12021                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
12022
12023   // Subtract the bias.
12024   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12025
12026   // Handle final rounding.
12027   EVT DestVT = Op.getValueType();
12028
12029   if (DestVT.bitsLT(MVT::f64))
12030     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12031                        DAG.getIntPtrConstant(0, dl));
12032   if (DestVT.bitsGT(MVT::f64))
12033     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12034
12035   // Handle final rounding.
12036   return Sub;
12037 }
12038
12039 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12040                                      const X86Subtarget &Subtarget) {
12041   // The algorithm is the following:
12042   // #ifdef __SSE4_1__
12043   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12044   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12045   //                                 (uint4) 0x53000000, 0xaa);
12046   // #else
12047   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12048   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12049   // #endif
12050   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12051   //     return (float4) lo + fhi;
12052
12053   SDLoc DL(Op);
12054   SDValue V = Op->getOperand(0);
12055   EVT VecIntVT = V.getValueType();
12056   bool Is128 = VecIntVT == MVT::v4i32;
12057   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12058   // If we convert to something else than the supported type, e.g., to v4f64,
12059   // abort early.
12060   if (VecFloatVT != Op->getValueType(0))
12061     return SDValue();
12062
12063   unsigned NumElts = VecIntVT.getVectorNumElements();
12064   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12065          "Unsupported custom type");
12066   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12067
12068   // In the #idef/#else code, we have in common:
12069   // - The vector of constants:
12070   // -- 0x4b000000
12071   // -- 0x53000000
12072   // - A shift:
12073   // -- v >> 16
12074
12075   // Create the splat vector for 0x4b000000.
12076   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12077   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12078                            CstLow, CstLow, CstLow, CstLow};
12079   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12080                                   makeArrayRef(&CstLowArray[0], NumElts));
12081   // Create the splat vector for 0x53000000.
12082   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12083   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12084                             CstHigh, CstHigh, CstHigh, CstHigh};
12085   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12086                                    makeArrayRef(&CstHighArray[0], NumElts));
12087
12088   // Create the right shift.
12089   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12090   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12091                              CstShift, CstShift, CstShift, CstShift};
12092   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12093                                     makeArrayRef(&CstShiftArray[0], NumElts));
12094   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12095
12096   SDValue Low, High;
12097   if (Subtarget.hasSSE41()) {
12098     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12099     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12100     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12101     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12102     // Low will be bitcasted right away, so do not bother bitcasting back to its
12103     // original type.
12104     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12105                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12106     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12107     //                                 (uint4) 0x53000000, 0xaa);
12108     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12109     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12110     // High will be bitcasted right away, so do not bother bitcasting back to
12111     // its original type.
12112     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12113                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12114   } else {
12115     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12116     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12117                                      CstMask, CstMask, CstMask);
12118     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12119     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12120     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12121
12122     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12123     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12124   }
12125
12126   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12127   SDValue CstFAdd = DAG.getConstantFP(
12128       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12129   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12130                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12131   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12132                                    makeArrayRef(&CstFAddArray[0], NumElts));
12133
12134   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12135   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12136   SDValue FHigh =
12137       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12138   //     return (float4) lo + fhi;
12139   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12140   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12141 }
12142
12143 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12144                                                SelectionDAG &DAG) const {
12145   SDValue N0 = Op.getOperand(0);
12146   MVT SVT = N0.getSimpleValueType();
12147   SDLoc dl(Op);
12148
12149   switch (SVT.SimpleTy) {
12150   default:
12151     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12152   case MVT::v4i8:
12153   case MVT::v4i16:
12154   case MVT::v8i8:
12155   case MVT::v8i16: {
12156     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12157     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12158                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12159   }
12160   case MVT::v4i32:
12161   case MVT::v8i32:
12162     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12163   case MVT::v16i8:
12164   case MVT::v16i16:
12165     if (Subtarget->hasAVX512())
12166       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12167                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12168   }
12169   llvm_unreachable(nullptr);
12170 }
12171
12172 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12173                                            SelectionDAG &DAG) const {
12174   SDValue N0 = Op.getOperand(0);
12175   SDLoc dl(Op);
12176   auto PtrVT = getPointerTy(DAG.getDataLayout());
12177
12178   if (Op.getValueType().isVector())
12179     return lowerUINT_TO_FP_vec(Op, DAG);
12180
12181   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12182   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12183   // the optimization here.
12184   if (DAG.SignBitIsZero(N0))
12185     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12186
12187   MVT SrcVT = N0.getSimpleValueType();
12188   MVT DstVT = Op.getSimpleValueType();
12189   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12190     return LowerUINT_TO_FP_i64(Op, DAG);
12191   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12192     return LowerUINT_TO_FP_i32(Op, DAG);
12193   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12194     return SDValue();
12195
12196   // Make a 64-bit buffer, and use it to build an FILD.
12197   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12198   if (SrcVT == MVT::i32) {
12199     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12200     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12201     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12202                                   StackSlot, MachinePointerInfo(),
12203                                   false, false, 0);
12204     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12205                                   OffsetSlot, MachinePointerInfo(),
12206                                   false, false, 0);
12207     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12208     return Fild;
12209   }
12210
12211   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12212   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12213                                StackSlot, MachinePointerInfo(),
12214                                false, false, 0);
12215   // For i64 source, we need to add the appropriate power of 2 if the input
12216   // was negative.  This is the same as the optimization in
12217   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12218   // we must be careful to do the computation in x87 extended precision, not
12219   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12220   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12221   MachineMemOperand *MMO =
12222     DAG.getMachineFunction()
12223     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12224                           MachineMemOperand::MOLoad, 8, 8);
12225
12226   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12227   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12228   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12229                                          MVT::i64, MMO);
12230
12231   APInt FF(32, 0x5F800000ULL);
12232
12233   // Check whether the sign bit is set.
12234   SDValue SignSet = DAG.getSetCC(
12235       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12236       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12237
12238   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12239   SDValue FudgePtr = DAG.getConstantPool(
12240       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12241
12242   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12243   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12244   SDValue Four = DAG.getIntPtrConstant(4, dl);
12245   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12246                                Zero, Four);
12247   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12248
12249   // Load the value out, extending it from f32 to f80.
12250   // FIXME: Avoid the extend by constructing the right constant pool?
12251   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12252                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12253                                  MVT::f32, false, false, false, 4);
12254   // Extend everything to 80 bits to force it to be done on x87.
12255   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12256   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12257                      DAG.getIntPtrConstant(0, dl));
12258 }
12259
12260 std::pair<SDValue,SDValue>
12261 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12262                                     bool IsSigned, bool IsReplace) const {
12263   SDLoc DL(Op);
12264
12265   EVT DstTy = Op.getValueType();
12266   auto PtrVT = getPointerTy(DAG.getDataLayout());
12267
12268   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12269     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12270     DstTy = MVT::i64;
12271   }
12272
12273   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12274          DstTy.getSimpleVT() >= MVT::i16 &&
12275          "Unknown FP_TO_INT to lower!");
12276
12277   // These are really Legal.
12278   if (DstTy == MVT::i32 &&
12279       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12280     return std::make_pair(SDValue(), SDValue());
12281   if (Subtarget->is64Bit() &&
12282       DstTy == MVT::i64 &&
12283       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12284     return std::make_pair(SDValue(), SDValue());
12285
12286   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12287   // stack slot, or into the FTOL runtime function.
12288   MachineFunction &MF = DAG.getMachineFunction();
12289   unsigned MemSize = DstTy.getSizeInBits()/8;
12290   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12291   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12292
12293   unsigned Opc;
12294   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12295     Opc = X86ISD::WIN_FTOL;
12296   else
12297     switch (DstTy.getSimpleVT().SimpleTy) {
12298     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12299     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12300     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12301     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12302     }
12303
12304   SDValue Chain = DAG.getEntryNode();
12305   SDValue Value = Op.getOperand(0);
12306   EVT TheVT = Op.getOperand(0).getValueType();
12307   // FIXME This causes a redundant load/store if the SSE-class value is already
12308   // in memory, such as if it is on the callstack.
12309   if (isScalarFPTypeInSSEReg(TheVT)) {
12310     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12311     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12312                          MachinePointerInfo::getFixedStack(SSFI),
12313                          false, false, 0);
12314     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12315     SDValue Ops[] = {
12316       Chain, StackSlot, DAG.getValueType(TheVT)
12317     };
12318
12319     MachineMemOperand *MMO =
12320       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12321                               MachineMemOperand::MOLoad, MemSize, MemSize);
12322     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12323     Chain = Value.getValue(1);
12324     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12325     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12326   }
12327
12328   MachineMemOperand *MMO =
12329     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12330                             MachineMemOperand::MOStore, MemSize, MemSize);
12331
12332   if (Opc != X86ISD::WIN_FTOL) {
12333     // Build the FP_TO_INT*_IN_MEM
12334     SDValue Ops[] = { Chain, Value, StackSlot };
12335     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12336                                            Ops, DstTy, MMO);
12337     return std::make_pair(FIST, StackSlot);
12338   } else {
12339     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12340       DAG.getVTList(MVT::Other, MVT::Glue),
12341       Chain, Value);
12342     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12343       MVT::i32, ftol.getValue(1));
12344     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12345       MVT::i32, eax.getValue(2));
12346     SDValue Ops[] = { eax, edx };
12347     SDValue pair = IsReplace
12348       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12349       : DAG.getMergeValues(Ops, DL);
12350     return std::make_pair(pair, SDValue());
12351   }
12352 }
12353
12354 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12355                               const X86Subtarget *Subtarget) {
12356   MVT VT = Op->getSimpleValueType(0);
12357   SDValue In = Op->getOperand(0);
12358   MVT InVT = In.getSimpleValueType();
12359   SDLoc dl(Op);
12360
12361   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12362     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12363
12364   // Optimize vectors in AVX mode:
12365   //
12366   //   v8i16 -> v8i32
12367   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12368   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12369   //   Concat upper and lower parts.
12370   //
12371   //   v4i32 -> v4i64
12372   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12373   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12374   //   Concat upper and lower parts.
12375   //
12376
12377   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12378       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12379       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12380     return SDValue();
12381
12382   if (Subtarget->hasInt256())
12383     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12384
12385   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12386   SDValue Undef = DAG.getUNDEF(InVT);
12387   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12388   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12389   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12390
12391   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12392                              VT.getVectorNumElements()/2);
12393
12394   OpLo = DAG.getBitcast(HVT, OpLo);
12395   OpHi = DAG.getBitcast(HVT, OpHi);
12396
12397   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12398 }
12399
12400 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12401                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12402   MVT VT = Op->getSimpleValueType(0);
12403   SDValue In = Op->getOperand(0);
12404   MVT InVT = In.getSimpleValueType();
12405   SDLoc DL(Op);
12406   unsigned int NumElts = VT.getVectorNumElements();
12407   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12408     return SDValue();
12409
12410   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12411     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12412
12413   assert(InVT.getVectorElementType() == MVT::i1);
12414   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12415   SDValue One =
12416    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12417   SDValue Zero =
12418    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12419
12420   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12421   if (VT.is512BitVector())
12422     return V;
12423   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12424 }
12425
12426 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12427                                SelectionDAG &DAG) {
12428   if (Subtarget->hasFp256())
12429     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12430       return Res;
12431
12432   return SDValue();
12433 }
12434
12435 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12436                                 SelectionDAG &DAG) {
12437   SDLoc DL(Op);
12438   MVT VT = Op.getSimpleValueType();
12439   SDValue In = Op.getOperand(0);
12440   MVT SVT = In.getSimpleValueType();
12441
12442   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12443     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12444
12445   if (Subtarget->hasFp256())
12446     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12447       return Res;
12448
12449   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12450          VT.getVectorNumElements() != SVT.getVectorNumElements());
12451   return SDValue();
12452 }
12453
12454 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12455   SDLoc DL(Op);
12456   MVT VT = Op.getSimpleValueType();
12457   SDValue In = Op.getOperand(0);
12458   MVT InVT = In.getSimpleValueType();
12459
12460   if (VT == MVT::i1) {
12461     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12462            "Invalid scalar TRUNCATE operation");
12463     if (InVT.getSizeInBits() >= 32)
12464       return SDValue();
12465     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12466     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12467   }
12468   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12469          "Invalid TRUNCATE operation");
12470
12471   // move vector to mask - truncate solution for SKX
12472   if (VT.getVectorElementType() == MVT::i1) {
12473     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12474         Subtarget->hasBWI())
12475       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12476     if ((InVT.is256BitVector() || InVT.is128BitVector())
12477         && InVT.getScalarSizeInBits() <= 16 &&
12478         Subtarget->hasBWI() && Subtarget->hasVLX())
12479       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12480     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12481         Subtarget->hasDQI())
12482       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12483     if ((InVT.is256BitVector() || InVT.is128BitVector())
12484         && InVT.getScalarSizeInBits() >= 32 &&
12485         Subtarget->hasDQI() && Subtarget->hasVLX())
12486       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12487   }
12488   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12489     if (VT.getVectorElementType().getSizeInBits() >=8)
12490       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12491
12492     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12493     unsigned NumElts = InVT.getVectorNumElements();
12494     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12495     if (InVT.getSizeInBits() < 512) {
12496       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12497       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12498       InVT = ExtVT;
12499     }
12500
12501     SDValue OneV =
12502      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12503     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12504     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12505   }
12506
12507   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12508     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12509     if (Subtarget->hasInt256()) {
12510       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12511       In = DAG.getBitcast(MVT::v8i32, In);
12512       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12513                                 ShufMask);
12514       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12515                          DAG.getIntPtrConstant(0, DL));
12516     }
12517
12518     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12519                                DAG.getIntPtrConstant(0, DL));
12520     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12521                                DAG.getIntPtrConstant(2, DL));
12522     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12523     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12524     static const int ShufMask[] = {0, 2, 4, 6};
12525     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12526   }
12527
12528   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12529     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12530     if (Subtarget->hasInt256()) {
12531       In = DAG.getBitcast(MVT::v32i8, In);
12532
12533       SmallVector<SDValue,32> pshufbMask;
12534       for (unsigned i = 0; i < 2; ++i) {
12535         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12536         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12537         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12538         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12539         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12540         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12541         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12542         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12543         for (unsigned j = 0; j < 8; ++j)
12544           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12545       }
12546       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12547       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12548       In = DAG.getBitcast(MVT::v4i64, In);
12549
12550       static const int ShufMask[] = {0,  2,  -1,  -1};
12551       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12552                                 &ShufMask[0]);
12553       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12554                        DAG.getIntPtrConstant(0, DL));
12555       return DAG.getBitcast(VT, In);
12556     }
12557
12558     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12559                                DAG.getIntPtrConstant(0, DL));
12560
12561     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12562                                DAG.getIntPtrConstant(4, DL));
12563
12564     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12565     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12566
12567     // The PSHUFB mask:
12568     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12569                                    -1, -1, -1, -1, -1, -1, -1, -1};
12570
12571     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12572     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12573     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12574
12575     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12576     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12577
12578     // The MOVLHPS Mask:
12579     static const int ShufMask2[] = {0, 1, 4, 5};
12580     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12581     return DAG.getBitcast(MVT::v8i16, res);
12582   }
12583
12584   // Handle truncation of V256 to V128 using shuffles.
12585   if (!VT.is128BitVector() || !InVT.is256BitVector())
12586     return SDValue();
12587
12588   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12589
12590   unsigned NumElems = VT.getVectorNumElements();
12591   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12592
12593   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12594   // Prepare truncation shuffle mask
12595   for (unsigned i = 0; i != NumElems; ++i)
12596     MaskVec[i] = i * 2;
12597   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12598                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12599   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12600                      DAG.getIntPtrConstant(0, DL));
12601 }
12602
12603 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12604                                            SelectionDAG &DAG) const {
12605   assert(!Op.getSimpleValueType().isVector());
12606
12607   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12608     /*IsSigned=*/ true, /*IsReplace=*/ false);
12609   SDValue FIST = Vals.first, StackSlot = Vals.second;
12610   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12611   if (!FIST.getNode()) return Op;
12612
12613   if (StackSlot.getNode())
12614     // Load the result.
12615     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12616                        FIST, StackSlot, MachinePointerInfo(),
12617                        false, false, false, 0);
12618
12619   // The node is the result.
12620   return FIST;
12621 }
12622
12623 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12624                                            SelectionDAG &DAG) const {
12625   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12626     /*IsSigned=*/ false, /*IsReplace=*/ false);
12627   SDValue FIST = Vals.first, StackSlot = Vals.second;
12628   assert(FIST.getNode() && "Unexpected failure");
12629
12630   if (StackSlot.getNode())
12631     // Load the result.
12632     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12633                        FIST, StackSlot, MachinePointerInfo(),
12634                        false, false, false, 0);
12635
12636   // The node is the result.
12637   return FIST;
12638 }
12639
12640 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12641   SDLoc DL(Op);
12642   MVT VT = Op.getSimpleValueType();
12643   SDValue In = Op.getOperand(0);
12644   MVT SVT = In.getSimpleValueType();
12645
12646   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12647
12648   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12649                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12650                                  In, DAG.getUNDEF(SVT)));
12651 }
12652
12653 /// The only differences between FABS and FNEG are the mask and the logic op.
12654 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12655 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12656   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12657          "Wrong opcode for lowering FABS or FNEG.");
12658
12659   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12660
12661   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12662   // into an FNABS. We'll lower the FABS after that if it is still in use.
12663   if (IsFABS)
12664     for (SDNode *User : Op->uses())
12665       if (User->getOpcode() == ISD::FNEG)
12666         return Op;
12667
12668   SDValue Op0 = Op.getOperand(0);
12669   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12670
12671   SDLoc dl(Op);
12672   MVT VT = Op.getSimpleValueType();
12673   // Assume scalar op for initialization; update for vector if needed.
12674   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12675   // generate a 16-byte vector constant and logic op even for the scalar case.
12676   // Using a 16-byte mask allows folding the load of the mask with
12677   // the logic op, so it can save (~4 bytes) on code size.
12678   MVT EltVT = VT;
12679   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12680   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12681   // decide if we should generate a 16-byte constant mask when we only need 4 or
12682   // 8 bytes for the scalar case.
12683   if (VT.isVector()) {
12684     EltVT = VT.getVectorElementType();
12685     NumElts = VT.getVectorNumElements();
12686   }
12687
12688   unsigned EltBits = EltVT.getSizeInBits();
12689   LLVMContext *Context = DAG.getContext();
12690   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12691   APInt MaskElt =
12692     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12693   Constant *C = ConstantInt::get(*Context, MaskElt);
12694   C = ConstantVector::getSplat(NumElts, C);
12695   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12696   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12697   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12698   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12699                              MachinePointerInfo::getConstantPool(),
12700                              false, false, false, Alignment);
12701
12702   if (VT.isVector()) {
12703     // For a vector, cast operands to a vector type, perform the logic op,
12704     // and cast the result back to the original value type.
12705     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12706     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12707     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12708                               : DAG.getBitcast(VecVT, Op0);
12709     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12710     return DAG.getBitcast(VT,
12711                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12712   }
12713
12714   // If not vector, then scalar.
12715   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12716   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12717   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12718 }
12719
12720 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12721   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12722   LLVMContext *Context = DAG.getContext();
12723   SDValue Op0 = Op.getOperand(0);
12724   SDValue Op1 = Op.getOperand(1);
12725   SDLoc dl(Op);
12726   MVT VT = Op.getSimpleValueType();
12727   MVT SrcVT = Op1.getSimpleValueType();
12728
12729   // If second operand is smaller, extend it first.
12730   if (SrcVT.bitsLT(VT)) {
12731     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12732     SrcVT = VT;
12733   }
12734   // And if it is bigger, shrink it first.
12735   if (SrcVT.bitsGT(VT)) {
12736     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12737     SrcVT = VT;
12738   }
12739
12740   // At this point the operands and the result should have the same
12741   // type, and that won't be f80 since that is not custom lowered.
12742
12743   const fltSemantics &Sem =
12744       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12745   const unsigned SizeInBits = VT.getSizeInBits();
12746
12747   SmallVector<Constant *, 4> CV(
12748       VT == MVT::f64 ? 2 : 4,
12749       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12750
12751   // First, clear all bits but the sign bit from the second operand (sign).
12752   CV[0] = ConstantFP::get(*Context,
12753                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12754   Constant *C = ConstantVector::get(CV);
12755   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12756   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12757   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12758                               MachinePointerInfo::getConstantPool(),
12759                               false, false, false, 16);
12760   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12761
12762   // Next, clear the sign bit from the first operand (magnitude).
12763   // If it's a constant, we can clear it here.
12764   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12765     APFloat APF = Op0CN->getValueAPF();
12766     // If the magnitude is a positive zero, the sign bit alone is enough.
12767     if (APF.isPosZero())
12768       return SignBit;
12769     APF.clearSign();
12770     CV[0] = ConstantFP::get(*Context, APF);
12771   } else {
12772     CV[0] = ConstantFP::get(
12773         *Context,
12774         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12775   }
12776   C = ConstantVector::get(CV);
12777   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12778   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12779                             MachinePointerInfo::getConstantPool(),
12780                             false, false, false, 16);
12781   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12782   if (!isa<ConstantFPSDNode>(Op0))
12783     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12784
12785   // OR the magnitude value with the sign bit.
12786   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12787 }
12788
12789 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12790   SDValue N0 = Op.getOperand(0);
12791   SDLoc dl(Op);
12792   MVT VT = Op.getSimpleValueType();
12793
12794   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12795   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12796                                   DAG.getConstant(1, dl, VT));
12797   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12798 }
12799
12800 // Check whether an OR'd tree is PTEST-able.
12801 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12802                                       SelectionDAG &DAG) {
12803   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12804
12805   if (!Subtarget->hasSSE41())
12806     return SDValue();
12807
12808   if (!Op->hasOneUse())
12809     return SDValue();
12810
12811   SDNode *N = Op.getNode();
12812   SDLoc DL(N);
12813
12814   SmallVector<SDValue, 8> Opnds;
12815   DenseMap<SDValue, unsigned> VecInMap;
12816   SmallVector<SDValue, 8> VecIns;
12817   EVT VT = MVT::Other;
12818
12819   // Recognize a special case where a vector is casted into wide integer to
12820   // test all 0s.
12821   Opnds.push_back(N->getOperand(0));
12822   Opnds.push_back(N->getOperand(1));
12823
12824   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12825     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12826     // BFS traverse all OR'd operands.
12827     if (I->getOpcode() == ISD::OR) {
12828       Opnds.push_back(I->getOperand(0));
12829       Opnds.push_back(I->getOperand(1));
12830       // Re-evaluate the number of nodes to be traversed.
12831       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12832       continue;
12833     }
12834
12835     // Quit if a non-EXTRACT_VECTOR_ELT
12836     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12837       return SDValue();
12838
12839     // Quit if without a constant index.
12840     SDValue Idx = I->getOperand(1);
12841     if (!isa<ConstantSDNode>(Idx))
12842       return SDValue();
12843
12844     SDValue ExtractedFromVec = I->getOperand(0);
12845     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12846     if (M == VecInMap.end()) {
12847       VT = ExtractedFromVec.getValueType();
12848       // Quit if not 128/256-bit vector.
12849       if (!VT.is128BitVector() && !VT.is256BitVector())
12850         return SDValue();
12851       // Quit if not the same type.
12852       if (VecInMap.begin() != VecInMap.end() &&
12853           VT != VecInMap.begin()->first.getValueType())
12854         return SDValue();
12855       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12856       VecIns.push_back(ExtractedFromVec);
12857     }
12858     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12859   }
12860
12861   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12862          "Not extracted from 128-/256-bit vector.");
12863
12864   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12865
12866   for (DenseMap<SDValue, unsigned>::const_iterator
12867         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12868     // Quit if not all elements are used.
12869     if (I->second != FullMask)
12870       return SDValue();
12871   }
12872
12873   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12874
12875   // Cast all vectors into TestVT for PTEST.
12876   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12877     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12878
12879   // If more than one full vectors are evaluated, OR them first before PTEST.
12880   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12881     // Each iteration will OR 2 nodes and append the result until there is only
12882     // 1 node left, i.e. the final OR'd value of all vectors.
12883     SDValue LHS = VecIns[Slot];
12884     SDValue RHS = VecIns[Slot + 1];
12885     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12886   }
12887
12888   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12889                      VecIns.back(), VecIns.back());
12890 }
12891
12892 /// \brief return true if \c Op has a use that doesn't just read flags.
12893 static bool hasNonFlagsUse(SDValue Op) {
12894   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12895        ++UI) {
12896     SDNode *User = *UI;
12897     unsigned UOpNo = UI.getOperandNo();
12898     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12899       // Look pass truncate.
12900       UOpNo = User->use_begin().getOperandNo();
12901       User = *User->use_begin();
12902     }
12903
12904     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12905         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12906       return true;
12907   }
12908   return false;
12909 }
12910
12911 /// Emit nodes that will be selected as "test Op0,Op0", or something
12912 /// equivalent.
12913 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12914                                     SelectionDAG &DAG) const {
12915   if (Op.getValueType() == MVT::i1) {
12916     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12917     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12918                        DAG.getConstant(0, dl, MVT::i8));
12919   }
12920   // CF and OF aren't always set the way we want. Determine which
12921   // of these we need.
12922   bool NeedCF = false;
12923   bool NeedOF = false;
12924   switch (X86CC) {
12925   default: break;
12926   case X86::COND_A: case X86::COND_AE:
12927   case X86::COND_B: case X86::COND_BE:
12928     NeedCF = true;
12929     break;
12930   case X86::COND_G: case X86::COND_GE:
12931   case X86::COND_L: case X86::COND_LE:
12932   case X86::COND_O: case X86::COND_NO: {
12933     // Check if we really need to set the
12934     // Overflow flag. If NoSignedWrap is present
12935     // that is not actually needed.
12936     switch (Op->getOpcode()) {
12937     case ISD::ADD:
12938     case ISD::SUB:
12939     case ISD::MUL:
12940     case ISD::SHL: {
12941       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12942       if (BinNode->Flags.hasNoSignedWrap())
12943         break;
12944     }
12945     default:
12946       NeedOF = true;
12947       break;
12948     }
12949     break;
12950   }
12951   }
12952   // See if we can use the EFLAGS value from the operand instead of
12953   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12954   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12955   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12956     // Emit a CMP with 0, which is the TEST pattern.
12957     //if (Op.getValueType() == MVT::i1)
12958     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12959     //                     DAG.getConstant(0, MVT::i1));
12960     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12961                        DAG.getConstant(0, dl, Op.getValueType()));
12962   }
12963   unsigned Opcode = 0;
12964   unsigned NumOperands = 0;
12965
12966   // Truncate operations may prevent the merge of the SETCC instruction
12967   // and the arithmetic instruction before it. Attempt to truncate the operands
12968   // of the arithmetic instruction and use a reduced bit-width instruction.
12969   bool NeedTruncation = false;
12970   SDValue ArithOp = Op;
12971   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12972     SDValue Arith = Op->getOperand(0);
12973     // Both the trunc and the arithmetic op need to have one user each.
12974     if (Arith->hasOneUse())
12975       switch (Arith.getOpcode()) {
12976         default: break;
12977         case ISD::ADD:
12978         case ISD::SUB:
12979         case ISD::AND:
12980         case ISD::OR:
12981         case ISD::XOR: {
12982           NeedTruncation = true;
12983           ArithOp = Arith;
12984         }
12985       }
12986   }
12987
12988   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12989   // which may be the result of a CAST.  We use the variable 'Op', which is the
12990   // non-casted variable when we check for possible users.
12991   switch (ArithOp.getOpcode()) {
12992   case ISD::ADD:
12993     // Due to an isel shortcoming, be conservative if this add is likely to be
12994     // selected as part of a load-modify-store instruction. When the root node
12995     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12996     // uses of other nodes in the match, such as the ADD in this case. This
12997     // leads to the ADD being left around and reselected, with the result being
12998     // two adds in the output.  Alas, even if none our users are stores, that
12999     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
13000     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
13001     // climbing the DAG back to the root, and it doesn't seem to be worth the
13002     // effort.
13003     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13004          UE = Op.getNode()->use_end(); UI != UE; ++UI)
13005       if (UI->getOpcode() != ISD::CopyToReg &&
13006           UI->getOpcode() != ISD::SETCC &&
13007           UI->getOpcode() != ISD::STORE)
13008         goto default_case;
13009
13010     if (ConstantSDNode *C =
13011         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
13012       // An add of one will be selected as an INC.
13013       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
13014         Opcode = X86ISD::INC;
13015         NumOperands = 1;
13016         break;
13017       }
13018
13019       // An add of negative one (subtract of one) will be selected as a DEC.
13020       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
13021         Opcode = X86ISD::DEC;
13022         NumOperands = 1;
13023         break;
13024       }
13025     }
13026
13027     // Otherwise use a regular EFLAGS-setting add.
13028     Opcode = X86ISD::ADD;
13029     NumOperands = 2;
13030     break;
13031   case ISD::SHL:
13032   case ISD::SRL:
13033     // If we have a constant logical shift that's only used in a comparison
13034     // against zero turn it into an equivalent AND. This allows turning it into
13035     // a TEST instruction later.
13036     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13037         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13038       EVT VT = Op.getValueType();
13039       unsigned BitWidth = VT.getSizeInBits();
13040       unsigned ShAmt = Op->getConstantOperandVal(1);
13041       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13042         break;
13043       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13044                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13045                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13046       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13047         break;
13048       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13049                                 DAG.getConstant(Mask, dl, VT));
13050       DAG.ReplaceAllUsesWith(Op, New);
13051       Op = New;
13052     }
13053     break;
13054
13055   case ISD::AND:
13056     // If the primary and result isn't used, don't bother using X86ISD::AND,
13057     // because a TEST instruction will be better.
13058     if (!hasNonFlagsUse(Op))
13059       break;
13060     // FALL THROUGH
13061   case ISD::SUB:
13062   case ISD::OR:
13063   case ISD::XOR:
13064     // Due to the ISEL shortcoming noted above, be conservative if this op is
13065     // likely to be selected as part of a load-modify-store instruction.
13066     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13067            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13068       if (UI->getOpcode() == ISD::STORE)
13069         goto default_case;
13070
13071     // Otherwise use a regular EFLAGS-setting instruction.
13072     switch (ArithOp.getOpcode()) {
13073     default: llvm_unreachable("unexpected operator!");
13074     case ISD::SUB: Opcode = X86ISD::SUB; break;
13075     case ISD::XOR: Opcode = X86ISD::XOR; break;
13076     case ISD::AND: Opcode = X86ISD::AND; break;
13077     case ISD::OR: {
13078       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13079         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13080         if (EFLAGS.getNode())
13081           return EFLAGS;
13082       }
13083       Opcode = X86ISD::OR;
13084       break;
13085     }
13086     }
13087
13088     NumOperands = 2;
13089     break;
13090   case X86ISD::ADD:
13091   case X86ISD::SUB:
13092   case X86ISD::INC:
13093   case X86ISD::DEC:
13094   case X86ISD::OR:
13095   case X86ISD::XOR:
13096   case X86ISD::AND:
13097     return SDValue(Op.getNode(), 1);
13098   default:
13099   default_case:
13100     break;
13101   }
13102
13103   // If we found that truncation is beneficial, perform the truncation and
13104   // update 'Op'.
13105   if (NeedTruncation) {
13106     EVT VT = Op.getValueType();
13107     SDValue WideVal = Op->getOperand(0);
13108     EVT WideVT = WideVal.getValueType();
13109     unsigned ConvertedOp = 0;
13110     // Use a target machine opcode to prevent further DAGCombine
13111     // optimizations that may separate the arithmetic operations
13112     // from the setcc node.
13113     switch (WideVal.getOpcode()) {
13114       default: break;
13115       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13116       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13117       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13118       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13119       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13120     }
13121
13122     if (ConvertedOp) {
13123       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13124       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13125         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13126         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13127         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13128       }
13129     }
13130   }
13131
13132   if (Opcode == 0)
13133     // Emit a CMP with 0, which is the TEST pattern.
13134     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13135                        DAG.getConstant(0, dl, Op.getValueType()));
13136
13137   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13138   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13139
13140   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13141   DAG.ReplaceAllUsesWith(Op, New);
13142   return SDValue(New.getNode(), 1);
13143 }
13144
13145 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13146 /// equivalent.
13147 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13148                                    SDLoc dl, SelectionDAG &DAG) const {
13149   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13150     if (C->getAPIntValue() == 0)
13151       return EmitTest(Op0, X86CC, dl, DAG);
13152
13153      if (Op0.getValueType() == MVT::i1)
13154        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13155   }
13156
13157   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13158        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13159     // Do the comparison at i32 if it's smaller, besides the Atom case.
13160     // This avoids subregister aliasing issues. Keep the smaller reference
13161     // if we're optimizing for size, however, as that'll allow better folding
13162     // of memory operations.
13163     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13164         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13165             Attribute::MinSize) &&
13166         !Subtarget->isAtom()) {
13167       unsigned ExtendOp =
13168           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13169       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13170       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13171     }
13172     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13173     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13174     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13175                               Op0, Op1);
13176     return SDValue(Sub.getNode(), 1);
13177   }
13178   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13179 }
13180
13181 /// Convert a comparison if required by the subtarget.
13182 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13183                                                  SelectionDAG &DAG) const {
13184   // If the subtarget does not support the FUCOMI instruction, floating-point
13185   // comparisons have to be converted.
13186   if (Subtarget->hasCMov() ||
13187       Cmp.getOpcode() != X86ISD::CMP ||
13188       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13189       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13190     return Cmp;
13191
13192   // The instruction selector will select an FUCOM instruction instead of
13193   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13194   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13195   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13196   SDLoc dl(Cmp);
13197   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13198   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13199   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13200                             DAG.getConstant(8, dl, MVT::i8));
13201   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13202   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13203 }
13204
13205 /// The minimum architected relative accuracy is 2^-12. We need one
13206 /// Newton-Raphson step to have a good float result (24 bits of precision).
13207 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13208                                             DAGCombinerInfo &DCI,
13209                                             unsigned &RefinementSteps,
13210                                             bool &UseOneConstNR) const {
13211   EVT VT = Op.getValueType();
13212   const char *RecipOp;
13213
13214   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13215   // TODO: Add support for AVX512 (v16f32).
13216   // It is likely not profitable to do this for f64 because a double-precision
13217   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13218   // instructions: convert to single, rsqrtss, convert back to double, refine
13219   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13220   // along with FMA, this could be a throughput win.
13221   if (VT == MVT::f32 && Subtarget->hasSSE1())
13222     RecipOp = "sqrtf";
13223   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13224            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13225     RecipOp = "vec-sqrtf";
13226   else
13227     return SDValue();
13228
13229   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13230   if (!Recips.isEnabled(RecipOp))
13231     return SDValue();
13232
13233   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13234   UseOneConstNR = false;
13235   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13236 }
13237
13238 /// The minimum architected relative accuracy is 2^-12. We need one
13239 /// Newton-Raphson step to have a good float result (24 bits of precision).
13240 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13241                                             DAGCombinerInfo &DCI,
13242                                             unsigned &RefinementSteps) const {
13243   EVT VT = Op.getValueType();
13244   const char *RecipOp;
13245
13246   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13247   // TODO: Add support for AVX512 (v16f32).
13248   // It is likely not profitable to do this for f64 because a double-precision
13249   // reciprocal estimate with refinement on x86 prior to FMA requires
13250   // 15 instructions: convert to single, rcpss, convert back to double, refine
13251   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13252   // along with FMA, this could be a throughput win.
13253   if (VT == MVT::f32 && Subtarget->hasSSE1())
13254     RecipOp = "divf";
13255   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13256            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13257     RecipOp = "vec-divf";
13258   else
13259     return SDValue();
13260
13261   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13262   if (!Recips.isEnabled(RecipOp))
13263     return SDValue();
13264
13265   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13266   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13267 }
13268
13269 /// If we have at least two divisions that use the same divisor, convert to
13270 /// multplication by a reciprocal. This may need to be adjusted for a given
13271 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13272 /// This is because we still need one division to calculate the reciprocal and
13273 /// then we need two multiplies by that reciprocal as replacements for the
13274 /// original divisions.
13275 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13276   return NumUsers > 1;
13277 }
13278
13279 static bool isAllOnes(SDValue V) {
13280   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13281   return C && C->isAllOnesValue();
13282 }
13283
13284 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13285 /// if it's possible.
13286 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13287                                      SDLoc dl, SelectionDAG &DAG) const {
13288   SDValue Op0 = And.getOperand(0);
13289   SDValue Op1 = And.getOperand(1);
13290   if (Op0.getOpcode() == ISD::TRUNCATE)
13291     Op0 = Op0.getOperand(0);
13292   if (Op1.getOpcode() == ISD::TRUNCATE)
13293     Op1 = Op1.getOperand(0);
13294
13295   SDValue LHS, RHS;
13296   if (Op1.getOpcode() == ISD::SHL)
13297     std::swap(Op0, Op1);
13298   if (Op0.getOpcode() == ISD::SHL) {
13299     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13300       if (And00C->getZExtValue() == 1) {
13301         // If we looked past a truncate, check that it's only truncating away
13302         // known zeros.
13303         unsigned BitWidth = Op0.getValueSizeInBits();
13304         unsigned AndBitWidth = And.getValueSizeInBits();
13305         if (BitWidth > AndBitWidth) {
13306           APInt Zeros, Ones;
13307           DAG.computeKnownBits(Op0, Zeros, Ones);
13308           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13309             return SDValue();
13310         }
13311         LHS = Op1;
13312         RHS = Op0.getOperand(1);
13313       }
13314   } else if (Op1.getOpcode() == ISD::Constant) {
13315     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13316     uint64_t AndRHSVal = AndRHS->getZExtValue();
13317     SDValue AndLHS = Op0;
13318
13319     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13320       LHS = AndLHS.getOperand(0);
13321       RHS = AndLHS.getOperand(1);
13322     }
13323
13324     // Use BT if the immediate can't be encoded in a TEST instruction.
13325     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13326       LHS = AndLHS;
13327       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13328     }
13329   }
13330
13331   if (LHS.getNode()) {
13332     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13333     // instruction.  Since the shift amount is in-range-or-undefined, we know
13334     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13335     // the encoding for the i16 version is larger than the i32 version.
13336     // Also promote i16 to i32 for performance / code size reason.
13337     if (LHS.getValueType() == MVT::i8 ||
13338         LHS.getValueType() == MVT::i16)
13339       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13340
13341     // If the operand types disagree, extend the shift amount to match.  Since
13342     // BT ignores high bits (like shifts) we can use anyextend.
13343     if (LHS.getValueType() != RHS.getValueType())
13344       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13345
13346     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13347     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13348     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13349                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13350   }
13351
13352   return SDValue();
13353 }
13354
13355 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13356 /// mask CMPs.
13357 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13358                               SDValue &Op1) {
13359   unsigned SSECC;
13360   bool Swap = false;
13361
13362   // SSE Condition code mapping:
13363   //  0 - EQ
13364   //  1 - LT
13365   //  2 - LE
13366   //  3 - UNORD
13367   //  4 - NEQ
13368   //  5 - NLT
13369   //  6 - NLE
13370   //  7 - ORD
13371   switch (SetCCOpcode) {
13372   default: llvm_unreachable("Unexpected SETCC condition");
13373   case ISD::SETOEQ:
13374   case ISD::SETEQ:  SSECC = 0; break;
13375   case ISD::SETOGT:
13376   case ISD::SETGT:  Swap = true; // Fallthrough
13377   case ISD::SETLT:
13378   case ISD::SETOLT: SSECC = 1; break;
13379   case ISD::SETOGE:
13380   case ISD::SETGE:  Swap = true; // Fallthrough
13381   case ISD::SETLE:
13382   case ISD::SETOLE: SSECC = 2; break;
13383   case ISD::SETUO:  SSECC = 3; break;
13384   case ISD::SETUNE:
13385   case ISD::SETNE:  SSECC = 4; break;
13386   case ISD::SETULE: Swap = true; // Fallthrough
13387   case ISD::SETUGE: SSECC = 5; break;
13388   case ISD::SETULT: Swap = true; // Fallthrough
13389   case ISD::SETUGT: SSECC = 6; break;
13390   case ISD::SETO:   SSECC = 7; break;
13391   case ISD::SETUEQ:
13392   case ISD::SETONE: SSECC = 8; break;
13393   }
13394   if (Swap)
13395     std::swap(Op0, Op1);
13396
13397   return SSECC;
13398 }
13399
13400 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13401 // ones, and then concatenate the result back.
13402 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13403   MVT VT = Op.getSimpleValueType();
13404
13405   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13406          "Unsupported value type for operation");
13407
13408   unsigned NumElems = VT.getVectorNumElements();
13409   SDLoc dl(Op);
13410   SDValue CC = Op.getOperand(2);
13411
13412   // Extract the LHS vectors
13413   SDValue LHS = Op.getOperand(0);
13414   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13415   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13416
13417   // Extract the RHS vectors
13418   SDValue RHS = Op.getOperand(1);
13419   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13420   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13421
13422   // Issue the operation on the smaller types and concatenate the result back
13423   MVT EltVT = VT.getVectorElementType();
13424   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13425   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13426                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13427                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13428 }
13429
13430 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13431   SDValue Op0 = Op.getOperand(0);
13432   SDValue Op1 = Op.getOperand(1);
13433   SDValue CC = Op.getOperand(2);
13434   MVT VT = Op.getSimpleValueType();
13435   SDLoc dl(Op);
13436
13437   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13438          "Unexpected type for boolean compare operation");
13439   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13440   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13441                                DAG.getConstant(-1, dl, VT));
13442   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13443                                DAG.getConstant(-1, dl, VT));
13444   switch (SetCCOpcode) {
13445   default: llvm_unreachable("Unexpected SETCC condition");
13446   case ISD::SETEQ:
13447     // (x == y) -> ~(x ^ y)
13448     return DAG.getNode(ISD::XOR, dl, VT,
13449                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13450                        DAG.getConstant(-1, dl, VT));
13451   case ISD::SETNE:
13452     // (x != y) -> (x ^ y)
13453     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13454   case ISD::SETUGT:
13455   case ISD::SETGT:
13456     // (x > y) -> (x & ~y)
13457     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13458   case ISD::SETULT:
13459   case ISD::SETLT:
13460     // (x < y) -> (~x & y)
13461     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13462   case ISD::SETULE:
13463   case ISD::SETLE:
13464     // (x <= y) -> (~x | y)
13465     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13466   case ISD::SETUGE:
13467   case ISD::SETGE:
13468     // (x >=y) -> (x | ~y)
13469     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13470   }
13471 }
13472
13473 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13474                                      const X86Subtarget *Subtarget) {
13475   SDValue Op0 = Op.getOperand(0);
13476   SDValue Op1 = Op.getOperand(1);
13477   SDValue CC = Op.getOperand(2);
13478   MVT VT = Op.getSimpleValueType();
13479   SDLoc dl(Op);
13480
13481   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13482          Op.getValueType().getScalarType() == MVT::i1 &&
13483          "Cannot set masked compare for this operation");
13484
13485   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13486   unsigned  Opc = 0;
13487   bool Unsigned = false;
13488   bool Swap = false;
13489   unsigned SSECC;
13490   switch (SetCCOpcode) {
13491   default: llvm_unreachable("Unexpected SETCC condition");
13492   case ISD::SETNE:  SSECC = 4; break;
13493   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13494   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13495   case ISD::SETLT:  Swap = true; //fall-through
13496   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13497   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13498   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13499   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13500   case ISD::SETULE: Unsigned = true; //fall-through
13501   case ISD::SETLE:  SSECC = 2; break;
13502   }
13503
13504   if (Swap)
13505     std::swap(Op0, Op1);
13506   if (Opc)
13507     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13508   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13509   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13510                      DAG.getConstant(SSECC, dl, MVT::i8));
13511 }
13512
13513 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13514 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13515 /// return an empty value.
13516 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13517 {
13518   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13519   if (!BV)
13520     return SDValue();
13521
13522   MVT VT = Op1.getSimpleValueType();
13523   MVT EVT = VT.getVectorElementType();
13524   unsigned n = VT.getVectorNumElements();
13525   SmallVector<SDValue, 8> ULTOp1;
13526
13527   for (unsigned i = 0; i < n; ++i) {
13528     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13529     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13530       return SDValue();
13531
13532     // Avoid underflow.
13533     APInt Val = Elt->getAPIntValue();
13534     if (Val == 0)
13535       return SDValue();
13536
13537     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13538   }
13539
13540   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13541 }
13542
13543 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13544                            SelectionDAG &DAG) {
13545   SDValue Op0 = Op.getOperand(0);
13546   SDValue Op1 = Op.getOperand(1);
13547   SDValue CC = Op.getOperand(2);
13548   MVT VT = Op.getSimpleValueType();
13549   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13550   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13551   SDLoc dl(Op);
13552
13553   if (isFP) {
13554 #ifndef NDEBUG
13555     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13556     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13557 #endif
13558
13559     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13560     unsigned Opc = X86ISD::CMPP;
13561     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13562       assert(VT.getVectorNumElements() <= 16);
13563       Opc = X86ISD::CMPM;
13564     }
13565     // In the two special cases we can't handle, emit two comparisons.
13566     if (SSECC == 8) {
13567       unsigned CC0, CC1;
13568       unsigned CombineOpc;
13569       if (SetCCOpcode == ISD::SETUEQ) {
13570         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13571       } else {
13572         assert(SetCCOpcode == ISD::SETONE);
13573         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13574       }
13575
13576       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13577                                  DAG.getConstant(CC0, dl, MVT::i8));
13578       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13579                                  DAG.getConstant(CC1, dl, MVT::i8));
13580       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13581     }
13582     // Handle all other FP comparisons here.
13583     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13584                        DAG.getConstant(SSECC, dl, MVT::i8));
13585   }
13586
13587   // Break 256-bit integer vector compare into smaller ones.
13588   if (VT.is256BitVector() && !Subtarget->hasInt256())
13589     return Lower256IntVSETCC(Op, DAG);
13590
13591   EVT OpVT = Op1.getValueType();
13592   if (OpVT.getVectorElementType() == MVT::i1)
13593     return LowerBoolVSETCC_AVX512(Op, DAG);
13594
13595   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13596   if (Subtarget->hasAVX512()) {
13597     if (Op1.getValueType().is512BitVector() ||
13598         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13599         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13600       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13601
13602     // In AVX-512 architecture setcc returns mask with i1 elements,
13603     // But there is no compare instruction for i8 and i16 elements in KNL.
13604     // We are not talking about 512-bit operands in this case, these
13605     // types are illegal.
13606     if (MaskResult &&
13607         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13608          OpVT.getVectorElementType().getSizeInBits() >= 8))
13609       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13610                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13611   }
13612
13613   // We are handling one of the integer comparisons here.  Since SSE only has
13614   // GT and EQ comparisons for integer, swapping operands and multiple
13615   // operations may be required for some comparisons.
13616   unsigned Opc;
13617   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13618   bool Subus = false;
13619
13620   switch (SetCCOpcode) {
13621   default: llvm_unreachable("Unexpected SETCC condition");
13622   case ISD::SETNE:  Invert = true;
13623   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13624   case ISD::SETLT:  Swap = true;
13625   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13626   case ISD::SETGE:  Swap = true;
13627   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13628                     Invert = true; break;
13629   case ISD::SETULT: Swap = true;
13630   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13631                     FlipSigns = true; break;
13632   case ISD::SETUGE: Swap = true;
13633   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13634                     FlipSigns = true; Invert = true; break;
13635   }
13636
13637   // Special case: Use min/max operations for SETULE/SETUGE
13638   MVT VET = VT.getVectorElementType();
13639   bool hasMinMax =
13640        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13641     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13642
13643   if (hasMinMax) {
13644     switch (SetCCOpcode) {
13645     default: break;
13646     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13647     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13648     }
13649
13650     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13651   }
13652
13653   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13654   if (!MinMax && hasSubus) {
13655     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13656     // Op0 u<= Op1:
13657     //   t = psubus Op0, Op1
13658     //   pcmpeq t, <0..0>
13659     switch (SetCCOpcode) {
13660     default: break;
13661     case ISD::SETULT: {
13662       // If the comparison is against a constant we can turn this into a
13663       // setule.  With psubus, setule does not require a swap.  This is
13664       // beneficial because the constant in the register is no longer
13665       // destructed as the destination so it can be hoisted out of a loop.
13666       // Only do this pre-AVX since vpcmp* is no longer destructive.
13667       if (Subtarget->hasAVX())
13668         break;
13669       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13670       if (ULEOp1.getNode()) {
13671         Op1 = ULEOp1;
13672         Subus = true; Invert = false; Swap = false;
13673       }
13674       break;
13675     }
13676     // Psubus is better than flip-sign because it requires no inversion.
13677     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13678     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13679     }
13680
13681     if (Subus) {
13682       Opc = X86ISD::SUBUS;
13683       FlipSigns = false;
13684     }
13685   }
13686
13687   if (Swap)
13688     std::swap(Op0, Op1);
13689
13690   // Check that the operation in question is available (most are plain SSE2,
13691   // but PCMPGTQ and PCMPEQQ have different requirements).
13692   if (VT == MVT::v2i64) {
13693     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13694       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13695
13696       // First cast everything to the right type.
13697       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13698       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13699
13700       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13701       // bits of the inputs before performing those operations. The lower
13702       // compare is always unsigned.
13703       SDValue SB;
13704       if (FlipSigns) {
13705         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13706       } else {
13707         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13708         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13709         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13710                          Sign, Zero, Sign, Zero);
13711       }
13712       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13713       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13714
13715       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13716       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13717       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13718
13719       // Create masks for only the low parts/high parts of the 64 bit integers.
13720       static const int MaskHi[] = { 1, 1, 3, 3 };
13721       static const int MaskLo[] = { 0, 0, 2, 2 };
13722       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13723       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13724       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13725
13726       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13727       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13728
13729       if (Invert)
13730         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13731
13732       return DAG.getBitcast(VT, Result);
13733     }
13734
13735     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13736       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13737       // pcmpeqd + pshufd + pand.
13738       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13739
13740       // First cast everything to the right type.
13741       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13742       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13743
13744       // Do the compare.
13745       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13746
13747       // Make sure the lower and upper halves are both all-ones.
13748       static const int Mask[] = { 1, 0, 3, 2 };
13749       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13750       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13751
13752       if (Invert)
13753         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13754
13755       return DAG.getBitcast(VT, Result);
13756     }
13757   }
13758
13759   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13760   // bits of the inputs before performing those operations.
13761   if (FlipSigns) {
13762     EVT EltVT = VT.getVectorElementType();
13763     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13764                                  VT);
13765     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13766     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13767   }
13768
13769   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13770
13771   // If the logical-not of the result is required, perform that now.
13772   if (Invert)
13773     Result = DAG.getNOT(dl, Result, VT);
13774
13775   if (MinMax)
13776     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13777
13778   if (Subus)
13779     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13780                          getZeroVector(VT, Subtarget, DAG, dl));
13781
13782   return Result;
13783 }
13784
13785 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13786
13787   MVT VT = Op.getSimpleValueType();
13788
13789   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13790
13791   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13792          && "SetCC type must be 8-bit or 1-bit integer");
13793   SDValue Op0 = Op.getOperand(0);
13794   SDValue Op1 = Op.getOperand(1);
13795   SDLoc dl(Op);
13796   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13797
13798   // Optimize to BT if possible.
13799   // Lower (X & (1 << N)) == 0 to BT(X, N).
13800   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13801   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13802   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13803       Op1.getOpcode() == ISD::Constant &&
13804       cast<ConstantSDNode>(Op1)->isNullValue() &&
13805       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13806     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13807     if (NewSetCC.getNode()) {
13808       if (VT == MVT::i1)
13809         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13810       return NewSetCC;
13811     }
13812   }
13813
13814   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13815   // these.
13816   if (Op1.getOpcode() == ISD::Constant &&
13817       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13818        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13819       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13820
13821     // If the input is a setcc, then reuse the input setcc or use a new one with
13822     // the inverted condition.
13823     if (Op0.getOpcode() == X86ISD::SETCC) {
13824       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13825       bool Invert = (CC == ISD::SETNE) ^
13826         cast<ConstantSDNode>(Op1)->isNullValue();
13827       if (!Invert)
13828         return Op0;
13829
13830       CCode = X86::GetOppositeBranchCondition(CCode);
13831       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13832                                   DAG.getConstant(CCode, dl, MVT::i8),
13833                                   Op0.getOperand(1));
13834       if (VT == MVT::i1)
13835         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13836       return SetCC;
13837     }
13838   }
13839   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13840       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13841       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13842
13843     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13844     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13845   }
13846
13847   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13848   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13849   if (X86CC == X86::COND_INVALID)
13850     return SDValue();
13851
13852   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13853   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13854   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13855                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13856   if (VT == MVT::i1)
13857     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13858   return SetCC;
13859 }
13860
13861 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13862 static bool isX86LogicalCmp(SDValue Op) {
13863   unsigned Opc = Op.getNode()->getOpcode();
13864   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13865       Opc == X86ISD::SAHF)
13866     return true;
13867   if (Op.getResNo() == 1 &&
13868       (Opc == X86ISD::ADD ||
13869        Opc == X86ISD::SUB ||
13870        Opc == X86ISD::ADC ||
13871        Opc == X86ISD::SBB ||
13872        Opc == X86ISD::SMUL ||
13873        Opc == X86ISD::UMUL ||
13874        Opc == X86ISD::INC ||
13875        Opc == X86ISD::DEC ||
13876        Opc == X86ISD::OR ||
13877        Opc == X86ISD::XOR ||
13878        Opc == X86ISD::AND))
13879     return true;
13880
13881   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13882     return true;
13883
13884   return false;
13885 }
13886
13887 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13888   if (V.getOpcode() != ISD::TRUNCATE)
13889     return false;
13890
13891   SDValue VOp0 = V.getOperand(0);
13892   unsigned InBits = VOp0.getValueSizeInBits();
13893   unsigned Bits = V.getValueSizeInBits();
13894   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13895 }
13896
13897 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13898   bool addTest = true;
13899   SDValue Cond  = Op.getOperand(0);
13900   SDValue Op1 = Op.getOperand(1);
13901   SDValue Op2 = Op.getOperand(2);
13902   SDLoc DL(Op);
13903   EVT VT = Op1.getValueType();
13904   SDValue CC;
13905
13906   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13907   // are available or VBLENDV if AVX is available.
13908   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13909   if (Cond.getOpcode() == ISD::SETCC &&
13910       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13911        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13912       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13913     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13914     int SSECC = translateX86FSETCC(
13915         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13916
13917     if (SSECC != 8) {
13918       if (Subtarget->hasAVX512()) {
13919         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13920                                   DAG.getConstant(SSECC, DL, MVT::i8));
13921         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13922       }
13923
13924       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13925                                 DAG.getConstant(SSECC, DL, MVT::i8));
13926
13927       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13928       // of 3 logic instructions for size savings and potentially speed.
13929       // Unfortunately, there is no scalar form of VBLENDV.
13930
13931       // If either operand is a constant, don't try this. We can expect to
13932       // optimize away at least one of the logic instructions later in that
13933       // case, so that sequence would be faster than a variable blend.
13934
13935       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13936       // uses XMM0 as the selection register. That may need just as many
13937       // instructions as the AND/ANDN/OR sequence due to register moves, so
13938       // don't bother.
13939
13940       if (Subtarget->hasAVX() &&
13941           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13942
13943         // Convert to vectors, do a VSELECT, and convert back to scalar.
13944         // All of the conversions should be optimized away.
13945
13946         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13947         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13948         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13949         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13950
13951         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13952         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13953
13954         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13955
13956         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13957                            VSel, DAG.getIntPtrConstant(0, DL));
13958       }
13959       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13960       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13961       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13962     }
13963   }
13964
13965     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13966       SDValue Op1Scalar;
13967       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13968         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13969       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13970         Op1Scalar = Op1.getOperand(0);
13971       SDValue Op2Scalar;
13972       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13973         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13974       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13975         Op2Scalar = Op2.getOperand(0);
13976       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13977         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13978                                         Op1Scalar.getValueType(),
13979                                         Cond, Op1Scalar, Op2Scalar);
13980         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13981           return DAG.getBitcast(VT, newSelect);
13982         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13983         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13984                            DAG.getIntPtrConstant(0, DL));
13985     }
13986   }
13987
13988   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13989     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13990     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13991                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13992     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13993                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13994     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13995                                     Cond, Op1, Op2);
13996     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13997   }
13998
13999   if (Cond.getOpcode() == ISD::SETCC) {
14000     SDValue NewCond = LowerSETCC(Cond, DAG);
14001     if (NewCond.getNode())
14002       Cond = NewCond;
14003   }
14004
14005   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
14006   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
14007   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
14008   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
14009   if (Cond.getOpcode() == X86ISD::SETCC &&
14010       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
14011       isZero(Cond.getOperand(1).getOperand(1))) {
14012     SDValue Cmp = Cond.getOperand(1);
14013
14014     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
14015
14016     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
14017         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
14018       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
14019
14020       SDValue CmpOp0 = Cmp.getOperand(0);
14021       // Apply further optimizations for special cases
14022       // (select (x != 0), -1, 0) -> neg & sbb
14023       // (select (x == 0), 0, -1) -> neg & sbb
14024       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14025         if (YC->isNullValue() &&
14026             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14027           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14028           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14029                                     DAG.getConstant(0, DL,
14030                                                     CmpOp0.getValueType()),
14031                                     CmpOp0);
14032           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14033                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14034                                     SDValue(Neg.getNode(), 1));
14035           return Res;
14036         }
14037
14038       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14039                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14040       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14041
14042       SDValue Res =   // Res = 0 or -1.
14043         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14044                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14045
14046       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14047         Res = DAG.getNOT(DL, Res, Res.getValueType());
14048
14049       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14050       if (!N2C || !N2C->isNullValue())
14051         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14052       return Res;
14053     }
14054   }
14055
14056   // Look past (and (setcc_carry (cmp ...)), 1).
14057   if (Cond.getOpcode() == ISD::AND &&
14058       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14059     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14060     if (C && C->getAPIntValue() == 1)
14061       Cond = Cond.getOperand(0);
14062   }
14063
14064   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14065   // setting operand in place of the X86ISD::SETCC.
14066   unsigned CondOpcode = Cond.getOpcode();
14067   if (CondOpcode == X86ISD::SETCC ||
14068       CondOpcode == X86ISD::SETCC_CARRY) {
14069     CC = Cond.getOperand(0);
14070
14071     SDValue Cmp = Cond.getOperand(1);
14072     unsigned Opc = Cmp.getOpcode();
14073     MVT VT = Op.getSimpleValueType();
14074
14075     bool IllegalFPCMov = false;
14076     if (VT.isFloatingPoint() && !VT.isVector() &&
14077         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14078       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14079
14080     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14081         Opc == X86ISD::BT) { // FIXME
14082       Cond = Cmp;
14083       addTest = false;
14084     }
14085   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14086              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14087              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14088               Cond.getOperand(0).getValueType() != MVT::i8)) {
14089     SDValue LHS = Cond.getOperand(0);
14090     SDValue RHS = Cond.getOperand(1);
14091     unsigned X86Opcode;
14092     unsigned X86Cond;
14093     SDVTList VTs;
14094     switch (CondOpcode) {
14095     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14096     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14097     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14098     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14099     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14100     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14101     default: llvm_unreachable("unexpected overflowing operator");
14102     }
14103     if (CondOpcode == ISD::UMULO)
14104       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14105                           MVT::i32);
14106     else
14107       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14108
14109     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14110
14111     if (CondOpcode == ISD::UMULO)
14112       Cond = X86Op.getValue(2);
14113     else
14114       Cond = X86Op.getValue(1);
14115
14116     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14117     addTest = false;
14118   }
14119
14120   if (addTest) {
14121     // Look pass the truncate if the high bits are known zero.
14122     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14123         Cond = Cond.getOperand(0);
14124
14125     // We know the result of AND is compared against zero. Try to match
14126     // it to BT.
14127     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14128       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14129       if (NewSetCC.getNode()) {
14130         CC = NewSetCC.getOperand(0);
14131         Cond = NewSetCC.getOperand(1);
14132         addTest = false;
14133       }
14134     }
14135   }
14136
14137   if (addTest) {
14138     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14139     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14140   }
14141
14142   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14143   // a <  b ?  0 : -1 -> RES = setcc_carry
14144   // a >= b ? -1 :  0 -> RES = setcc_carry
14145   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14146   if (Cond.getOpcode() == X86ISD::SUB) {
14147     Cond = ConvertCmpIfNecessary(Cond, DAG);
14148     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14149
14150     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14151         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14152       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14153                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14154                                 Cond);
14155       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14156         return DAG.getNOT(DL, Res, Res.getValueType());
14157       return Res;
14158     }
14159   }
14160
14161   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14162   // widen the cmov and push the truncate through. This avoids introducing a new
14163   // branch during isel and doesn't add any extensions.
14164   if (Op.getValueType() == MVT::i8 &&
14165       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14166     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14167     if (T1.getValueType() == T2.getValueType() &&
14168         // Blacklist CopyFromReg to avoid partial register stalls.
14169         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14170       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14171       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14172       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14173     }
14174   }
14175
14176   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14177   // condition is true.
14178   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14179   SDValue Ops[] = { Op2, Op1, CC, Cond };
14180   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14181 }
14182
14183 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14184                                        const X86Subtarget *Subtarget,
14185                                        SelectionDAG &DAG) {
14186   MVT VT = Op->getSimpleValueType(0);
14187   SDValue In = Op->getOperand(0);
14188   MVT InVT = In.getSimpleValueType();
14189   MVT VTElt = VT.getVectorElementType();
14190   MVT InVTElt = InVT.getVectorElementType();
14191   SDLoc dl(Op);
14192
14193   // SKX processor
14194   if ((InVTElt == MVT::i1) &&
14195       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14196         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14197
14198        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14199         VTElt.getSizeInBits() <= 16)) ||
14200
14201        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14202         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14203
14204        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14205         VTElt.getSizeInBits() >= 32))))
14206     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14207
14208   unsigned int NumElts = VT.getVectorNumElements();
14209
14210   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14211     return SDValue();
14212
14213   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14214     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14215       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14216     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14217   }
14218
14219   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14220   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14221   SDValue NegOne =
14222    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14223                    ExtVT);
14224   SDValue Zero =
14225    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14226
14227   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14228   if (VT.is512BitVector())
14229     return V;
14230   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14231 }
14232
14233 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14234                                              const X86Subtarget *Subtarget,
14235                                              SelectionDAG &DAG) {
14236   SDValue In = Op->getOperand(0);
14237   MVT VT = Op->getSimpleValueType(0);
14238   MVT InVT = In.getSimpleValueType();
14239   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14240
14241   MVT InSVT = InVT.getScalarType();
14242   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14243
14244   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14245     return SDValue();
14246   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14247     return SDValue();
14248
14249   SDLoc dl(Op);
14250
14251   // SSE41 targets can use the pmovsx* instructions directly.
14252   if (Subtarget->hasSSE41())
14253     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14254
14255   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14256   SDValue Curr = In;
14257   MVT CurrVT = InVT;
14258
14259   // As SRAI is only available on i16/i32 types, we expand only up to i32
14260   // and handle i64 separately.
14261   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14262     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14263     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14264     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14265     Curr = DAG.getBitcast(CurrVT, Curr);
14266   }
14267
14268   SDValue SignExt = Curr;
14269   if (CurrVT != InVT) {
14270     unsigned SignExtShift =
14271         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14272     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14273                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14274   }
14275
14276   if (CurrVT == VT)
14277     return SignExt;
14278
14279   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14280     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14281                                DAG.getConstant(31, dl, MVT::i8));
14282     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14283     return DAG.getBitcast(VT, Ext);
14284   }
14285
14286   return SDValue();
14287 }
14288
14289 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14290                                 SelectionDAG &DAG) {
14291   MVT VT = Op->getSimpleValueType(0);
14292   SDValue In = Op->getOperand(0);
14293   MVT InVT = In.getSimpleValueType();
14294   SDLoc dl(Op);
14295
14296   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14297     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14298
14299   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14300       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14301       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14302     return SDValue();
14303
14304   if (Subtarget->hasInt256())
14305     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14306
14307   // Optimize vectors in AVX mode
14308   // Sign extend  v8i16 to v8i32 and
14309   //              v4i32 to v4i64
14310   //
14311   // Divide input vector into two parts
14312   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14313   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14314   // concat the vectors to original VT
14315
14316   unsigned NumElems = InVT.getVectorNumElements();
14317   SDValue Undef = DAG.getUNDEF(InVT);
14318
14319   SmallVector<int,8> ShufMask1(NumElems, -1);
14320   for (unsigned i = 0; i != NumElems/2; ++i)
14321     ShufMask1[i] = i;
14322
14323   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14324
14325   SmallVector<int,8> ShufMask2(NumElems, -1);
14326   for (unsigned i = 0; i != NumElems/2; ++i)
14327     ShufMask2[i] = i + NumElems/2;
14328
14329   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14330
14331   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14332                                 VT.getVectorNumElements()/2);
14333
14334   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14335   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14336
14337   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14338 }
14339
14340 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14341 // may emit an illegal shuffle but the expansion is still better than scalar
14342 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14343 // we'll emit a shuffle and a arithmetic shift.
14344 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14345 // TODO: It is possible to support ZExt by zeroing the undef values during
14346 // the shuffle phase or after the shuffle.
14347 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14348                                  SelectionDAG &DAG) {
14349   MVT RegVT = Op.getSimpleValueType();
14350   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14351   assert(RegVT.isInteger() &&
14352          "We only custom lower integer vector sext loads.");
14353
14354   // Nothing useful we can do without SSE2 shuffles.
14355   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14356
14357   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14358   SDLoc dl(Ld);
14359   EVT MemVT = Ld->getMemoryVT();
14360   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14361   unsigned RegSz = RegVT.getSizeInBits();
14362
14363   ISD::LoadExtType Ext = Ld->getExtensionType();
14364
14365   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14366          && "Only anyext and sext are currently implemented.");
14367   assert(MemVT != RegVT && "Cannot extend to the same type");
14368   assert(MemVT.isVector() && "Must load a vector from memory");
14369
14370   unsigned NumElems = RegVT.getVectorNumElements();
14371   unsigned MemSz = MemVT.getSizeInBits();
14372   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14373
14374   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14375     // The only way in which we have a legal 256-bit vector result but not the
14376     // integer 256-bit operations needed to directly lower a sextload is if we
14377     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14378     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14379     // correctly legalized. We do this late to allow the canonical form of
14380     // sextload to persist throughout the rest of the DAG combiner -- it wants
14381     // to fold together any extensions it can, and so will fuse a sign_extend
14382     // of an sextload into a sextload targeting a wider value.
14383     SDValue Load;
14384     if (MemSz == 128) {
14385       // Just switch this to a normal load.
14386       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14387                                        "it must be a legal 128-bit vector "
14388                                        "type!");
14389       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14390                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14391                   Ld->isInvariant(), Ld->getAlignment());
14392     } else {
14393       assert(MemSz < 128 &&
14394              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14395       // Do an sext load to a 128-bit vector type. We want to use the same
14396       // number of elements, but elements half as wide. This will end up being
14397       // recursively lowered by this routine, but will succeed as we definitely
14398       // have all the necessary features if we're using AVX1.
14399       EVT HalfEltVT =
14400           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14401       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14402       Load =
14403           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14404                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14405                          Ld->isNonTemporal(), Ld->isInvariant(),
14406                          Ld->getAlignment());
14407     }
14408
14409     // Replace chain users with the new chain.
14410     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14411     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14412
14413     // Finally, do a normal sign-extend to the desired register.
14414     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14415   }
14416
14417   // All sizes must be a power of two.
14418   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14419          "Non-power-of-two elements are not custom lowered!");
14420
14421   // Attempt to load the original value using scalar loads.
14422   // Find the largest scalar type that divides the total loaded size.
14423   MVT SclrLoadTy = MVT::i8;
14424   for (MVT Tp : MVT::integer_valuetypes()) {
14425     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14426       SclrLoadTy = Tp;
14427     }
14428   }
14429
14430   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14431   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14432       (64 <= MemSz))
14433     SclrLoadTy = MVT::f64;
14434
14435   // Calculate the number of scalar loads that we need to perform
14436   // in order to load our vector from memory.
14437   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14438
14439   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14440          "Can only lower sext loads with a single scalar load!");
14441
14442   unsigned loadRegZize = RegSz;
14443   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14444     loadRegZize = 128;
14445
14446   // Represent our vector as a sequence of elements which are the
14447   // largest scalar that we can load.
14448   EVT LoadUnitVecVT = EVT::getVectorVT(
14449       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14450
14451   // Represent the data using the same element type that is stored in
14452   // memory. In practice, we ''widen'' MemVT.
14453   EVT WideVecVT =
14454       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14455                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14456
14457   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14458          "Invalid vector type");
14459
14460   // We can't shuffle using an illegal type.
14461   assert(TLI.isTypeLegal(WideVecVT) &&
14462          "We only lower types that form legal widened vector types");
14463
14464   SmallVector<SDValue, 8> Chains;
14465   SDValue Ptr = Ld->getBasePtr();
14466   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14467                                       TLI.getPointerTy(DAG.getDataLayout()));
14468   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14469
14470   for (unsigned i = 0; i < NumLoads; ++i) {
14471     // Perform a single load.
14472     SDValue ScalarLoad =
14473         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14474                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14475                     Ld->getAlignment());
14476     Chains.push_back(ScalarLoad.getValue(1));
14477     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14478     // another round of DAGCombining.
14479     if (i == 0)
14480       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14481     else
14482       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14483                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14484
14485     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14486   }
14487
14488   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14489
14490   // Bitcast the loaded value to a vector of the original element type, in
14491   // the size of the target vector type.
14492   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14493   unsigned SizeRatio = RegSz / MemSz;
14494
14495   if (Ext == ISD::SEXTLOAD) {
14496     // If we have SSE4.1, we can directly emit a VSEXT node.
14497     if (Subtarget->hasSSE41()) {
14498       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14499       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14500       return Sext;
14501     }
14502
14503     // Otherwise we'll shuffle the small elements in the high bits of the
14504     // larger type and perform an arithmetic shift. If the shift is not legal
14505     // it's better to scalarize.
14506     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14507            "We can't implement a sext load without an arithmetic right shift!");
14508
14509     // Redistribute the loaded elements into the different locations.
14510     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14511     for (unsigned i = 0; i != NumElems; ++i)
14512       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14513
14514     SDValue Shuff = DAG.getVectorShuffle(
14515         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14516
14517     Shuff = DAG.getBitcast(RegVT, Shuff);
14518
14519     // Build the arithmetic shift.
14520     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14521                    MemVT.getVectorElementType().getSizeInBits();
14522     Shuff =
14523         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14524                     DAG.getConstant(Amt, dl, RegVT));
14525
14526     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14527     return Shuff;
14528   }
14529
14530   // Redistribute the loaded elements into the different locations.
14531   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14532   for (unsigned i = 0; i != NumElems; ++i)
14533     ShuffleVec[i * SizeRatio] = i;
14534
14535   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14536                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14537
14538   // Bitcast to the requested type.
14539   Shuff = DAG.getBitcast(RegVT, Shuff);
14540   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14541   return Shuff;
14542 }
14543
14544 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14545 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14546 // from the AND / OR.
14547 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14548   Opc = Op.getOpcode();
14549   if (Opc != ISD::OR && Opc != ISD::AND)
14550     return false;
14551   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14552           Op.getOperand(0).hasOneUse() &&
14553           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14554           Op.getOperand(1).hasOneUse());
14555 }
14556
14557 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14558 // 1 and that the SETCC node has a single use.
14559 static bool isXor1OfSetCC(SDValue Op) {
14560   if (Op.getOpcode() != ISD::XOR)
14561     return false;
14562   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14563   if (N1C && N1C->getAPIntValue() == 1) {
14564     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14565       Op.getOperand(0).hasOneUse();
14566   }
14567   return false;
14568 }
14569
14570 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14571   bool addTest = true;
14572   SDValue Chain = Op.getOperand(0);
14573   SDValue Cond  = Op.getOperand(1);
14574   SDValue Dest  = Op.getOperand(2);
14575   SDLoc dl(Op);
14576   SDValue CC;
14577   bool Inverted = false;
14578
14579   if (Cond.getOpcode() == ISD::SETCC) {
14580     // Check for setcc([su]{add,sub,mul}o == 0).
14581     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14582         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14583         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14584         Cond.getOperand(0).getResNo() == 1 &&
14585         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14586          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14587          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14588          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14589          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14590          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14591       Inverted = true;
14592       Cond = Cond.getOperand(0);
14593     } else {
14594       SDValue NewCond = LowerSETCC(Cond, DAG);
14595       if (NewCond.getNode())
14596         Cond = NewCond;
14597     }
14598   }
14599 #if 0
14600   // FIXME: LowerXALUO doesn't handle these!!
14601   else if (Cond.getOpcode() == X86ISD::ADD  ||
14602            Cond.getOpcode() == X86ISD::SUB  ||
14603            Cond.getOpcode() == X86ISD::SMUL ||
14604            Cond.getOpcode() == X86ISD::UMUL)
14605     Cond = LowerXALUO(Cond, DAG);
14606 #endif
14607
14608   // Look pass (and (setcc_carry (cmp ...)), 1).
14609   if (Cond.getOpcode() == ISD::AND &&
14610       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14611     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14612     if (C && C->getAPIntValue() == 1)
14613       Cond = Cond.getOperand(0);
14614   }
14615
14616   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14617   // setting operand in place of the X86ISD::SETCC.
14618   unsigned CondOpcode = Cond.getOpcode();
14619   if (CondOpcode == X86ISD::SETCC ||
14620       CondOpcode == X86ISD::SETCC_CARRY) {
14621     CC = Cond.getOperand(0);
14622
14623     SDValue Cmp = Cond.getOperand(1);
14624     unsigned Opc = Cmp.getOpcode();
14625     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14626     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14627       Cond = Cmp;
14628       addTest = false;
14629     } else {
14630       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14631       default: break;
14632       case X86::COND_O:
14633       case X86::COND_B:
14634         // These can only come from an arithmetic instruction with overflow,
14635         // e.g. SADDO, UADDO.
14636         Cond = Cond.getNode()->getOperand(1);
14637         addTest = false;
14638         break;
14639       }
14640     }
14641   }
14642   CondOpcode = Cond.getOpcode();
14643   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14644       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14645       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14646        Cond.getOperand(0).getValueType() != MVT::i8)) {
14647     SDValue LHS = Cond.getOperand(0);
14648     SDValue RHS = Cond.getOperand(1);
14649     unsigned X86Opcode;
14650     unsigned X86Cond;
14651     SDVTList VTs;
14652     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14653     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14654     // X86ISD::INC).
14655     switch (CondOpcode) {
14656     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14657     case ISD::SADDO:
14658       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14659         if (C->isOne()) {
14660           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14661           break;
14662         }
14663       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14664     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14665     case ISD::SSUBO:
14666       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14667         if (C->isOne()) {
14668           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14669           break;
14670         }
14671       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14672     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14673     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14674     default: llvm_unreachable("unexpected overflowing operator");
14675     }
14676     if (Inverted)
14677       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14678     if (CondOpcode == ISD::UMULO)
14679       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14680                           MVT::i32);
14681     else
14682       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14683
14684     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14685
14686     if (CondOpcode == ISD::UMULO)
14687       Cond = X86Op.getValue(2);
14688     else
14689       Cond = X86Op.getValue(1);
14690
14691     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14692     addTest = false;
14693   } else {
14694     unsigned CondOpc;
14695     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14696       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14697       if (CondOpc == ISD::OR) {
14698         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14699         // two branches instead of an explicit OR instruction with a
14700         // separate test.
14701         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14702             isX86LogicalCmp(Cmp)) {
14703           CC = Cond.getOperand(0).getOperand(0);
14704           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14705                               Chain, Dest, CC, Cmp);
14706           CC = Cond.getOperand(1).getOperand(0);
14707           Cond = Cmp;
14708           addTest = false;
14709         }
14710       } else { // ISD::AND
14711         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14712         // two branches instead of an explicit AND instruction with a
14713         // separate test. However, we only do this if this block doesn't
14714         // have a fall-through edge, because this requires an explicit
14715         // jmp when the condition is false.
14716         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14717             isX86LogicalCmp(Cmp) &&
14718             Op.getNode()->hasOneUse()) {
14719           X86::CondCode CCode =
14720             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14721           CCode = X86::GetOppositeBranchCondition(CCode);
14722           CC = DAG.getConstant(CCode, dl, MVT::i8);
14723           SDNode *User = *Op.getNode()->use_begin();
14724           // Look for an unconditional branch following this conditional branch.
14725           // We need this because we need to reverse the successors in order
14726           // to implement FCMP_OEQ.
14727           if (User->getOpcode() == ISD::BR) {
14728             SDValue FalseBB = User->getOperand(1);
14729             SDNode *NewBR =
14730               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14731             assert(NewBR == User);
14732             (void)NewBR;
14733             Dest = FalseBB;
14734
14735             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14736                                 Chain, Dest, CC, Cmp);
14737             X86::CondCode CCode =
14738               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14739             CCode = X86::GetOppositeBranchCondition(CCode);
14740             CC = DAG.getConstant(CCode, dl, MVT::i8);
14741             Cond = Cmp;
14742             addTest = false;
14743           }
14744         }
14745       }
14746     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14747       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14748       // It should be transformed during dag combiner except when the condition
14749       // is set by a arithmetics with overflow node.
14750       X86::CondCode CCode =
14751         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14752       CCode = X86::GetOppositeBranchCondition(CCode);
14753       CC = DAG.getConstant(CCode, dl, MVT::i8);
14754       Cond = Cond.getOperand(0).getOperand(1);
14755       addTest = false;
14756     } else if (Cond.getOpcode() == ISD::SETCC &&
14757                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14758       // For FCMP_OEQ, we can emit
14759       // two branches instead of an explicit AND instruction with a
14760       // separate test. However, we only do this if this block doesn't
14761       // have a fall-through edge, because this requires an explicit
14762       // jmp when the condition is false.
14763       if (Op.getNode()->hasOneUse()) {
14764         SDNode *User = *Op.getNode()->use_begin();
14765         // Look for an unconditional branch following this conditional branch.
14766         // We need this because we need to reverse the successors in order
14767         // to implement FCMP_OEQ.
14768         if (User->getOpcode() == ISD::BR) {
14769           SDValue FalseBB = User->getOperand(1);
14770           SDNode *NewBR =
14771             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14772           assert(NewBR == User);
14773           (void)NewBR;
14774           Dest = FalseBB;
14775
14776           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14777                                     Cond.getOperand(0), Cond.getOperand(1));
14778           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14779           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14780           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14781                               Chain, Dest, CC, Cmp);
14782           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14783           Cond = Cmp;
14784           addTest = false;
14785         }
14786       }
14787     } else if (Cond.getOpcode() == ISD::SETCC &&
14788                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14789       // For FCMP_UNE, we can emit
14790       // two branches instead of an explicit AND instruction with a
14791       // separate test. However, we only do this if this block doesn't
14792       // have a fall-through edge, because this requires an explicit
14793       // jmp when the condition is false.
14794       if (Op.getNode()->hasOneUse()) {
14795         SDNode *User = *Op.getNode()->use_begin();
14796         // Look for an unconditional branch following this conditional branch.
14797         // We need this because we need to reverse the successors in order
14798         // to implement FCMP_UNE.
14799         if (User->getOpcode() == ISD::BR) {
14800           SDValue FalseBB = User->getOperand(1);
14801           SDNode *NewBR =
14802             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14803           assert(NewBR == User);
14804           (void)NewBR;
14805
14806           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14807                                     Cond.getOperand(0), Cond.getOperand(1));
14808           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14809           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14810           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14811                               Chain, Dest, CC, Cmp);
14812           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14813           Cond = Cmp;
14814           addTest = false;
14815           Dest = FalseBB;
14816         }
14817       }
14818     }
14819   }
14820
14821   if (addTest) {
14822     // Look pass the truncate if the high bits are known zero.
14823     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14824         Cond = Cond.getOperand(0);
14825
14826     // We know the result of AND is compared against zero. Try to match
14827     // it to BT.
14828     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14829       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14830       if (NewSetCC.getNode()) {
14831         CC = NewSetCC.getOperand(0);
14832         Cond = NewSetCC.getOperand(1);
14833         addTest = false;
14834       }
14835     }
14836   }
14837
14838   if (addTest) {
14839     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14840     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14841     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14842   }
14843   Cond = ConvertCmpIfNecessary(Cond, DAG);
14844   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14845                      Chain, Dest, CC, Cond);
14846 }
14847
14848 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14849 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14850 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14851 // that the guard pages used by the OS virtual memory manager are allocated in
14852 // correct sequence.
14853 SDValue
14854 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14855                                            SelectionDAG &DAG) const {
14856   MachineFunction &MF = DAG.getMachineFunction();
14857   bool SplitStack = MF.shouldSplitStack();
14858   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14859                SplitStack;
14860   SDLoc dl(Op);
14861
14862   if (!Lower) {
14863     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14864     SDNode* Node = Op.getNode();
14865
14866     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14867     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14868         " not tell us which reg is the stack pointer!");
14869     EVT VT = Node->getValueType(0);
14870     SDValue Tmp1 = SDValue(Node, 0);
14871     SDValue Tmp2 = SDValue(Node, 1);
14872     SDValue Tmp3 = Node->getOperand(2);
14873     SDValue Chain = Tmp1.getOperand(0);
14874
14875     // Chain the dynamic stack allocation so that it doesn't modify the stack
14876     // pointer when other instructions are using the stack.
14877     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14878         SDLoc(Node));
14879
14880     SDValue Size = Tmp2.getOperand(1);
14881     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14882     Chain = SP.getValue(1);
14883     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14884     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14885     unsigned StackAlign = TFI.getStackAlignment();
14886     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14887     if (Align > StackAlign)
14888       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14889           DAG.getConstant(-(uint64_t)Align, dl, VT));
14890     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14891
14892     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14893         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14894         SDLoc(Node));
14895
14896     SDValue Ops[2] = { Tmp1, Tmp2 };
14897     return DAG.getMergeValues(Ops, dl);
14898   }
14899
14900   // Get the inputs.
14901   SDValue Chain = Op.getOperand(0);
14902   SDValue Size  = Op.getOperand(1);
14903   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14904   EVT VT = Op.getNode()->getValueType(0);
14905
14906   bool Is64Bit = Subtarget->is64Bit();
14907   MVT SPTy = getPointerTy(DAG.getDataLayout());
14908
14909   if (SplitStack) {
14910     MachineRegisterInfo &MRI = MF.getRegInfo();
14911
14912     if (Is64Bit) {
14913       // The 64 bit implementation of segmented stacks needs to clobber both r10
14914       // r11. This makes it impossible to use it along with nested parameters.
14915       const Function *F = MF.getFunction();
14916
14917       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14918            I != E; ++I)
14919         if (I->hasNestAttr())
14920           report_fatal_error("Cannot use segmented stacks with functions that "
14921                              "have nested arguments.");
14922     }
14923
14924     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14925     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14926     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14927     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14928                                 DAG.getRegister(Vreg, SPTy));
14929     SDValue Ops1[2] = { Value, Chain };
14930     return DAG.getMergeValues(Ops1, dl);
14931   } else {
14932     SDValue Flag;
14933     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14934
14935     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14936     Flag = Chain.getValue(1);
14937     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14938
14939     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14940
14941     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14942     unsigned SPReg = RegInfo->getStackRegister();
14943     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14944     Chain = SP.getValue(1);
14945
14946     if (Align) {
14947       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14948                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14949       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14950     }
14951
14952     SDValue Ops1[2] = { SP, Chain };
14953     return DAG.getMergeValues(Ops1, dl);
14954   }
14955 }
14956
14957 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14958   MachineFunction &MF = DAG.getMachineFunction();
14959   auto PtrVT = getPointerTy(MF.getDataLayout());
14960   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14961
14962   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14963   SDLoc DL(Op);
14964
14965   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14966     // vastart just stores the address of the VarArgsFrameIndex slot into the
14967     // memory location argument.
14968     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14969     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14970                         MachinePointerInfo(SV), false, false, 0);
14971   }
14972
14973   // __va_list_tag:
14974   //   gp_offset         (0 - 6 * 8)
14975   //   fp_offset         (48 - 48 + 8 * 16)
14976   //   overflow_arg_area (point to parameters coming in memory).
14977   //   reg_save_area
14978   SmallVector<SDValue, 8> MemOps;
14979   SDValue FIN = Op.getOperand(1);
14980   // Store gp_offset
14981   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14982                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14983                                                DL, MVT::i32),
14984                                FIN, MachinePointerInfo(SV), false, false, 0);
14985   MemOps.push_back(Store);
14986
14987   // Store fp_offset
14988   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14989   Store = DAG.getStore(Op.getOperand(0), DL,
14990                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14991                                        MVT::i32),
14992                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14993   MemOps.push_back(Store);
14994
14995   // Store ptr to overflow_arg_area
14996   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14997   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14998   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14999                        MachinePointerInfo(SV, 8),
15000                        false, false, 0);
15001   MemOps.push_back(Store);
15002
15003   // Store ptr to reg_save_area.
15004   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
15005   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
15006   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
15007                        MachinePointerInfo(SV, 16), false, false, 0);
15008   MemOps.push_back(Store);
15009   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
15010 }
15011
15012 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
15013   assert(Subtarget->is64Bit() &&
15014          "LowerVAARG only handles 64-bit va_arg!");
15015   assert((Subtarget->isTargetLinux() ||
15016           Subtarget->isTargetDarwin()) &&
15017           "Unhandled target in LowerVAARG");
15018   assert(Op.getNode()->getNumOperands() == 4);
15019   SDValue Chain = Op.getOperand(0);
15020   SDValue SrcPtr = Op.getOperand(1);
15021   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
15022   unsigned Align = Op.getConstantOperandVal(3);
15023   SDLoc dl(Op);
15024
15025   EVT ArgVT = Op.getNode()->getValueType(0);
15026   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15027   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15028   uint8_t ArgMode;
15029
15030   // Decide which area this value should be read from.
15031   // TODO: Implement the AMD64 ABI in its entirety. This simple
15032   // selection mechanism works only for the basic types.
15033   if (ArgVT == MVT::f80) {
15034     llvm_unreachable("va_arg for f80 not yet implemented");
15035   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15036     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15037   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15038     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15039   } else {
15040     llvm_unreachable("Unhandled argument type in LowerVAARG");
15041   }
15042
15043   if (ArgMode == 2) {
15044     // Sanity Check: Make sure using fp_offset makes sense.
15045     assert(!Subtarget->useSoftFloat() &&
15046            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15047                Attribute::NoImplicitFloat)) &&
15048            Subtarget->hasSSE1());
15049   }
15050
15051   // Insert VAARG_64 node into the DAG
15052   // VAARG_64 returns two values: Variable Argument Address, Chain
15053   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15054                        DAG.getConstant(ArgMode, dl, MVT::i8),
15055                        DAG.getConstant(Align, dl, MVT::i32)};
15056   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15057   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15058                                           VTs, InstOps, MVT::i64,
15059                                           MachinePointerInfo(SV),
15060                                           /*Align=*/0,
15061                                           /*Volatile=*/false,
15062                                           /*ReadMem=*/true,
15063                                           /*WriteMem=*/true);
15064   Chain = VAARG.getValue(1);
15065
15066   // Load the next argument and return it
15067   return DAG.getLoad(ArgVT, dl,
15068                      Chain,
15069                      VAARG,
15070                      MachinePointerInfo(),
15071                      false, false, false, 0);
15072 }
15073
15074 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15075                            SelectionDAG &DAG) {
15076   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15077   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15078   SDValue Chain = Op.getOperand(0);
15079   SDValue DstPtr = Op.getOperand(1);
15080   SDValue SrcPtr = Op.getOperand(2);
15081   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15082   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15083   SDLoc DL(Op);
15084
15085   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15086                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15087                        false, false,
15088                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15089 }
15090
15091 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15092 // amount is a constant. Takes immediate version of shift as input.
15093 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15094                                           SDValue SrcOp, uint64_t ShiftAmt,
15095                                           SelectionDAG &DAG) {
15096   MVT ElementType = VT.getVectorElementType();
15097
15098   // Fold this packed shift into its first operand if ShiftAmt is 0.
15099   if (ShiftAmt == 0)
15100     return SrcOp;
15101
15102   // Check for ShiftAmt >= element width
15103   if (ShiftAmt >= ElementType.getSizeInBits()) {
15104     if (Opc == X86ISD::VSRAI)
15105       ShiftAmt = ElementType.getSizeInBits() - 1;
15106     else
15107       return DAG.getConstant(0, dl, VT);
15108   }
15109
15110   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15111          && "Unknown target vector shift-by-constant node");
15112
15113   // Fold this packed vector shift into a build vector if SrcOp is a
15114   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15115   if (VT == SrcOp.getSimpleValueType() &&
15116       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15117     SmallVector<SDValue, 8> Elts;
15118     unsigned NumElts = SrcOp->getNumOperands();
15119     ConstantSDNode *ND;
15120
15121     switch(Opc) {
15122     default: llvm_unreachable(nullptr);
15123     case X86ISD::VSHLI:
15124       for (unsigned i=0; i!=NumElts; ++i) {
15125         SDValue CurrentOp = SrcOp->getOperand(i);
15126         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15127           Elts.push_back(CurrentOp);
15128           continue;
15129         }
15130         ND = cast<ConstantSDNode>(CurrentOp);
15131         const APInt &C = ND->getAPIntValue();
15132         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15133       }
15134       break;
15135     case X86ISD::VSRLI:
15136       for (unsigned i=0; i!=NumElts; ++i) {
15137         SDValue CurrentOp = SrcOp->getOperand(i);
15138         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15139           Elts.push_back(CurrentOp);
15140           continue;
15141         }
15142         ND = cast<ConstantSDNode>(CurrentOp);
15143         const APInt &C = ND->getAPIntValue();
15144         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15145       }
15146       break;
15147     case X86ISD::VSRAI:
15148       for (unsigned i=0; i!=NumElts; ++i) {
15149         SDValue CurrentOp = SrcOp->getOperand(i);
15150         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15151           Elts.push_back(CurrentOp);
15152           continue;
15153         }
15154         ND = cast<ConstantSDNode>(CurrentOp);
15155         const APInt &C = ND->getAPIntValue();
15156         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15157       }
15158       break;
15159     }
15160
15161     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15162   }
15163
15164   return DAG.getNode(Opc, dl, VT, SrcOp,
15165                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15166 }
15167
15168 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15169 // may or may not be a constant. Takes immediate version of shift as input.
15170 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15171                                    SDValue SrcOp, SDValue ShAmt,
15172                                    SelectionDAG &DAG) {
15173   MVT SVT = ShAmt.getSimpleValueType();
15174   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15175
15176   // Catch shift-by-constant.
15177   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15178     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15179                                       CShAmt->getZExtValue(), DAG);
15180
15181   // Change opcode to non-immediate version
15182   switch (Opc) {
15183     default: llvm_unreachable("Unknown target vector shift node");
15184     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15185     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15186     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15187   }
15188
15189   const X86Subtarget &Subtarget =
15190       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15191   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15192       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15193     // Let the shuffle legalizer expand this shift amount node.
15194     SDValue Op0 = ShAmt.getOperand(0);
15195     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15196     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15197   } else {
15198     // Need to build a vector containing shift amount.
15199     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15200     SmallVector<SDValue, 4> ShOps;
15201     ShOps.push_back(ShAmt);
15202     if (SVT == MVT::i32) {
15203       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15204       ShOps.push_back(DAG.getUNDEF(SVT));
15205     }
15206     ShOps.push_back(DAG.getUNDEF(SVT));
15207
15208     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15209     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15210   }
15211
15212   // The return type has to be a 128-bit type with the same element
15213   // type as the input type.
15214   MVT EltVT = VT.getVectorElementType();
15215   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15216
15217   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15218   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15219 }
15220
15221 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15222 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15223 /// necessary casting for \p Mask when lowering masking intrinsics.
15224 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15225                                     SDValue PreservedSrc,
15226                                     const X86Subtarget *Subtarget,
15227                                     SelectionDAG &DAG) {
15228     EVT VT = Op.getValueType();
15229     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15230                                   MVT::i1, VT.getVectorNumElements());
15231     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15232                                      Mask.getValueType().getSizeInBits());
15233     SDLoc dl(Op);
15234
15235     assert(MaskVT.isSimple() && "invalid mask type");
15236
15237     if (isAllOnes(Mask))
15238       return Op;
15239
15240     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15241     // are extracted by EXTRACT_SUBVECTOR.
15242     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15243                                 DAG.getBitcast(BitcastVT, Mask),
15244                                 DAG.getIntPtrConstant(0, dl));
15245
15246     switch (Op.getOpcode()) {
15247       default: break;
15248       case X86ISD::PCMPEQM:
15249       case X86ISD::PCMPGTM:
15250       case X86ISD::CMPM:
15251       case X86ISD::CMPMU:
15252         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15253     }
15254     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15255       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15256     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15257 }
15258
15259 /// \brief Creates an SDNode for a predicated scalar operation.
15260 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15261 /// The mask is comming as MVT::i8 and it should be truncated
15262 /// to MVT::i1 while lowering masking intrinsics.
15263 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15264 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15265 /// a scalar instruction.
15266 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15267                                     SDValue PreservedSrc,
15268                                     const X86Subtarget *Subtarget,
15269                                     SelectionDAG &DAG) {
15270     if (isAllOnes(Mask))
15271       return Op;
15272
15273     EVT VT = Op.getValueType();
15274     SDLoc dl(Op);
15275     // The mask should be of type MVT::i1
15276     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15277
15278     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15279       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15280     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15281 }
15282
15283 static int getSEHRegistrationNodeSize(const Function *Fn) {
15284   if (!Fn->hasPersonalityFn())
15285     report_fatal_error(
15286         "querying registration node size for function without personality");
15287   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15288   // WinEHStatePass for the full struct definition.
15289   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15290   case EHPersonality::MSVC_X86SEH: return 24;
15291   case EHPersonality::MSVC_CXX: return 16;
15292   default: break;
15293   }
15294   report_fatal_error("can only recover FP for MSVC EH personality functions");
15295 }
15296
15297 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15298 /// function or when returning to a parent frame after catching an exception, we
15299 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15300 /// Here's the math:
15301 ///   RegNodeBase = EntryEBP - RegNodeSize
15302 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15303 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15304 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15305 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15306                                    SDValue EntryEBP) {
15307   MachineFunction &MF = DAG.getMachineFunction();
15308   SDLoc dl;
15309
15310   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15311   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15312
15313   // It's possible that the parent function no longer has a personality function
15314   // if the exceptional code was optimized away, in which case we just return
15315   // the incoming EBP.
15316   if (!Fn->hasPersonalityFn())
15317     return EntryEBP;
15318
15319   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15320
15321   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15322   // registration.
15323   MCSymbol *OffsetSym =
15324       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15325           GlobalValue::getRealLinkageName(Fn->getName()));
15326   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15327   SDValue RegNodeFrameOffset =
15328       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15329
15330   // RegNodeBase = EntryEBP - RegNodeSize
15331   // ParentFP = RegNodeBase - RegNodeFrameOffset
15332   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15333                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15334   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15335 }
15336
15337 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15338                                        SelectionDAG &DAG) {
15339   SDLoc dl(Op);
15340   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15341   EVT VT = Op.getValueType();
15342   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15343   if (IntrData) {
15344     switch(IntrData->Type) {
15345     case INTR_TYPE_1OP:
15346       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15347     case INTR_TYPE_2OP:
15348       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15349         Op.getOperand(2));
15350     case INTR_TYPE_3OP:
15351       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15352         Op.getOperand(2), Op.getOperand(3));
15353     case INTR_TYPE_4OP:
15354       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15355         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15356     case INTR_TYPE_1OP_MASK_RM: {
15357       SDValue Src = Op.getOperand(1);
15358       SDValue PassThru = Op.getOperand(2);
15359       SDValue Mask = Op.getOperand(3);
15360       SDValue RoundingMode;
15361       if (Op.getNumOperands() == 4)
15362         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15363       else
15364         RoundingMode = Op.getOperand(4);
15365       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15366       if (IntrWithRoundingModeOpcode != 0) {
15367         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15368         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15369           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15370                                       dl, Op.getValueType(), Src, RoundingMode),
15371                                       Mask, PassThru, Subtarget, DAG);
15372       }
15373       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15374                                               RoundingMode),
15375                                   Mask, PassThru, Subtarget, DAG);
15376     }
15377     case INTR_TYPE_1OP_MASK: {
15378       SDValue Src = Op.getOperand(1);
15379       SDValue Passthru = Op.getOperand(2);
15380       SDValue Mask = Op.getOperand(3);
15381       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15382                                   Mask, Passthru, Subtarget, DAG);
15383     }
15384     case INTR_TYPE_SCALAR_MASK_RM: {
15385       SDValue Src1 = Op.getOperand(1);
15386       SDValue Src2 = Op.getOperand(2);
15387       SDValue Src0 = Op.getOperand(3);
15388       SDValue Mask = Op.getOperand(4);
15389       // There are 2 kinds of intrinsics in this group:
15390       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15391       // (2) With rounding mode and sae - 7 operands.
15392       if (Op.getNumOperands() == 6) {
15393         SDValue Sae  = Op.getOperand(5);
15394         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15395         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15396                                                 Sae),
15397                                     Mask, Src0, Subtarget, DAG);
15398       }
15399       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15400       SDValue RoundingMode  = Op.getOperand(5);
15401       SDValue Sae  = Op.getOperand(6);
15402       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15403                                               RoundingMode, Sae),
15404                                   Mask, Src0, Subtarget, DAG);
15405     }
15406     case INTR_TYPE_2OP_MASK: {
15407       SDValue Src1 = Op.getOperand(1);
15408       SDValue Src2 = Op.getOperand(2);
15409       SDValue PassThru = Op.getOperand(3);
15410       SDValue Mask = Op.getOperand(4);
15411       // We specify 2 possible opcodes for intrinsics with rounding modes.
15412       // First, we check if the intrinsic may have non-default rounding mode,
15413       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15414       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15415       if (IntrWithRoundingModeOpcode != 0) {
15416         SDValue Rnd = Op.getOperand(5);
15417         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15418         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15419           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15420                                       dl, Op.getValueType(),
15421                                       Src1, Src2, Rnd),
15422                                       Mask, PassThru, Subtarget, DAG);
15423         }
15424       }
15425       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15426                                               Src1,Src2),
15427                                   Mask, PassThru, Subtarget, DAG);
15428     }
15429     case INTR_TYPE_2OP_MASK_RM: {
15430       SDValue Src1 = Op.getOperand(1);
15431       SDValue Src2 = Op.getOperand(2);
15432       SDValue PassThru = Op.getOperand(3);
15433       SDValue Mask = Op.getOperand(4);
15434       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15435       // First, we check if the intrinsic have rounding mode (6 operands),
15436       // if not, we set rounding mode to "current".
15437       SDValue Rnd;
15438       if (Op.getNumOperands() == 6)
15439         Rnd = Op.getOperand(5);
15440       else
15441         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15442       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15443                                               Src1, Src2, Rnd),
15444                                   Mask, PassThru, Subtarget, DAG);
15445     }
15446     case INTR_TYPE_3OP_MASK: {
15447       SDValue Src1 = Op.getOperand(1);
15448       SDValue Src2 = Op.getOperand(2);
15449       SDValue Src3 = Op.getOperand(3);
15450       SDValue PassThru = Op.getOperand(4);
15451       SDValue Mask = Op.getOperand(5);
15452       // We specify 2 possible opcodes for intrinsics with rounding modes.
15453       // First, we check if the intrinsic may have non-default rounding mode,
15454       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15455       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15456       if (IntrWithRoundingModeOpcode != 0) {
15457         SDValue Rnd = Op.getOperand(6);
15458         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15459         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15460           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15461                                       dl, Op.getValueType(),
15462                                       Src1, Src2, Src3, Rnd),
15463                                       Mask, PassThru, Subtarget, DAG);
15464         }
15465       }
15466       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15467                                               Src1, Src2, Src3),
15468                                   Mask, PassThru, Subtarget, DAG);
15469     }
15470     case VPERM_3OP_MASKZ:
15471     case VPERM_3OP_MASK:
15472     case FMA_OP_MASK3:
15473     case FMA_OP_MASKZ:
15474     case FMA_OP_MASK: {
15475       SDValue Src1 = Op.getOperand(1);
15476       SDValue Src2 = Op.getOperand(2);
15477       SDValue Src3 = Op.getOperand(3);
15478       SDValue Mask = Op.getOperand(4);
15479       EVT VT = Op.getValueType();
15480       SDValue PassThru = SDValue();
15481
15482       // set PassThru element
15483       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15484         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15485       else if (IntrData->Type == FMA_OP_MASK3)
15486         PassThru = Src3;
15487       else
15488         PassThru = Src1;
15489
15490       // We specify 2 possible opcodes for intrinsics with rounding modes.
15491       // First, we check if the intrinsic may have non-default rounding mode,
15492       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15493       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15494       if (IntrWithRoundingModeOpcode != 0) {
15495         SDValue Rnd = Op.getOperand(5);
15496         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15497             X86::STATIC_ROUNDING::CUR_DIRECTION)
15498           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15499                                                   dl, Op.getValueType(),
15500                                                   Src1, Src2, Src3, Rnd),
15501                                       Mask, PassThru, Subtarget, DAG);
15502       }
15503       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15504                                               dl, Op.getValueType(),
15505                                               Src1, Src2, Src3),
15506                                   Mask, PassThru, Subtarget, DAG);
15507     }
15508     case CMP_MASK:
15509     case CMP_MASK_CC: {
15510       // Comparison intrinsics with masks.
15511       // Example of transformation:
15512       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15513       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15514       // (i8 (bitcast
15515       //   (v8i1 (insert_subvector undef,
15516       //           (v2i1 (and (PCMPEQM %a, %b),
15517       //                      (extract_subvector
15518       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15519       EVT VT = Op.getOperand(1).getValueType();
15520       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15521                                     VT.getVectorNumElements());
15522       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15523       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15524                                        Mask.getValueType().getSizeInBits());
15525       SDValue Cmp;
15526       if (IntrData->Type == CMP_MASK_CC) {
15527         SDValue CC = Op.getOperand(3);
15528         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15529         // We specify 2 possible opcodes for intrinsics with rounding modes.
15530         // First, we check if the intrinsic may have non-default rounding mode,
15531         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15532         if (IntrData->Opc1 != 0) {
15533           SDValue Rnd = Op.getOperand(5);
15534           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15535               X86::STATIC_ROUNDING::CUR_DIRECTION)
15536             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15537                               Op.getOperand(2), CC, Rnd);
15538         }
15539         //default rounding mode
15540         if(!Cmp.getNode())
15541             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15542                               Op.getOperand(2), CC);
15543
15544       } else {
15545         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15546         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15547                           Op.getOperand(2));
15548       }
15549       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15550                                              DAG.getTargetConstant(0, dl,
15551                                                                    MaskVT),
15552                                              Subtarget, DAG);
15553       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15554                                 DAG.getUNDEF(BitcastVT), CmpMask,
15555                                 DAG.getIntPtrConstant(0, dl));
15556       return DAG.getBitcast(Op.getValueType(), Res);
15557     }
15558     case COMI: { // Comparison intrinsics
15559       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15560       SDValue LHS = Op.getOperand(1);
15561       SDValue RHS = Op.getOperand(2);
15562       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15563       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15564       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15565       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15566                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15567       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15568     }
15569     case VSHIFT:
15570       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15571                                  Op.getOperand(1), Op.getOperand(2), DAG);
15572     case VSHIFT_MASK:
15573       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15574                                                       Op.getSimpleValueType(),
15575                                                       Op.getOperand(1),
15576                                                       Op.getOperand(2), DAG),
15577                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15578                                   DAG);
15579     case COMPRESS_EXPAND_IN_REG: {
15580       SDValue Mask = Op.getOperand(3);
15581       SDValue DataToCompress = Op.getOperand(1);
15582       SDValue PassThru = Op.getOperand(2);
15583       if (isAllOnes(Mask)) // return data as is
15584         return Op.getOperand(1);
15585
15586       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15587                                               DataToCompress),
15588                                   Mask, PassThru, Subtarget, DAG);
15589     }
15590     case BLEND: {
15591       SDValue Mask = Op.getOperand(3);
15592       EVT VT = Op.getValueType();
15593       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15594                                     VT.getVectorNumElements());
15595       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15596                                        Mask.getValueType().getSizeInBits());
15597       SDLoc dl(Op);
15598       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15599                                   DAG.getBitcast(BitcastVT, Mask),
15600                                   DAG.getIntPtrConstant(0, dl));
15601       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15602                          Op.getOperand(2));
15603     }
15604     default:
15605       break;
15606     }
15607   }
15608
15609   switch (IntNo) {
15610   default: return SDValue();    // Don't custom lower most intrinsics.
15611
15612   case Intrinsic::x86_avx2_permd:
15613   case Intrinsic::x86_avx2_permps:
15614     // Operands intentionally swapped. Mask is last operand to intrinsic,
15615     // but second operand for node/instruction.
15616     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15617                        Op.getOperand(2), Op.getOperand(1));
15618
15619   // ptest and testp intrinsics. The intrinsic these come from are designed to
15620   // return an integer value, not just an instruction so lower it to the ptest
15621   // or testp pattern and a setcc for the result.
15622   case Intrinsic::x86_sse41_ptestz:
15623   case Intrinsic::x86_sse41_ptestc:
15624   case Intrinsic::x86_sse41_ptestnzc:
15625   case Intrinsic::x86_avx_ptestz_256:
15626   case Intrinsic::x86_avx_ptestc_256:
15627   case Intrinsic::x86_avx_ptestnzc_256:
15628   case Intrinsic::x86_avx_vtestz_ps:
15629   case Intrinsic::x86_avx_vtestc_ps:
15630   case Intrinsic::x86_avx_vtestnzc_ps:
15631   case Intrinsic::x86_avx_vtestz_pd:
15632   case Intrinsic::x86_avx_vtestc_pd:
15633   case Intrinsic::x86_avx_vtestnzc_pd:
15634   case Intrinsic::x86_avx_vtestz_ps_256:
15635   case Intrinsic::x86_avx_vtestc_ps_256:
15636   case Intrinsic::x86_avx_vtestnzc_ps_256:
15637   case Intrinsic::x86_avx_vtestz_pd_256:
15638   case Intrinsic::x86_avx_vtestc_pd_256:
15639   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15640     bool IsTestPacked = false;
15641     unsigned X86CC;
15642     switch (IntNo) {
15643     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15644     case Intrinsic::x86_avx_vtestz_ps:
15645     case Intrinsic::x86_avx_vtestz_pd:
15646     case Intrinsic::x86_avx_vtestz_ps_256:
15647     case Intrinsic::x86_avx_vtestz_pd_256:
15648       IsTestPacked = true; // Fallthrough
15649     case Intrinsic::x86_sse41_ptestz:
15650     case Intrinsic::x86_avx_ptestz_256:
15651       // ZF = 1
15652       X86CC = X86::COND_E;
15653       break;
15654     case Intrinsic::x86_avx_vtestc_ps:
15655     case Intrinsic::x86_avx_vtestc_pd:
15656     case Intrinsic::x86_avx_vtestc_ps_256:
15657     case Intrinsic::x86_avx_vtestc_pd_256:
15658       IsTestPacked = true; // Fallthrough
15659     case Intrinsic::x86_sse41_ptestc:
15660     case Intrinsic::x86_avx_ptestc_256:
15661       // CF = 1
15662       X86CC = X86::COND_B;
15663       break;
15664     case Intrinsic::x86_avx_vtestnzc_ps:
15665     case Intrinsic::x86_avx_vtestnzc_pd:
15666     case Intrinsic::x86_avx_vtestnzc_ps_256:
15667     case Intrinsic::x86_avx_vtestnzc_pd_256:
15668       IsTestPacked = true; // Fallthrough
15669     case Intrinsic::x86_sse41_ptestnzc:
15670     case Intrinsic::x86_avx_ptestnzc_256:
15671       // ZF and CF = 0
15672       X86CC = X86::COND_A;
15673       break;
15674     }
15675
15676     SDValue LHS = Op.getOperand(1);
15677     SDValue RHS = Op.getOperand(2);
15678     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15679     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15680     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15681     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15682     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15683   }
15684   case Intrinsic::x86_avx512_kortestz_w:
15685   case Intrinsic::x86_avx512_kortestc_w: {
15686     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15687     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15688     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15689     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15690     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15691     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15692     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15693   }
15694
15695   case Intrinsic::x86_sse42_pcmpistria128:
15696   case Intrinsic::x86_sse42_pcmpestria128:
15697   case Intrinsic::x86_sse42_pcmpistric128:
15698   case Intrinsic::x86_sse42_pcmpestric128:
15699   case Intrinsic::x86_sse42_pcmpistrio128:
15700   case Intrinsic::x86_sse42_pcmpestrio128:
15701   case Intrinsic::x86_sse42_pcmpistris128:
15702   case Intrinsic::x86_sse42_pcmpestris128:
15703   case Intrinsic::x86_sse42_pcmpistriz128:
15704   case Intrinsic::x86_sse42_pcmpestriz128: {
15705     unsigned Opcode;
15706     unsigned X86CC;
15707     switch (IntNo) {
15708     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15709     case Intrinsic::x86_sse42_pcmpistria128:
15710       Opcode = X86ISD::PCMPISTRI;
15711       X86CC = X86::COND_A;
15712       break;
15713     case Intrinsic::x86_sse42_pcmpestria128:
15714       Opcode = X86ISD::PCMPESTRI;
15715       X86CC = X86::COND_A;
15716       break;
15717     case Intrinsic::x86_sse42_pcmpistric128:
15718       Opcode = X86ISD::PCMPISTRI;
15719       X86CC = X86::COND_B;
15720       break;
15721     case Intrinsic::x86_sse42_pcmpestric128:
15722       Opcode = X86ISD::PCMPESTRI;
15723       X86CC = X86::COND_B;
15724       break;
15725     case Intrinsic::x86_sse42_pcmpistrio128:
15726       Opcode = X86ISD::PCMPISTRI;
15727       X86CC = X86::COND_O;
15728       break;
15729     case Intrinsic::x86_sse42_pcmpestrio128:
15730       Opcode = X86ISD::PCMPESTRI;
15731       X86CC = X86::COND_O;
15732       break;
15733     case Intrinsic::x86_sse42_pcmpistris128:
15734       Opcode = X86ISD::PCMPISTRI;
15735       X86CC = X86::COND_S;
15736       break;
15737     case Intrinsic::x86_sse42_pcmpestris128:
15738       Opcode = X86ISD::PCMPESTRI;
15739       X86CC = X86::COND_S;
15740       break;
15741     case Intrinsic::x86_sse42_pcmpistriz128:
15742       Opcode = X86ISD::PCMPISTRI;
15743       X86CC = X86::COND_E;
15744       break;
15745     case Intrinsic::x86_sse42_pcmpestriz128:
15746       Opcode = X86ISD::PCMPESTRI;
15747       X86CC = X86::COND_E;
15748       break;
15749     }
15750     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15751     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15752     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15753     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15754                                 DAG.getConstant(X86CC, dl, MVT::i8),
15755                                 SDValue(PCMP.getNode(), 1));
15756     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15757   }
15758
15759   case Intrinsic::x86_sse42_pcmpistri128:
15760   case Intrinsic::x86_sse42_pcmpestri128: {
15761     unsigned Opcode;
15762     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15763       Opcode = X86ISD::PCMPISTRI;
15764     else
15765       Opcode = X86ISD::PCMPESTRI;
15766
15767     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15768     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15769     return DAG.getNode(Opcode, dl, VTs, NewOps);
15770   }
15771
15772   case Intrinsic::x86_seh_lsda: {
15773     // Compute the symbol for the LSDA. We know it'll get emitted later.
15774     MachineFunction &MF = DAG.getMachineFunction();
15775     SDValue Op1 = Op.getOperand(1);
15776     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15777     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15778         GlobalValue::getRealLinkageName(Fn->getName()));
15779
15780     // Generate a simple absolute symbol reference. This intrinsic is only
15781     // supported on 32-bit Windows, which isn't PIC.
15782     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15783     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15784   }
15785
15786   case Intrinsic::x86_seh_recoverfp: {
15787     SDValue FnOp = Op.getOperand(1);
15788     SDValue IncomingFPOp = Op.getOperand(2);
15789     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15790     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15791     if (!Fn)
15792       report_fatal_error(
15793           "llvm.x86.seh.recoverfp must take a function as the first argument");
15794     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15795   }
15796
15797   case Intrinsic::localaddress: {
15798     // Returns one of the stack, base, or frame pointer registers, depending on
15799     // which is used to reference local variables.
15800     MachineFunction &MF = DAG.getMachineFunction();
15801     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15802     unsigned Reg;
15803     if (RegInfo->hasBasePointer(MF))
15804       Reg = RegInfo->getBaseRegister();
15805     else // This function handles the SP or FP case.
15806       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15807     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15808   }
15809   }
15810 }
15811
15812 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15813                               SDValue Src, SDValue Mask, SDValue Base,
15814                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15815                               const X86Subtarget * Subtarget) {
15816   SDLoc dl(Op);
15817   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15818   if (!C)
15819     llvm_unreachable("Invalid scale type");
15820   unsigned ScaleVal = C->getZExtValue();
15821   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15822     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15823
15824   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15825   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15826                              Index.getSimpleValueType().getVectorNumElements());
15827   SDValue MaskInReg;
15828   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15829   if (MaskC)
15830     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15831   else {
15832     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15833                                      Mask.getValueType().getSizeInBits());
15834
15835     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15836     // are extracted by EXTRACT_SUBVECTOR.
15837     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15838                             DAG.getBitcast(BitcastVT, Mask),
15839                             DAG.getIntPtrConstant(0, dl));
15840   }
15841   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15842   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15843   SDValue Segment = DAG.getRegister(0, MVT::i32);
15844   if (Src.getOpcode() == ISD::UNDEF)
15845     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15846   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15847   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15848   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15849   return DAG.getMergeValues(RetOps, dl);
15850 }
15851
15852 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15853                                SDValue Src, SDValue Mask, SDValue Base,
15854                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15855   SDLoc dl(Op);
15856   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15857   if (!C)
15858     llvm_unreachable("Invalid scale type");
15859   unsigned ScaleVal = C->getZExtValue();
15860   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15861     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15862
15863   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15864   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15865   SDValue Segment = DAG.getRegister(0, MVT::i32);
15866   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15867                              Index.getSimpleValueType().getVectorNumElements());
15868   SDValue MaskInReg;
15869   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15870   if (MaskC)
15871     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15872   else {
15873     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15874                                      Mask.getValueType().getSizeInBits());
15875
15876     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15877     // are extracted by EXTRACT_SUBVECTOR.
15878     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15879                             DAG.getBitcast(BitcastVT, Mask),
15880                             DAG.getIntPtrConstant(0, dl));
15881   }
15882   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15883   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15884   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15885   return SDValue(Res, 1);
15886 }
15887
15888 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15889                                SDValue Mask, SDValue Base, SDValue Index,
15890                                SDValue ScaleOp, SDValue Chain) {
15891   SDLoc dl(Op);
15892   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15893   assert(C && "Invalid scale type");
15894   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15895   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15896   SDValue Segment = DAG.getRegister(0, MVT::i32);
15897   EVT MaskVT =
15898     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15899   SDValue MaskInReg;
15900   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15901   if (MaskC)
15902     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15903   else
15904     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15905   //SDVTList VTs = DAG.getVTList(MVT::Other);
15906   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15907   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15908   return SDValue(Res, 0);
15909 }
15910
15911 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15912 // read performance monitor counters (x86_rdpmc).
15913 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15914                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15915                               SmallVectorImpl<SDValue> &Results) {
15916   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15917   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15918   SDValue LO, HI;
15919
15920   // The ECX register is used to select the index of the performance counter
15921   // to read.
15922   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15923                                    N->getOperand(2));
15924   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15925
15926   // Reads the content of a 64-bit performance counter and returns it in the
15927   // registers EDX:EAX.
15928   if (Subtarget->is64Bit()) {
15929     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15930     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15931                             LO.getValue(2));
15932   } else {
15933     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15934     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15935                             LO.getValue(2));
15936   }
15937   Chain = HI.getValue(1);
15938
15939   if (Subtarget->is64Bit()) {
15940     // The EAX register is loaded with the low-order 32 bits. The EDX register
15941     // is loaded with the supported high-order bits of the counter.
15942     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15943                               DAG.getConstant(32, DL, MVT::i8));
15944     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15945     Results.push_back(Chain);
15946     return;
15947   }
15948
15949   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15950   SDValue Ops[] = { LO, HI };
15951   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15952   Results.push_back(Pair);
15953   Results.push_back(Chain);
15954 }
15955
15956 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15957 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15958 // also used to custom lower READCYCLECOUNTER nodes.
15959 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15960                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15961                               SmallVectorImpl<SDValue> &Results) {
15962   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15963   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15964   SDValue LO, HI;
15965
15966   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15967   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15968   // and the EAX register is loaded with the low-order 32 bits.
15969   if (Subtarget->is64Bit()) {
15970     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15971     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15972                             LO.getValue(2));
15973   } else {
15974     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15975     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15976                             LO.getValue(2));
15977   }
15978   SDValue Chain = HI.getValue(1);
15979
15980   if (Opcode == X86ISD::RDTSCP_DAG) {
15981     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15982
15983     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15984     // the ECX register. Add 'ecx' explicitly to the chain.
15985     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15986                                      HI.getValue(2));
15987     // Explicitly store the content of ECX at the location passed in input
15988     // to the 'rdtscp' intrinsic.
15989     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15990                          MachinePointerInfo(), false, false, 0);
15991   }
15992
15993   if (Subtarget->is64Bit()) {
15994     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15995     // the EAX register is loaded with the low-order 32 bits.
15996     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15997                               DAG.getConstant(32, DL, MVT::i8));
15998     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15999     Results.push_back(Chain);
16000     return;
16001   }
16002
16003   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
16004   SDValue Ops[] = { LO, HI };
16005   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
16006   Results.push_back(Pair);
16007   Results.push_back(Chain);
16008 }
16009
16010 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
16011                                      SelectionDAG &DAG) {
16012   SmallVector<SDValue, 2> Results;
16013   SDLoc DL(Op);
16014   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
16015                           Results);
16016   return DAG.getMergeValues(Results, DL);
16017 }
16018
16019 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
16020                                     SelectionDAG &DAG) {
16021   MachineFunction &MF = DAG.getMachineFunction();
16022   const Function *Fn = MF.getFunction();
16023   SDLoc dl(Op);
16024   SDValue Chain = Op.getOperand(0);
16025
16026   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16027          "using llvm.x86.seh.restoreframe requires a frame pointer");
16028
16029   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16030   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16031
16032   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16033   unsigned FrameReg =
16034       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16035   unsigned SPReg = RegInfo->getStackRegister();
16036   unsigned SlotSize = RegInfo->getSlotSize();
16037
16038   // Get incoming EBP.
16039   SDValue IncomingEBP =
16040       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16041
16042   // SP is saved in the first field of every registration node, so load
16043   // [EBP-RegNodeSize] into SP.
16044   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16045   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16046                                DAG.getConstant(-RegNodeSize, dl, VT));
16047   SDValue NewSP =
16048       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16049                   false, VT.getScalarSizeInBits() / 8);
16050   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16051
16052   if (!RegInfo->needsStackRealignment(MF)) {
16053     // Adjust EBP to point back to the original frame position.
16054     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16055     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16056   } else {
16057     assert(RegInfo->hasBasePointer(MF) &&
16058            "functions with Win32 EH must use frame or base pointer register");
16059
16060     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16061     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16062     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16063
16064     // Reload the spilled EBP value, now that the stack and base pointers are
16065     // set up.
16066     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16067     X86FI->setHasSEHFramePtrSave(true);
16068     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16069     X86FI->setSEHFramePtrSaveIndex(FI);
16070     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16071                                 MachinePointerInfo(), false, false, false,
16072                                 VT.getScalarSizeInBits() / 8);
16073     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16074   }
16075
16076   return Chain;
16077 }
16078
16079 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16080                                       SelectionDAG &DAG) {
16081   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16082
16083   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16084   if (!IntrData) {
16085     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16086       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16087     return SDValue();
16088   }
16089
16090   SDLoc dl(Op);
16091   switch(IntrData->Type) {
16092   default:
16093     llvm_unreachable("Unknown Intrinsic Type");
16094     break;
16095   case RDSEED:
16096   case RDRAND: {
16097     // Emit the node with the right value type.
16098     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16099     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16100
16101     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16102     // Otherwise return the value from Rand, which is always 0, casted to i32.
16103     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16104                       DAG.getConstant(1, dl, Op->getValueType(1)),
16105                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16106                       SDValue(Result.getNode(), 1) };
16107     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16108                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16109                                   Ops);
16110
16111     // Return { result, isValid, chain }.
16112     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16113                        SDValue(Result.getNode(), 2));
16114   }
16115   case GATHER: {
16116   //gather(v1, mask, index, base, scale);
16117     SDValue Chain = Op.getOperand(0);
16118     SDValue Src   = Op.getOperand(2);
16119     SDValue Base  = Op.getOperand(3);
16120     SDValue Index = Op.getOperand(4);
16121     SDValue Mask  = Op.getOperand(5);
16122     SDValue Scale = Op.getOperand(6);
16123     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16124                          Chain, Subtarget);
16125   }
16126   case SCATTER: {
16127   //scatter(base, mask, index, v1, scale);
16128     SDValue Chain = Op.getOperand(0);
16129     SDValue Base  = Op.getOperand(2);
16130     SDValue Mask  = Op.getOperand(3);
16131     SDValue Index = Op.getOperand(4);
16132     SDValue Src   = Op.getOperand(5);
16133     SDValue Scale = Op.getOperand(6);
16134     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16135                           Scale, Chain);
16136   }
16137   case PREFETCH: {
16138     SDValue Hint = Op.getOperand(6);
16139     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16140     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16141     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16142     SDValue Chain = Op.getOperand(0);
16143     SDValue Mask  = Op.getOperand(2);
16144     SDValue Index = Op.getOperand(3);
16145     SDValue Base  = Op.getOperand(4);
16146     SDValue Scale = Op.getOperand(5);
16147     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16148   }
16149   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16150   case RDTSC: {
16151     SmallVector<SDValue, 2> Results;
16152     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16153                             Results);
16154     return DAG.getMergeValues(Results, dl);
16155   }
16156   // Read Performance Monitoring Counters.
16157   case RDPMC: {
16158     SmallVector<SDValue, 2> Results;
16159     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16160     return DAG.getMergeValues(Results, dl);
16161   }
16162   // XTEST intrinsics.
16163   case XTEST: {
16164     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16165     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16166     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16167                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16168                                 InTrans);
16169     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16170     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16171                        Ret, SDValue(InTrans.getNode(), 1));
16172   }
16173   // ADC/ADCX/SBB
16174   case ADX: {
16175     SmallVector<SDValue, 2> Results;
16176     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16177     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16178     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16179                                 DAG.getConstant(-1, dl, MVT::i8));
16180     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16181                               Op.getOperand(4), GenCF.getValue(1));
16182     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16183                                  Op.getOperand(5), MachinePointerInfo(),
16184                                  false, false, 0);
16185     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16186                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16187                                 Res.getValue(1));
16188     Results.push_back(SetCC);
16189     Results.push_back(Store);
16190     return DAG.getMergeValues(Results, dl);
16191   }
16192   case COMPRESS_TO_MEM: {
16193     SDLoc dl(Op);
16194     SDValue Mask = Op.getOperand(4);
16195     SDValue DataToCompress = Op.getOperand(3);
16196     SDValue Addr = Op.getOperand(2);
16197     SDValue Chain = Op.getOperand(0);
16198
16199     EVT VT = DataToCompress.getValueType();
16200     if (isAllOnes(Mask)) // return just a store
16201       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16202                           MachinePointerInfo(), false, false,
16203                           VT.getScalarSizeInBits()/8);
16204
16205     SDValue Compressed =
16206       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16207                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16208     return DAG.getStore(Chain, dl, Compressed, Addr,
16209                         MachinePointerInfo(), false, false,
16210                         VT.getScalarSizeInBits()/8);
16211   }
16212   case EXPAND_FROM_MEM: {
16213     SDLoc dl(Op);
16214     SDValue Mask = Op.getOperand(4);
16215     SDValue PassThru = Op.getOperand(3);
16216     SDValue Addr = Op.getOperand(2);
16217     SDValue Chain = Op.getOperand(0);
16218     EVT VT = Op.getValueType();
16219
16220     if (isAllOnes(Mask)) // return just a load
16221       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16222                          false, VT.getScalarSizeInBits()/8);
16223
16224     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16225                                        false, false, false,
16226                                        VT.getScalarSizeInBits()/8);
16227
16228     SDValue Results[] = {
16229       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16230                            Mask, PassThru, Subtarget, DAG), Chain};
16231     return DAG.getMergeValues(Results, dl);
16232   }
16233   }
16234 }
16235
16236 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16237                                            SelectionDAG &DAG) const {
16238   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16239   MFI->setReturnAddressIsTaken(true);
16240
16241   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16242     return SDValue();
16243
16244   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16245   SDLoc dl(Op);
16246   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16247
16248   if (Depth > 0) {
16249     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16250     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16251     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16252     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16253                        DAG.getNode(ISD::ADD, dl, PtrVT,
16254                                    FrameAddr, Offset),
16255                        MachinePointerInfo(), false, false, false, 0);
16256   }
16257
16258   // Just load the return address.
16259   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16260   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16261                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16262 }
16263
16264 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16265   MachineFunction &MF = DAG.getMachineFunction();
16266   MachineFrameInfo *MFI = MF.getFrameInfo();
16267   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16268   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16269   EVT VT = Op.getValueType();
16270
16271   MFI->setFrameAddressIsTaken(true);
16272
16273   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16274     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16275     // is not possible to crawl up the stack without looking at the unwind codes
16276     // simultaneously.
16277     int FrameAddrIndex = FuncInfo->getFAIndex();
16278     if (!FrameAddrIndex) {
16279       // Set up a frame object for the return address.
16280       unsigned SlotSize = RegInfo->getSlotSize();
16281       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16282           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16283       FuncInfo->setFAIndex(FrameAddrIndex);
16284     }
16285     return DAG.getFrameIndex(FrameAddrIndex, VT);
16286   }
16287
16288   unsigned FrameReg =
16289       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16290   SDLoc dl(Op);  // FIXME probably not meaningful
16291   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16292   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16293           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16294          "Invalid Frame Register!");
16295   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16296   while (Depth--)
16297     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16298                             MachinePointerInfo(),
16299                             false, false, false, 0);
16300   return FrameAddr;
16301 }
16302
16303 // FIXME? Maybe this could be a TableGen attribute on some registers and
16304 // this table could be generated automatically from RegInfo.
16305 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16306                                               SelectionDAG &DAG) const {
16307   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16308   const MachineFunction &MF = DAG.getMachineFunction();
16309
16310   unsigned Reg = StringSwitch<unsigned>(RegName)
16311                        .Case("esp", X86::ESP)
16312                        .Case("rsp", X86::RSP)
16313                        .Case("ebp", X86::EBP)
16314                        .Case("rbp", X86::RBP)
16315                        .Default(0);
16316
16317   if (Reg == X86::EBP || Reg == X86::RBP) {
16318     if (!TFI.hasFP(MF))
16319       report_fatal_error("register " + StringRef(RegName) +
16320                          " is allocatable: function has no frame pointer");
16321 #ifndef NDEBUG
16322     else {
16323       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16324       unsigned FrameReg =
16325           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16326       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16327              "Invalid Frame Register!");
16328     }
16329 #endif
16330   }
16331
16332   if (Reg)
16333     return Reg;
16334
16335   report_fatal_error("Invalid register name global variable");
16336 }
16337
16338 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16339                                                      SelectionDAG &DAG) const {
16340   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16341   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16342 }
16343
16344 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16345   SDValue Chain     = Op.getOperand(0);
16346   SDValue Offset    = Op.getOperand(1);
16347   SDValue Handler   = Op.getOperand(2);
16348   SDLoc dl      (Op);
16349
16350   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16351   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16352   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16353   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16354           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16355          "Invalid Frame Register!");
16356   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16357   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16358
16359   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16360                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16361                                                        dl));
16362   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16363   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16364                        false, false, 0);
16365   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16366
16367   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16368                      DAG.getRegister(StoreAddrReg, PtrVT));
16369 }
16370
16371 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16372                                                SelectionDAG &DAG) const {
16373   SDLoc DL(Op);
16374   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16375                      DAG.getVTList(MVT::i32, MVT::Other),
16376                      Op.getOperand(0), Op.getOperand(1));
16377 }
16378
16379 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16380                                                 SelectionDAG &DAG) const {
16381   SDLoc DL(Op);
16382   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16383                      Op.getOperand(0), Op.getOperand(1));
16384 }
16385
16386 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16387   return Op.getOperand(0);
16388 }
16389
16390 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16391                                                 SelectionDAG &DAG) const {
16392   SDValue Root = Op.getOperand(0);
16393   SDValue Trmp = Op.getOperand(1); // trampoline
16394   SDValue FPtr = Op.getOperand(2); // nested function
16395   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16396   SDLoc dl (Op);
16397
16398   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16399   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16400
16401   if (Subtarget->is64Bit()) {
16402     SDValue OutChains[6];
16403
16404     // Large code-model.
16405     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16406     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16407
16408     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16409     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16410
16411     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16412
16413     // Load the pointer to the nested function into R11.
16414     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16415     SDValue Addr = Trmp;
16416     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16417                                 Addr, MachinePointerInfo(TrmpAddr),
16418                                 false, false, 0);
16419
16420     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16421                        DAG.getConstant(2, dl, MVT::i64));
16422     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16423                                 MachinePointerInfo(TrmpAddr, 2),
16424                                 false, false, 2);
16425
16426     // Load the 'nest' parameter value into R10.
16427     // R10 is specified in X86CallingConv.td
16428     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16429     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16430                        DAG.getConstant(10, dl, MVT::i64));
16431     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16432                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16433                                 false, false, 0);
16434
16435     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16436                        DAG.getConstant(12, dl, MVT::i64));
16437     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16438                                 MachinePointerInfo(TrmpAddr, 12),
16439                                 false, false, 2);
16440
16441     // Jump to the nested function.
16442     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16443     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16444                        DAG.getConstant(20, dl, MVT::i64));
16445     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16446                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16447                                 false, false, 0);
16448
16449     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16450     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16451                        DAG.getConstant(22, dl, MVT::i64));
16452     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16453                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16454                                 false, false, 0);
16455
16456     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16457   } else {
16458     const Function *Func =
16459       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16460     CallingConv::ID CC = Func->getCallingConv();
16461     unsigned NestReg;
16462
16463     switch (CC) {
16464     default:
16465       llvm_unreachable("Unsupported calling convention");
16466     case CallingConv::C:
16467     case CallingConv::X86_StdCall: {
16468       // Pass 'nest' parameter in ECX.
16469       // Must be kept in sync with X86CallingConv.td
16470       NestReg = X86::ECX;
16471
16472       // Check that ECX wasn't needed by an 'inreg' parameter.
16473       FunctionType *FTy = Func->getFunctionType();
16474       const AttributeSet &Attrs = Func->getAttributes();
16475
16476       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16477         unsigned InRegCount = 0;
16478         unsigned Idx = 1;
16479
16480         for (FunctionType::param_iterator I = FTy->param_begin(),
16481              E = FTy->param_end(); I != E; ++I, ++Idx)
16482           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16483             // FIXME: should only count parameters that are lowered to integers.
16484             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16485
16486         if (InRegCount > 2) {
16487           report_fatal_error("Nest register in use - reduce number of inreg"
16488                              " parameters!");
16489         }
16490       }
16491       break;
16492     }
16493     case CallingConv::X86_FastCall:
16494     case CallingConv::X86_ThisCall:
16495     case CallingConv::Fast:
16496       // Pass 'nest' parameter in EAX.
16497       // Must be kept in sync with X86CallingConv.td
16498       NestReg = X86::EAX;
16499       break;
16500     }
16501
16502     SDValue OutChains[4];
16503     SDValue Addr, Disp;
16504
16505     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16506                        DAG.getConstant(10, dl, MVT::i32));
16507     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16508
16509     // This is storing the opcode for MOV32ri.
16510     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16511     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16512     OutChains[0] = DAG.getStore(Root, dl,
16513                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16514                                 Trmp, MachinePointerInfo(TrmpAddr),
16515                                 false, false, 0);
16516
16517     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16518                        DAG.getConstant(1, dl, MVT::i32));
16519     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16520                                 MachinePointerInfo(TrmpAddr, 1),
16521                                 false, false, 1);
16522
16523     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16524     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16525                        DAG.getConstant(5, dl, MVT::i32));
16526     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16527                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16528                                 false, false, 1);
16529
16530     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16531                        DAG.getConstant(6, dl, MVT::i32));
16532     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16533                                 MachinePointerInfo(TrmpAddr, 6),
16534                                 false, false, 1);
16535
16536     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16537   }
16538 }
16539
16540 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16541                                             SelectionDAG &DAG) const {
16542   /*
16543    The rounding mode is in bits 11:10 of FPSR, and has the following
16544    settings:
16545      00 Round to nearest
16546      01 Round to -inf
16547      10 Round to +inf
16548      11 Round to 0
16549
16550   FLT_ROUNDS, on the other hand, expects the following:
16551     -1 Undefined
16552      0 Round to 0
16553      1 Round to nearest
16554      2 Round to +inf
16555      3 Round to -inf
16556
16557   To perform the conversion, we do:
16558     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16559   */
16560
16561   MachineFunction &MF = DAG.getMachineFunction();
16562   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16563   unsigned StackAlignment = TFI.getStackAlignment();
16564   MVT VT = Op.getSimpleValueType();
16565   SDLoc DL(Op);
16566
16567   // Save FP Control Word to stack slot
16568   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16569   SDValue StackSlot =
16570       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16571
16572   MachineMemOperand *MMO =
16573    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16574                            MachineMemOperand::MOStore, 2, 2);
16575
16576   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16577   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16578                                           DAG.getVTList(MVT::Other),
16579                                           Ops, MVT::i16, MMO);
16580
16581   // Load FP Control Word from stack slot
16582   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16583                             MachinePointerInfo(), false, false, false, 0);
16584
16585   // Transform as necessary
16586   SDValue CWD1 =
16587     DAG.getNode(ISD::SRL, DL, MVT::i16,
16588                 DAG.getNode(ISD::AND, DL, MVT::i16,
16589                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16590                 DAG.getConstant(11, DL, MVT::i8));
16591   SDValue CWD2 =
16592     DAG.getNode(ISD::SRL, DL, MVT::i16,
16593                 DAG.getNode(ISD::AND, DL, MVT::i16,
16594                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16595                 DAG.getConstant(9, DL, MVT::i8));
16596
16597   SDValue RetVal =
16598     DAG.getNode(ISD::AND, DL, MVT::i16,
16599                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16600                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16601                             DAG.getConstant(1, DL, MVT::i16)),
16602                 DAG.getConstant(3, DL, MVT::i16));
16603
16604   return DAG.getNode((VT.getSizeInBits() < 16 ?
16605                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16606 }
16607
16608 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16609   MVT VT = Op.getSimpleValueType();
16610   EVT OpVT = VT;
16611   unsigned NumBits = VT.getSizeInBits();
16612   SDLoc dl(Op);
16613
16614   Op = Op.getOperand(0);
16615   if (VT == MVT::i8) {
16616     // Zero extend to i32 since there is not an i8 bsr.
16617     OpVT = MVT::i32;
16618     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16619   }
16620
16621   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16622   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16623   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16624
16625   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16626   SDValue Ops[] = {
16627     Op,
16628     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16629     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16630     Op.getValue(1)
16631   };
16632   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16633
16634   // Finally xor with NumBits-1.
16635   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16636                    DAG.getConstant(NumBits - 1, dl, OpVT));
16637
16638   if (VT == MVT::i8)
16639     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16640   return Op;
16641 }
16642
16643 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16644   MVT VT = Op.getSimpleValueType();
16645   EVT OpVT = VT;
16646   unsigned NumBits = VT.getSizeInBits();
16647   SDLoc dl(Op);
16648
16649   Op = Op.getOperand(0);
16650   if (VT == MVT::i8) {
16651     // Zero extend to i32 since there is not an i8 bsr.
16652     OpVT = MVT::i32;
16653     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16654   }
16655
16656   // Issue a bsr (scan bits in reverse).
16657   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16658   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16659
16660   // And xor with NumBits-1.
16661   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16662                    DAG.getConstant(NumBits - 1, dl, OpVT));
16663
16664   if (VT == MVT::i8)
16665     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16666   return Op;
16667 }
16668
16669 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16670   MVT VT = Op.getSimpleValueType();
16671   unsigned NumBits = VT.getSizeInBits();
16672   SDLoc dl(Op);
16673   Op = Op.getOperand(0);
16674
16675   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16676   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16677   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16678
16679   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16680   SDValue Ops[] = {
16681     Op,
16682     DAG.getConstant(NumBits, dl, VT),
16683     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16684     Op.getValue(1)
16685   };
16686   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16687 }
16688
16689 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16690 // ones, and then concatenate the result back.
16691 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16692   MVT VT = Op.getSimpleValueType();
16693
16694   assert(VT.is256BitVector() && VT.isInteger() &&
16695          "Unsupported value type for operation");
16696
16697   unsigned NumElems = VT.getVectorNumElements();
16698   SDLoc dl(Op);
16699
16700   // Extract the LHS vectors
16701   SDValue LHS = Op.getOperand(0);
16702   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16703   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16704
16705   // Extract the RHS vectors
16706   SDValue RHS = Op.getOperand(1);
16707   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16708   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16709
16710   MVT EltVT = VT.getVectorElementType();
16711   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16712
16713   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16714                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16715                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16716 }
16717
16718 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16719   if (Op.getValueType() == MVT::i1)
16720     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16721                        Op.getOperand(0), Op.getOperand(1));
16722   assert(Op.getSimpleValueType().is256BitVector() &&
16723          Op.getSimpleValueType().isInteger() &&
16724          "Only handle AVX 256-bit vector integer operation");
16725   return Lower256IntArith(Op, DAG);
16726 }
16727
16728 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16729   if (Op.getValueType() == MVT::i1)
16730     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16731                        Op.getOperand(0), Op.getOperand(1));
16732   assert(Op.getSimpleValueType().is256BitVector() &&
16733          Op.getSimpleValueType().isInteger() &&
16734          "Only handle AVX 256-bit vector integer operation");
16735   return Lower256IntArith(Op, DAG);
16736 }
16737
16738 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16739                         SelectionDAG &DAG) {
16740   SDLoc dl(Op);
16741   MVT VT = Op.getSimpleValueType();
16742
16743   if (VT == MVT::i1)
16744     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16745
16746   // Decompose 256-bit ops into smaller 128-bit ops.
16747   if (VT.is256BitVector() && !Subtarget->hasInt256())
16748     return Lower256IntArith(Op, DAG);
16749
16750   SDValue A = Op.getOperand(0);
16751   SDValue B = Op.getOperand(1);
16752
16753   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16754   // pairs, multiply and truncate.
16755   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16756     if (Subtarget->hasInt256()) {
16757       if (VT == MVT::v32i8) {
16758         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16759         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16760         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16761         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16762         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16763         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16764         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16765         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16766                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16767                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16768       }
16769
16770       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16771       return DAG.getNode(
16772           ISD::TRUNCATE, dl, VT,
16773           DAG.getNode(ISD::MUL, dl, ExVT,
16774                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16775                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16776     }
16777
16778     assert(VT == MVT::v16i8 &&
16779            "Pre-AVX2 support only supports v16i8 multiplication");
16780     MVT ExVT = MVT::v8i16;
16781
16782     // Extract the lo parts and sign extend to i16
16783     SDValue ALo, BLo;
16784     if (Subtarget->hasSSE41()) {
16785       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16786       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16787     } else {
16788       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16789                               -1, 4, -1, 5, -1, 6, -1, 7};
16790       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16791       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16792       ALo = DAG.getBitcast(ExVT, ALo);
16793       BLo = DAG.getBitcast(ExVT, BLo);
16794       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16795       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16796     }
16797
16798     // Extract the hi parts and sign extend to i16
16799     SDValue AHi, BHi;
16800     if (Subtarget->hasSSE41()) {
16801       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16802                               -1, -1, -1, -1, -1, -1, -1, -1};
16803       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16804       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16805       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16806       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16807     } else {
16808       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16809                               -1, 12, -1, 13, -1, 14, -1, 15};
16810       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16811       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16812       AHi = DAG.getBitcast(ExVT, AHi);
16813       BHi = DAG.getBitcast(ExVT, BHi);
16814       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16815       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16816     }
16817
16818     // Multiply, mask the lower 8bits of the lo/hi results and pack
16819     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16820     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16821     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16822     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16823     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16824   }
16825
16826   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16827   if (VT == MVT::v4i32) {
16828     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16829            "Should not custom lower when pmuldq is available!");
16830
16831     // Extract the odd parts.
16832     static const int UnpackMask[] = { 1, -1, 3, -1 };
16833     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16834     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16835
16836     // Multiply the even parts.
16837     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16838     // Now multiply odd parts.
16839     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16840
16841     Evens = DAG.getBitcast(VT, Evens);
16842     Odds = DAG.getBitcast(VT, Odds);
16843
16844     // Merge the two vectors back together with a shuffle. This expands into 2
16845     // shuffles.
16846     static const int ShufMask[] = { 0, 4, 2, 6 };
16847     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16848   }
16849
16850   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16851          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16852
16853   //  Ahi = psrlqi(a, 32);
16854   //  Bhi = psrlqi(b, 32);
16855   //
16856   //  AloBlo = pmuludq(a, b);
16857   //  AloBhi = pmuludq(a, Bhi);
16858   //  AhiBlo = pmuludq(Ahi, b);
16859
16860   //  AloBhi = psllqi(AloBhi, 32);
16861   //  AhiBlo = psllqi(AhiBlo, 32);
16862   //  return AloBlo + AloBhi + AhiBlo;
16863
16864   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16865   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16866
16867   SDValue AhiBlo = Ahi;
16868   SDValue AloBhi = Bhi;
16869   // Bit cast to 32-bit vectors for MULUDQ
16870   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16871                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16872   A = DAG.getBitcast(MulVT, A);
16873   B = DAG.getBitcast(MulVT, B);
16874   Ahi = DAG.getBitcast(MulVT, Ahi);
16875   Bhi = DAG.getBitcast(MulVT, Bhi);
16876
16877   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16878   // After shifting right const values the result may be all-zero.
16879   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16880     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16881     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16882   }
16883   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16884     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16885     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16886   }
16887
16888   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16889   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16890 }
16891
16892 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16893   assert(Subtarget->isTargetWin64() && "Unexpected target");
16894   EVT VT = Op.getValueType();
16895   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16896          "Unexpected return type for lowering");
16897
16898   RTLIB::Libcall LC;
16899   bool isSigned;
16900   switch (Op->getOpcode()) {
16901   default: llvm_unreachable("Unexpected request for libcall!");
16902   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16903   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16904   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16905   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16906   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16907   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16908   }
16909
16910   SDLoc dl(Op);
16911   SDValue InChain = DAG.getEntryNode();
16912
16913   TargetLowering::ArgListTy Args;
16914   TargetLowering::ArgListEntry Entry;
16915   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16916     EVT ArgVT = Op->getOperand(i).getValueType();
16917     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16918            "Unexpected argument type for lowering");
16919     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16920     Entry.Node = StackPtr;
16921     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16922                            false, false, 16);
16923     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16924     Entry.Ty = PointerType::get(ArgTy,0);
16925     Entry.isSExt = false;
16926     Entry.isZExt = false;
16927     Args.push_back(Entry);
16928   }
16929
16930   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16931                                          getPointerTy(DAG.getDataLayout()));
16932
16933   TargetLowering::CallLoweringInfo CLI(DAG);
16934   CLI.setDebugLoc(dl).setChain(InChain)
16935     .setCallee(getLibcallCallingConv(LC),
16936                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16937                Callee, std::move(Args), 0)
16938     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16939
16940   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16941   return DAG.getBitcast(VT, CallInfo.first);
16942 }
16943
16944 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16945                              SelectionDAG &DAG) {
16946   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16947   EVT VT = Op0.getValueType();
16948   SDLoc dl(Op);
16949
16950   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16951          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16952
16953   // PMULxD operations multiply each even value (starting at 0) of LHS with
16954   // the related value of RHS and produce a widen result.
16955   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16956   // => <2 x i64> <ae|cg>
16957   //
16958   // In other word, to have all the results, we need to perform two PMULxD:
16959   // 1. one with the even values.
16960   // 2. one with the odd values.
16961   // To achieve #2, with need to place the odd values at an even position.
16962   //
16963   // Place the odd value at an even position (basically, shift all values 1
16964   // step to the left):
16965   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16966   // <a|b|c|d> => <b|undef|d|undef>
16967   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16968   // <e|f|g|h> => <f|undef|h|undef>
16969   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16970
16971   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16972   // ints.
16973   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16974   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16975   unsigned Opcode =
16976       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16977   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16978   // => <2 x i64> <ae|cg>
16979   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16980   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16981   // => <2 x i64> <bf|dh>
16982   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16983
16984   // Shuffle it back into the right order.
16985   SDValue Highs, Lows;
16986   if (VT == MVT::v8i32) {
16987     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16988     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16989     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16990     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16991   } else {
16992     const int HighMask[] = {1, 5, 3, 7};
16993     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16994     const int LowMask[] = {0, 4, 2, 6};
16995     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16996   }
16997
16998   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16999   // unsigned multiply.
17000   if (IsSigned && !Subtarget->hasSSE41()) {
17001     SDValue ShAmt = DAG.getConstant(
17002         31, dl,
17003         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
17004     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
17005                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
17006     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
17007                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
17008
17009     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
17010     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
17011   }
17012
17013   // The first result of MUL_LOHI is actually the low value, followed by the
17014   // high value.
17015   SDValue Ops[] = {Lows, Highs};
17016   return DAG.getMergeValues(Ops, dl);
17017 }
17018
17019 // Return true if the required (according to Opcode) shift-imm form is natively
17020 // supported by the Subtarget
17021 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
17022                                         unsigned Opcode) {
17023   if (VT.getScalarSizeInBits() < 16)
17024     return false;
17025
17026   if (VT.is512BitVector() &&
17027       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17028     return true;
17029
17030   bool LShift = VT.is128BitVector() ||
17031     (VT.is256BitVector() && Subtarget->hasInt256());
17032
17033   bool AShift = LShift && (Subtarget->hasVLX() ||
17034     (VT != MVT::v2i64 && VT != MVT::v4i64));
17035   return (Opcode == ISD::SRA) ? AShift : LShift;
17036 }
17037
17038 // The shift amount is a variable, but it is the same for all vector lanes.
17039 // These instructions are defined together with shift-immediate.
17040 static
17041 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17042                                       unsigned Opcode) {
17043   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17044 }
17045
17046 // Return true if the required (according to Opcode) variable-shift form is
17047 // natively supported by the Subtarget
17048 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17049                                     unsigned Opcode) {
17050
17051   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17052     return false;
17053
17054   // vXi16 supported only on AVX-512, BWI
17055   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17056     return false;
17057
17058   if (VT.is512BitVector() || Subtarget->hasVLX())
17059     return true;
17060
17061   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17062   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17063   return (Opcode == ISD::SRA) ? AShift : LShift;
17064 }
17065
17066 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17067                                          const X86Subtarget *Subtarget) {
17068   MVT VT = Op.getSimpleValueType();
17069   SDLoc dl(Op);
17070   SDValue R = Op.getOperand(0);
17071   SDValue Amt = Op.getOperand(1);
17072
17073   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17074     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17075
17076   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17077     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17078     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17079     SDValue Ex = DAG.getBitcast(ExVT, R);
17080
17081     if (ShiftAmt >= 32) {
17082       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17083       SDValue Upper =
17084           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17085       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17086                                                  ShiftAmt - 32, DAG);
17087       if (VT == MVT::v2i64)
17088         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17089       if (VT == MVT::v4i64)
17090         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17091                                   {9, 1, 11, 3, 13, 5, 15, 7});
17092     } else {
17093       // SRA upper i32, SHL whole i64 and select lower i32.
17094       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17095                                                  ShiftAmt, DAG);
17096       SDValue Lower =
17097           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17098       Lower = DAG.getBitcast(ExVT, Lower);
17099       if (VT == MVT::v2i64)
17100         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17101       if (VT == MVT::v4i64)
17102         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17103                                   {8, 1, 10, 3, 12, 5, 14, 7});
17104     }
17105     return DAG.getBitcast(VT, Ex);
17106   };
17107
17108   // Optimize shl/srl/sra with constant shift amount.
17109   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17110     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17111       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17112
17113       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17114         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17115
17116       // i64 SRA needs to be performed as partial shifts.
17117       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17118           Op.getOpcode() == ISD::SRA)
17119         return ArithmeticShiftRight64(ShiftAmt);
17120
17121       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17122         unsigned NumElts = VT.getVectorNumElements();
17123         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17124
17125         if (Op.getOpcode() == ISD::SHL) {
17126           // Simple i8 add case
17127           if (ShiftAmt == 1)
17128             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17129
17130           // Make a large shift.
17131           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17132                                                    R, ShiftAmt, DAG);
17133           SHL = DAG.getBitcast(VT, SHL);
17134           // Zero out the rightmost bits.
17135           SmallVector<SDValue, 32> V(
17136               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17137           return DAG.getNode(ISD::AND, dl, VT, SHL,
17138                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17139         }
17140         if (Op.getOpcode() == ISD::SRL) {
17141           // Make a large shift.
17142           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17143                                                    R, ShiftAmt, DAG);
17144           SRL = DAG.getBitcast(VT, SRL);
17145           // Zero out the leftmost bits.
17146           SmallVector<SDValue, 32> V(
17147               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17148           return DAG.getNode(ISD::AND, dl, VT, SRL,
17149                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17150         }
17151         if (Op.getOpcode() == ISD::SRA) {
17152           if (ShiftAmt == 7) {
17153             // R s>> 7  ===  R s< 0
17154             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17155             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17156           }
17157
17158           // R s>> a === ((R u>> a) ^ m) - m
17159           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17160           SmallVector<SDValue, 32> V(NumElts,
17161                                      DAG.getConstant(128 >> ShiftAmt, dl,
17162                                                      MVT::i8));
17163           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17164           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17165           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17166           return Res;
17167         }
17168         llvm_unreachable("Unknown shift opcode.");
17169       }
17170     }
17171   }
17172
17173   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17174   if (!Subtarget->is64Bit() &&
17175       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17176       Amt.getOpcode() == ISD::BITCAST &&
17177       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17178     Amt = Amt.getOperand(0);
17179     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17180                      VT.getVectorNumElements();
17181     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17182     uint64_t ShiftAmt = 0;
17183     for (unsigned i = 0; i != Ratio; ++i) {
17184       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17185       if (!C)
17186         return SDValue();
17187       // 6 == Log2(64)
17188       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17189     }
17190     // Check remaining shift amounts.
17191     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17192       uint64_t ShAmt = 0;
17193       for (unsigned j = 0; j != Ratio; ++j) {
17194         ConstantSDNode *C =
17195           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17196         if (!C)
17197           return SDValue();
17198         // 6 == Log2(64)
17199         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17200       }
17201       if (ShAmt != ShiftAmt)
17202         return SDValue();
17203     }
17204
17205     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17206       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17207
17208     if (Op.getOpcode() == ISD::SRA)
17209       return ArithmeticShiftRight64(ShiftAmt);
17210   }
17211
17212   return SDValue();
17213 }
17214
17215 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17216                                         const X86Subtarget* Subtarget) {
17217   MVT VT = Op.getSimpleValueType();
17218   SDLoc dl(Op);
17219   SDValue R = Op.getOperand(0);
17220   SDValue Amt = Op.getOperand(1);
17221
17222   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17223     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17224
17225   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17226     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17227
17228   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17229     SDValue BaseShAmt;
17230     EVT EltVT = VT.getVectorElementType();
17231
17232     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17233       // Check if this build_vector node is doing a splat.
17234       // If so, then set BaseShAmt equal to the splat value.
17235       BaseShAmt = BV->getSplatValue();
17236       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17237         BaseShAmt = SDValue();
17238     } else {
17239       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17240         Amt = Amt.getOperand(0);
17241
17242       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17243       if (SVN && SVN->isSplat()) {
17244         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17245         SDValue InVec = Amt.getOperand(0);
17246         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17247           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17248                  "Unexpected shuffle index found!");
17249           BaseShAmt = InVec.getOperand(SplatIdx);
17250         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17251            if (ConstantSDNode *C =
17252                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17253              if (C->getZExtValue() == SplatIdx)
17254                BaseShAmt = InVec.getOperand(1);
17255            }
17256         }
17257
17258         if (!BaseShAmt)
17259           // Avoid introducing an extract element from a shuffle.
17260           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17261                                   DAG.getIntPtrConstant(SplatIdx, dl));
17262       }
17263     }
17264
17265     if (BaseShAmt.getNode()) {
17266       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17267       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17268         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17269       else if (EltVT.bitsLT(MVT::i32))
17270         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17271
17272       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17273     }
17274   }
17275
17276   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17277   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17278       Amt.getOpcode() == ISD::BITCAST &&
17279       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17280     Amt = Amt.getOperand(0);
17281     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17282                      VT.getVectorNumElements();
17283     std::vector<SDValue> Vals(Ratio);
17284     for (unsigned i = 0; i != Ratio; ++i)
17285       Vals[i] = Amt.getOperand(i);
17286     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17287       for (unsigned j = 0; j != Ratio; ++j)
17288         if (Vals[j] != Amt.getOperand(i + j))
17289           return SDValue();
17290     }
17291
17292     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17293       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17294   }
17295   return SDValue();
17296 }
17297
17298 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17299                           SelectionDAG &DAG) {
17300   MVT VT = Op.getSimpleValueType();
17301   SDLoc dl(Op);
17302   SDValue R = Op.getOperand(0);
17303   SDValue Amt = Op.getOperand(1);
17304
17305   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17306   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17307
17308   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17309     return V;
17310
17311   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17312       return V;
17313
17314   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17315     return Op;
17316
17317   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17318   // shifts per-lane and then shuffle the partial results back together.
17319   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17320     // Splat the shift amounts so the scalar shifts above will catch it.
17321     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17322     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17323     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17324     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17325     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17326   }
17327
17328   // If possible, lower this packed shift into a vector multiply instead of
17329   // expanding it into a sequence of scalar shifts.
17330   // Do this only if the vector shift count is a constant build_vector.
17331   if (Op.getOpcode() == ISD::SHL &&
17332       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17333        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17334       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17335     SmallVector<SDValue, 8> Elts;
17336     EVT SVT = VT.getScalarType();
17337     unsigned SVTBits = SVT.getSizeInBits();
17338     const APInt &One = APInt(SVTBits, 1);
17339     unsigned NumElems = VT.getVectorNumElements();
17340
17341     for (unsigned i=0; i !=NumElems; ++i) {
17342       SDValue Op = Amt->getOperand(i);
17343       if (Op->getOpcode() == ISD::UNDEF) {
17344         Elts.push_back(Op);
17345         continue;
17346       }
17347
17348       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17349       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17350       uint64_t ShAmt = C.getZExtValue();
17351       if (ShAmt >= SVTBits) {
17352         Elts.push_back(DAG.getUNDEF(SVT));
17353         continue;
17354       }
17355       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17356     }
17357     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17358     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17359   }
17360
17361   // Lower SHL with variable shift amount.
17362   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17363     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17364
17365     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17366                      DAG.getConstant(0x3f800000U, dl, VT));
17367     Op = DAG.getBitcast(MVT::v4f32, Op);
17368     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17369     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17370   }
17371
17372   // If possible, lower this shift as a sequence of two shifts by
17373   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17374   // Example:
17375   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17376   //
17377   // Could be rewritten as:
17378   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17379   //
17380   // The advantage is that the two shifts from the example would be
17381   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17382   // the vector shift into four scalar shifts plus four pairs of vector
17383   // insert/extract.
17384   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17385       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17386     unsigned TargetOpcode = X86ISD::MOVSS;
17387     bool CanBeSimplified;
17388     // The splat value for the first packed shift (the 'X' from the example).
17389     SDValue Amt1 = Amt->getOperand(0);
17390     // The splat value for the second packed shift (the 'Y' from the example).
17391     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17392                                         Amt->getOperand(2);
17393
17394     // See if it is possible to replace this node with a sequence of
17395     // two shifts followed by a MOVSS/MOVSD
17396     if (VT == MVT::v4i32) {
17397       // Check if it is legal to use a MOVSS.
17398       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17399                         Amt2 == Amt->getOperand(3);
17400       if (!CanBeSimplified) {
17401         // Otherwise, check if we can still simplify this node using a MOVSD.
17402         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17403                           Amt->getOperand(2) == Amt->getOperand(3);
17404         TargetOpcode = X86ISD::MOVSD;
17405         Amt2 = Amt->getOperand(2);
17406       }
17407     } else {
17408       // Do similar checks for the case where the machine value type
17409       // is MVT::v8i16.
17410       CanBeSimplified = Amt1 == Amt->getOperand(1);
17411       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17412         CanBeSimplified = Amt2 == Amt->getOperand(i);
17413
17414       if (!CanBeSimplified) {
17415         TargetOpcode = X86ISD::MOVSD;
17416         CanBeSimplified = true;
17417         Amt2 = Amt->getOperand(4);
17418         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17419           CanBeSimplified = Amt1 == Amt->getOperand(i);
17420         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17421           CanBeSimplified = Amt2 == Amt->getOperand(j);
17422       }
17423     }
17424
17425     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17426         isa<ConstantSDNode>(Amt2)) {
17427       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17428       EVT CastVT = MVT::v4i32;
17429       SDValue Splat1 =
17430         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17431       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17432       SDValue Splat2 =
17433         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17434       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17435       if (TargetOpcode == X86ISD::MOVSD)
17436         CastVT = MVT::v2i64;
17437       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17438       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17439       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17440                                             BitCast1, DAG);
17441       return DAG.getBitcast(VT, Result);
17442     }
17443   }
17444
17445   // v4i32 Non Uniform Shifts.
17446   // If the shift amount is constant we can shift each lane using the SSE2
17447   // immediate shifts, else we need to zero-extend each lane to the lower i64
17448   // and shift using the SSE2 variable shifts.
17449   // The separate results can then be blended together.
17450   if (VT == MVT::v4i32) {
17451     unsigned Opc = Op.getOpcode();
17452     SDValue Amt0, Amt1, Amt2, Amt3;
17453     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17454       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17455       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17456       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17457       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17458     } else {
17459       // ISD::SHL is handled above but we include it here for completeness.
17460       switch (Opc) {
17461       default:
17462         llvm_unreachable("Unknown target vector shift node");
17463       case ISD::SHL:
17464         Opc = X86ISD::VSHL;
17465         break;
17466       case ISD::SRL:
17467         Opc = X86ISD::VSRL;
17468         break;
17469       case ISD::SRA:
17470         Opc = X86ISD::VSRA;
17471         break;
17472       }
17473       // The SSE2 shifts use the lower i64 as the same shift amount for
17474       // all lanes and the upper i64 is ignored. These shuffle masks
17475       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17476       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17477       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17478       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17479       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17480       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17481     }
17482
17483     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17484     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17485     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17486     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17487     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17488     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17489     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17490   }
17491
17492   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17493     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17494     unsigned ShiftOpcode = Op->getOpcode();
17495
17496     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17497       // On SSE41 targets we make use of the fact that VSELECT lowers
17498       // to PBLENDVB which selects bytes based just on the sign bit.
17499       if (Subtarget->hasSSE41()) {
17500         V0 = DAG.getBitcast(VT, V0);
17501         V1 = DAG.getBitcast(VT, V1);
17502         Sel = DAG.getBitcast(VT, Sel);
17503         return DAG.getBitcast(SelVT,
17504                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17505       }
17506       // On pre-SSE41 targets we test for the sign bit by comparing to
17507       // zero - a negative value will set all bits of the lanes to true
17508       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17509       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17510       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17511       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17512     };
17513
17514     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17515     // We can safely do this using i16 shifts as we're only interested in
17516     // the 3 lower bits of each byte.
17517     Amt = DAG.getBitcast(ExtVT, Amt);
17518     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17519     Amt = DAG.getBitcast(VT, Amt);
17520
17521     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17522       // r = VSELECT(r, shift(r, 4), a);
17523       SDValue M =
17524           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17525       R = SignBitSelect(VT, Amt, M, R);
17526
17527       // a += a
17528       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17529
17530       // r = VSELECT(r, shift(r, 2), a);
17531       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17532       R = SignBitSelect(VT, Amt, M, R);
17533
17534       // a += a
17535       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17536
17537       // return VSELECT(r, shift(r, 1), a);
17538       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17539       R = SignBitSelect(VT, Amt, M, R);
17540       return R;
17541     }
17542
17543     if (Op->getOpcode() == ISD::SRA) {
17544       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17545       // so we can correctly sign extend. We don't care what happens to the
17546       // lower byte.
17547       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17548       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17549       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17550       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17551       ALo = DAG.getBitcast(ExtVT, ALo);
17552       AHi = DAG.getBitcast(ExtVT, AHi);
17553       RLo = DAG.getBitcast(ExtVT, RLo);
17554       RHi = DAG.getBitcast(ExtVT, RHi);
17555
17556       // r = VSELECT(r, shift(r, 4), a);
17557       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17558                                 DAG.getConstant(4, dl, ExtVT));
17559       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17560                                 DAG.getConstant(4, dl, ExtVT));
17561       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17562       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17563
17564       // a += a
17565       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17566       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17567
17568       // r = VSELECT(r, shift(r, 2), a);
17569       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17570                         DAG.getConstant(2, dl, ExtVT));
17571       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17572                         DAG.getConstant(2, dl, ExtVT));
17573       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17574       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17575
17576       // a += a
17577       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17578       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17579
17580       // r = VSELECT(r, shift(r, 1), a);
17581       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17582                         DAG.getConstant(1, dl, ExtVT));
17583       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17584                         DAG.getConstant(1, dl, ExtVT));
17585       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17586       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17587
17588       // Logical shift the result back to the lower byte, leaving a zero upper
17589       // byte
17590       // meaning that we can safely pack with PACKUSWB.
17591       RLo =
17592           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17593       RHi =
17594           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17595       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17596     }
17597   }
17598
17599   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17600   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17601   // solution better.
17602   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17603     MVT ExtVT = MVT::v8i32;
17604     unsigned ExtOpc =
17605         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17606     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17607     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17608     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17609                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17610   }
17611
17612   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17613     MVT ExtVT = MVT::v8i32;
17614     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17615     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17616     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17617     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17618     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17619     ALo = DAG.getBitcast(ExtVT, ALo);
17620     AHi = DAG.getBitcast(ExtVT, AHi);
17621     RLo = DAG.getBitcast(ExtVT, RLo);
17622     RHi = DAG.getBitcast(ExtVT, RHi);
17623     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17624     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17625     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17626     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17627     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17628   }
17629
17630   if (VT == MVT::v8i16) {
17631     unsigned ShiftOpcode = Op->getOpcode();
17632
17633     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17634       // On SSE41 targets we make use of the fact that VSELECT lowers
17635       // to PBLENDVB which selects bytes based just on the sign bit.
17636       if (Subtarget->hasSSE41()) {
17637         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17638         V0 = DAG.getBitcast(ExtVT, V0);
17639         V1 = DAG.getBitcast(ExtVT, V1);
17640         Sel = DAG.getBitcast(ExtVT, Sel);
17641         return DAG.getBitcast(
17642             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17643       }
17644       // On pre-SSE41 targets we splat the sign bit - a negative value will
17645       // set all bits of the lanes to true and VSELECT uses that in
17646       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17647       SDValue C =
17648           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17649       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17650     };
17651
17652     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17653     if (Subtarget->hasSSE41()) {
17654       // On SSE41 targets we need to replicate the shift mask in both
17655       // bytes for PBLENDVB.
17656       Amt = DAG.getNode(
17657           ISD::OR, dl, VT,
17658           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17659           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17660     } else {
17661       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17662     }
17663
17664     // r = VSELECT(r, shift(r, 8), a);
17665     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17666     R = SignBitSelect(Amt, M, R);
17667
17668     // a += a
17669     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17670
17671     // r = VSELECT(r, shift(r, 4), a);
17672     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17673     R = SignBitSelect(Amt, M, R);
17674
17675     // a += a
17676     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17677
17678     // r = VSELECT(r, shift(r, 2), a);
17679     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17680     R = SignBitSelect(Amt, M, R);
17681
17682     // a += a
17683     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17684
17685     // return VSELECT(r, shift(r, 1), a);
17686     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17687     R = SignBitSelect(Amt, M, R);
17688     return R;
17689   }
17690
17691   // Decompose 256-bit shifts into smaller 128-bit shifts.
17692   if (VT.is256BitVector()) {
17693     unsigned NumElems = VT.getVectorNumElements();
17694     MVT EltVT = VT.getVectorElementType();
17695     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17696
17697     // Extract the two vectors
17698     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17699     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17700
17701     // Recreate the shift amount vectors
17702     SDValue Amt1, Amt2;
17703     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17704       // Constant shift amount
17705       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17706       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17707       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17708
17709       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17710       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17711     } else {
17712       // Variable shift amount
17713       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17714       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17715     }
17716
17717     // Issue new vector shifts for the smaller types
17718     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17719     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17720
17721     // Concatenate the result back
17722     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17723   }
17724
17725   return SDValue();
17726 }
17727
17728 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17729   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17730   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17731   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17732   // has only one use.
17733   SDNode *N = Op.getNode();
17734   SDValue LHS = N->getOperand(0);
17735   SDValue RHS = N->getOperand(1);
17736   unsigned BaseOp = 0;
17737   unsigned Cond = 0;
17738   SDLoc DL(Op);
17739   switch (Op.getOpcode()) {
17740   default: llvm_unreachable("Unknown ovf instruction!");
17741   case ISD::SADDO:
17742     // A subtract of one will be selected as a INC. Note that INC doesn't
17743     // set CF, so we can't do this for UADDO.
17744     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17745       if (C->isOne()) {
17746         BaseOp = X86ISD::INC;
17747         Cond = X86::COND_O;
17748         break;
17749       }
17750     BaseOp = X86ISD::ADD;
17751     Cond = X86::COND_O;
17752     break;
17753   case ISD::UADDO:
17754     BaseOp = X86ISD::ADD;
17755     Cond = X86::COND_B;
17756     break;
17757   case ISD::SSUBO:
17758     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17759     // set CF, so we can't do this for USUBO.
17760     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17761       if (C->isOne()) {
17762         BaseOp = X86ISD::DEC;
17763         Cond = X86::COND_O;
17764         break;
17765       }
17766     BaseOp = X86ISD::SUB;
17767     Cond = X86::COND_O;
17768     break;
17769   case ISD::USUBO:
17770     BaseOp = X86ISD::SUB;
17771     Cond = X86::COND_B;
17772     break;
17773   case ISD::SMULO:
17774     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17775     Cond = X86::COND_O;
17776     break;
17777   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17778     if (N->getValueType(0) == MVT::i8) {
17779       BaseOp = X86ISD::UMUL8;
17780       Cond = X86::COND_O;
17781       break;
17782     }
17783     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17784                                  MVT::i32);
17785     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17786
17787     SDValue SetCC =
17788       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17789                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17790                   SDValue(Sum.getNode(), 2));
17791
17792     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17793   }
17794   }
17795
17796   // Also sets EFLAGS.
17797   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17798   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17799
17800   SDValue SetCC =
17801     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17802                 DAG.getConstant(Cond, DL, MVT::i32),
17803                 SDValue(Sum.getNode(), 1));
17804
17805   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17806 }
17807
17808 /// Returns true if the operand type is exactly twice the native width, and
17809 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17810 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17811 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17812 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17813   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17814
17815   if (OpWidth == 64)
17816     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17817   else if (OpWidth == 128)
17818     return Subtarget->hasCmpxchg16b();
17819   else
17820     return false;
17821 }
17822
17823 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17824   return needsCmpXchgNb(SI->getValueOperand()->getType());
17825 }
17826
17827 // Note: this turns large loads into lock cmpxchg8b/16b.
17828 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17829 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17830   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17831   return needsCmpXchgNb(PTy->getElementType());
17832 }
17833
17834 TargetLoweringBase::AtomicRMWExpansionKind
17835 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17836   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17837   const Type *MemType = AI->getType();
17838
17839   // If the operand is too big, we must see if cmpxchg8/16b is available
17840   // and default to library calls otherwise.
17841   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17842     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17843                                    : AtomicRMWExpansionKind::None;
17844   }
17845
17846   AtomicRMWInst::BinOp Op = AI->getOperation();
17847   switch (Op) {
17848   default:
17849     llvm_unreachable("Unknown atomic operation");
17850   case AtomicRMWInst::Xchg:
17851   case AtomicRMWInst::Add:
17852   case AtomicRMWInst::Sub:
17853     // It's better to use xadd, xsub or xchg for these in all cases.
17854     return AtomicRMWExpansionKind::None;
17855   case AtomicRMWInst::Or:
17856   case AtomicRMWInst::And:
17857   case AtomicRMWInst::Xor:
17858     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17859     // prefix to a normal instruction for these operations.
17860     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17861                             : AtomicRMWExpansionKind::None;
17862   case AtomicRMWInst::Nand:
17863   case AtomicRMWInst::Max:
17864   case AtomicRMWInst::Min:
17865   case AtomicRMWInst::UMax:
17866   case AtomicRMWInst::UMin:
17867     // These always require a non-trivial set of data operations on x86. We must
17868     // use a cmpxchg loop.
17869     return AtomicRMWExpansionKind::CmpXChg;
17870   }
17871 }
17872
17873 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17874   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17875   // no-sse2). There isn't any reason to disable it if the target processor
17876   // supports it.
17877   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17878 }
17879
17880 LoadInst *
17881 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17882   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17883   const Type *MemType = AI->getType();
17884   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17885   // there is no benefit in turning such RMWs into loads, and it is actually
17886   // harmful as it introduces a mfence.
17887   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17888     return nullptr;
17889
17890   auto Builder = IRBuilder<>(AI);
17891   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17892   auto SynchScope = AI->getSynchScope();
17893   // We must restrict the ordering to avoid generating loads with Release or
17894   // ReleaseAcquire orderings.
17895   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17896   auto Ptr = AI->getPointerOperand();
17897
17898   // Before the load we need a fence. Here is an example lifted from
17899   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17900   // is required:
17901   // Thread 0:
17902   //   x.store(1, relaxed);
17903   //   r1 = y.fetch_add(0, release);
17904   // Thread 1:
17905   //   y.fetch_add(42, acquire);
17906   //   r2 = x.load(relaxed);
17907   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17908   // lowered to just a load without a fence. A mfence flushes the store buffer,
17909   // making the optimization clearly correct.
17910   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17911   // otherwise, we might be able to be more agressive on relaxed idempotent
17912   // rmw. In practice, they do not look useful, so we don't try to be
17913   // especially clever.
17914   if (SynchScope == SingleThread)
17915     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17916     // the IR level, so we must wrap it in an intrinsic.
17917     return nullptr;
17918
17919   if (!hasMFENCE(*Subtarget))
17920     // FIXME: it might make sense to use a locked operation here but on a
17921     // different cache-line to prevent cache-line bouncing. In practice it
17922     // is probably a small win, and x86 processors without mfence are rare
17923     // enough that we do not bother.
17924     return nullptr;
17925
17926   Function *MFence =
17927       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17928   Builder.CreateCall(MFence, {});
17929
17930   // Finally we can emit the atomic load.
17931   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17932           AI->getType()->getPrimitiveSizeInBits());
17933   Loaded->setAtomic(Order, SynchScope);
17934   AI->replaceAllUsesWith(Loaded);
17935   AI->eraseFromParent();
17936   return Loaded;
17937 }
17938
17939 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17940                                  SelectionDAG &DAG) {
17941   SDLoc dl(Op);
17942   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17943     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17944   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17945     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17946
17947   // The only fence that needs an instruction is a sequentially-consistent
17948   // cross-thread fence.
17949   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17950     if (hasMFENCE(*Subtarget))
17951       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17952
17953     SDValue Chain = Op.getOperand(0);
17954     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17955     SDValue Ops[] = {
17956       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17957       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17958       DAG.getRegister(0, MVT::i32),            // Index
17959       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17960       DAG.getRegister(0, MVT::i32),            // Segment.
17961       Zero,
17962       Chain
17963     };
17964     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17965     return SDValue(Res, 0);
17966   }
17967
17968   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17969   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17970 }
17971
17972 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17973                              SelectionDAG &DAG) {
17974   MVT T = Op.getSimpleValueType();
17975   SDLoc DL(Op);
17976   unsigned Reg = 0;
17977   unsigned size = 0;
17978   switch(T.SimpleTy) {
17979   default: llvm_unreachable("Invalid value type!");
17980   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17981   case MVT::i16: Reg = X86::AX;  size = 2; break;
17982   case MVT::i32: Reg = X86::EAX; size = 4; break;
17983   case MVT::i64:
17984     assert(Subtarget->is64Bit() && "Node not type legal!");
17985     Reg = X86::RAX; size = 8;
17986     break;
17987   }
17988   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17989                                   Op.getOperand(2), SDValue());
17990   SDValue Ops[] = { cpIn.getValue(0),
17991                     Op.getOperand(1),
17992                     Op.getOperand(3),
17993                     DAG.getTargetConstant(size, DL, MVT::i8),
17994                     cpIn.getValue(1) };
17995   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17996   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17997   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17998                                            Ops, T, MMO);
17999
18000   SDValue cpOut =
18001     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
18002   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
18003                                       MVT::i32, cpOut.getValue(2));
18004   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
18005                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
18006                                 EFLAGS);
18007
18008   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
18009   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
18010   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
18011   return SDValue();
18012 }
18013
18014 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
18015                             SelectionDAG &DAG) {
18016   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
18017   MVT DstVT = Op.getSimpleValueType();
18018
18019   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
18020     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18021     if (DstVT != MVT::f64)
18022       // This conversion needs to be expanded.
18023       return SDValue();
18024
18025     SDValue InVec = Op->getOperand(0);
18026     SDLoc dl(Op);
18027     unsigned NumElts = SrcVT.getVectorNumElements();
18028     EVT SVT = SrcVT.getVectorElementType();
18029
18030     // Widen the vector in input in the case of MVT::v2i32.
18031     // Example: from MVT::v2i32 to MVT::v4i32.
18032     SmallVector<SDValue, 16> Elts;
18033     for (unsigned i = 0, e = NumElts; i != e; ++i)
18034       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18035                                  DAG.getIntPtrConstant(i, dl)));
18036
18037     // Explicitly mark the extra elements as Undef.
18038     Elts.append(NumElts, DAG.getUNDEF(SVT));
18039
18040     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18041     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18042     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18043     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18044                        DAG.getIntPtrConstant(0, dl));
18045   }
18046
18047   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18048          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18049   assert((DstVT == MVT::i64 ||
18050           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18051          "Unexpected custom BITCAST");
18052   // i64 <=> MMX conversions are Legal.
18053   if (SrcVT==MVT::i64 && DstVT.isVector())
18054     return Op;
18055   if (DstVT==MVT::i64 && SrcVT.isVector())
18056     return Op;
18057   // MMX <=> MMX conversions are Legal.
18058   if (SrcVT.isVector() && DstVT.isVector())
18059     return Op;
18060   // All other conversions need to be expanded.
18061   return SDValue();
18062 }
18063
18064 /// Compute the horizontal sum of bytes in V for the elements of VT.
18065 ///
18066 /// Requires V to be a byte vector and VT to be an integer vector type with
18067 /// wider elements than V's type. The width of the elements of VT determines
18068 /// how many bytes of V are summed horizontally to produce each element of the
18069 /// result.
18070 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18071                                       const X86Subtarget *Subtarget,
18072                                       SelectionDAG &DAG) {
18073   SDLoc DL(V);
18074   MVT ByteVecVT = V.getSimpleValueType();
18075   MVT EltVT = VT.getVectorElementType();
18076   int NumElts = VT.getVectorNumElements();
18077   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18078          "Expected value to have byte element type.");
18079   assert(EltVT != MVT::i8 &&
18080          "Horizontal byte sum only makes sense for wider elements!");
18081   unsigned VecSize = VT.getSizeInBits();
18082   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18083
18084   // PSADBW instruction horizontally add all bytes and leave the result in i64
18085   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18086   if (EltVT == MVT::i64) {
18087     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18088     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18089     return DAG.getBitcast(VT, V);
18090   }
18091
18092   if (EltVT == MVT::i32) {
18093     // We unpack the low half and high half into i32s interleaved with zeros so
18094     // that we can use PSADBW to horizontally sum them. The most useful part of
18095     // this is that it lines up the results of two PSADBW instructions to be
18096     // two v2i64 vectors which concatenated are the 4 population counts. We can
18097     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18098     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18099     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18100     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18101
18102     // Do the horizontal sums into two v2i64s.
18103     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18104     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18105                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18106     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18107                        DAG.getBitcast(ByteVecVT, High), Zeros);
18108
18109     // Merge them together.
18110     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18111     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18112                     DAG.getBitcast(ShortVecVT, Low),
18113                     DAG.getBitcast(ShortVecVT, High));
18114
18115     return DAG.getBitcast(VT, V);
18116   }
18117
18118   // The only element type left is i16.
18119   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18120
18121   // To obtain pop count for each i16 element starting from the pop count for
18122   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18123   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18124   // directly supported.
18125   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18126   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18127   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18128   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18129                   DAG.getBitcast(ByteVecVT, V));
18130   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18131 }
18132
18133 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18134                                         const X86Subtarget *Subtarget,
18135                                         SelectionDAG &DAG) {
18136   MVT VT = Op.getSimpleValueType();
18137   MVT EltVT = VT.getVectorElementType();
18138   unsigned VecSize = VT.getSizeInBits();
18139
18140   // Implement a lookup table in register by using an algorithm based on:
18141   // http://wm.ite.pl/articles/sse-popcount.html
18142   //
18143   // The general idea is that every lower byte nibble in the input vector is an
18144   // index into a in-register pre-computed pop count table. We then split up the
18145   // input vector in two new ones: (1) a vector with only the shifted-right
18146   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18147   // masked out higher ones) for each byte. PSHUB is used separately with both
18148   // to index the in-register table. Next, both are added and the result is a
18149   // i8 vector where each element contains the pop count for input byte.
18150   //
18151   // To obtain the pop count for elements != i8, we follow up with the same
18152   // approach and use additional tricks as described below.
18153   //
18154   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18155                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18156                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18157                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18158
18159   int NumByteElts = VecSize / 8;
18160   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18161   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18162   SmallVector<SDValue, 16> LUTVec;
18163   for (int i = 0; i < NumByteElts; ++i)
18164     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18165   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18166   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18167                                   DAG.getConstant(0x0F, DL, MVT::i8));
18168   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18169
18170   // High nibbles
18171   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18172   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18173   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18174
18175   // Low nibbles
18176   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18177
18178   // The input vector is used as the shuffle mask that index elements into the
18179   // LUT. After counting low and high nibbles, add the vector to obtain the
18180   // final pop count per i8 element.
18181   SDValue HighPopCnt =
18182       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18183   SDValue LowPopCnt =
18184       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18185   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18186
18187   if (EltVT == MVT::i8)
18188     return PopCnt;
18189
18190   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18191 }
18192
18193 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18194                                        const X86Subtarget *Subtarget,
18195                                        SelectionDAG &DAG) {
18196   MVT VT = Op.getSimpleValueType();
18197   assert(VT.is128BitVector() &&
18198          "Only 128-bit vector bitmath lowering supported.");
18199
18200   int VecSize = VT.getSizeInBits();
18201   MVT EltVT = VT.getVectorElementType();
18202   int Len = EltVT.getSizeInBits();
18203
18204   // This is the vectorized version of the "best" algorithm from
18205   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18206   // with a minor tweak to use a series of adds + shifts instead of vector
18207   // multiplications. Implemented for all integer vector types. We only use
18208   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18209   // much faster, even faster than using native popcnt instructions.
18210
18211   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18212     MVT VT = V.getSimpleValueType();
18213     SmallVector<SDValue, 32> Shifters(
18214         VT.getVectorNumElements(),
18215         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18216     return DAG.getNode(OpCode, DL, VT, V,
18217                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18218   };
18219   auto GetMask = [&](SDValue V, APInt Mask) {
18220     MVT VT = V.getSimpleValueType();
18221     SmallVector<SDValue, 32> Masks(
18222         VT.getVectorNumElements(),
18223         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18224     return DAG.getNode(ISD::AND, DL, VT, V,
18225                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18226   };
18227
18228   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18229   // x86, so set the SRL type to have elements at least i16 wide. This is
18230   // correct because all of our SRLs are followed immediately by a mask anyways
18231   // that handles any bits that sneak into the high bits of the byte elements.
18232   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18233
18234   SDValue V = Op;
18235
18236   // v = v - ((v >> 1) & 0x55555555...)
18237   SDValue Srl =
18238       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18239   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18240   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18241
18242   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18243   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18244   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18245   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18246   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18247
18248   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18249   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18250   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18251   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18252
18253   // At this point, V contains the byte-wise population count, and we are
18254   // merely doing a horizontal sum if necessary to get the wider element
18255   // counts.
18256   if (EltVT == MVT::i8)
18257     return V;
18258
18259   return LowerHorizontalByteSum(
18260       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18261       DAG);
18262 }
18263
18264 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18265                                 SelectionDAG &DAG) {
18266   MVT VT = Op.getSimpleValueType();
18267   // FIXME: Need to add AVX-512 support here!
18268   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18269          "Unknown CTPOP type to handle");
18270   SDLoc DL(Op.getNode());
18271   SDValue Op0 = Op.getOperand(0);
18272
18273   if (!Subtarget->hasSSSE3()) {
18274     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18275     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18276     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18277   }
18278
18279   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18280     unsigned NumElems = VT.getVectorNumElements();
18281
18282     // Extract each 128-bit vector, compute pop count and concat the result.
18283     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18284     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18285
18286     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18287                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18288                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18289   }
18290
18291   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18292 }
18293
18294 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18295                           SelectionDAG &DAG) {
18296   assert(Op.getValueType().isVector() &&
18297          "We only do custom lowering for vector population count.");
18298   return LowerVectorCTPOP(Op, Subtarget, DAG);
18299 }
18300
18301 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18302   SDNode *Node = Op.getNode();
18303   SDLoc dl(Node);
18304   EVT T = Node->getValueType(0);
18305   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18306                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18307   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18308                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18309                        Node->getOperand(0),
18310                        Node->getOperand(1), negOp,
18311                        cast<AtomicSDNode>(Node)->getMemOperand(),
18312                        cast<AtomicSDNode>(Node)->getOrdering(),
18313                        cast<AtomicSDNode>(Node)->getSynchScope());
18314 }
18315
18316 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18317   SDNode *Node = Op.getNode();
18318   SDLoc dl(Node);
18319   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18320
18321   // Convert seq_cst store -> xchg
18322   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18323   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18324   //        (The only way to get a 16-byte store is cmpxchg16b)
18325   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18326   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18327       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18328     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18329                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18330                                  Node->getOperand(0),
18331                                  Node->getOperand(1), Node->getOperand(2),
18332                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18333                                  cast<AtomicSDNode>(Node)->getOrdering(),
18334                                  cast<AtomicSDNode>(Node)->getSynchScope());
18335     return Swap.getValue(1);
18336   }
18337   // Other atomic stores have a simple pattern.
18338   return Op;
18339 }
18340
18341 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18342   EVT VT = Op.getNode()->getSimpleValueType(0);
18343
18344   // Let legalize expand this if it isn't a legal type yet.
18345   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18346     return SDValue();
18347
18348   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18349
18350   unsigned Opc;
18351   bool ExtraOp = false;
18352   switch (Op.getOpcode()) {
18353   default: llvm_unreachable("Invalid code");
18354   case ISD::ADDC: Opc = X86ISD::ADD; break;
18355   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18356   case ISD::SUBC: Opc = X86ISD::SUB; break;
18357   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18358   }
18359
18360   if (!ExtraOp)
18361     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18362                        Op.getOperand(1));
18363   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18364                      Op.getOperand(1), Op.getOperand(2));
18365 }
18366
18367 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18368                             SelectionDAG &DAG) {
18369   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18370
18371   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18372   // which returns the values as { float, float } (in XMM0) or
18373   // { double, double } (which is returned in XMM0, XMM1).
18374   SDLoc dl(Op);
18375   SDValue Arg = Op.getOperand(0);
18376   EVT ArgVT = Arg.getValueType();
18377   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18378
18379   TargetLowering::ArgListTy Args;
18380   TargetLowering::ArgListEntry Entry;
18381
18382   Entry.Node = Arg;
18383   Entry.Ty = ArgTy;
18384   Entry.isSExt = false;
18385   Entry.isZExt = false;
18386   Args.push_back(Entry);
18387
18388   bool isF64 = ArgVT == MVT::f64;
18389   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18390   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18391   // the results are returned via SRet in memory.
18392   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18393   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18394   SDValue Callee =
18395       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18396
18397   Type *RetTy = isF64
18398     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18399     : (Type*)VectorType::get(ArgTy, 4);
18400
18401   TargetLowering::CallLoweringInfo CLI(DAG);
18402   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18403     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18404
18405   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18406
18407   if (isF64)
18408     // Returned in xmm0 and xmm1.
18409     return CallResult.first;
18410
18411   // Returned in bits 0:31 and 32:64 xmm0.
18412   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18413                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18414   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18415                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18416   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18417   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18418 }
18419
18420 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18421                              SelectionDAG &DAG) {
18422   assert(Subtarget->hasAVX512() &&
18423          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18424
18425   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18426   EVT VT = N->getValue().getValueType();
18427   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18428   SDLoc dl(Op);
18429
18430   // X86 scatter kills mask register, so its type should be added to
18431   // the list of return values
18432   if (N->getNumValues() == 1) {
18433     SDValue Index = N->getIndex();
18434     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18435         !Index.getValueType().is512BitVector())
18436       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18437
18438     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18439     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18440                       N->getOperand(3), Index };
18441
18442     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18443     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18444     return SDValue(NewScatter.getNode(), 0);
18445   }
18446   return Op;
18447 }
18448
18449 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18450                             SelectionDAG &DAG) {
18451   assert(Subtarget->hasAVX512() &&
18452          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18453
18454   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18455   EVT VT = Op.getValueType();
18456   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18457   SDLoc dl(Op);
18458
18459   SDValue Index = N->getIndex();
18460   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18461       !Index.getValueType().is512BitVector()) {
18462     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18463     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18464                       N->getOperand(3), Index };
18465     DAG.UpdateNodeOperands(N, Ops);
18466   }
18467   return Op;
18468 }
18469
18470 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18471                                                     SelectionDAG &DAG) const {
18472   // TODO: Eventually, the lowering of these nodes should be informed by or
18473   // deferred to the GC strategy for the function in which they appear. For
18474   // now, however, they must be lowered to something. Since they are logically
18475   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18476   // require special handling for these nodes), lower them as literal NOOPs for
18477   // the time being.
18478   SmallVector<SDValue, 2> Ops;
18479
18480   Ops.push_back(Op.getOperand(0));
18481   if (Op->getGluedNode())
18482     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18483
18484   SDLoc OpDL(Op);
18485   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18486   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18487
18488   return NOOP;
18489 }
18490
18491 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18492                                                   SelectionDAG &DAG) const {
18493   // TODO: Eventually, the lowering of these nodes should be informed by or
18494   // deferred to the GC strategy for the function in which they appear. For
18495   // now, however, they must be lowered to something. Since they are logically
18496   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18497   // require special handling for these nodes), lower them as literal NOOPs for
18498   // the time being.
18499   SmallVector<SDValue, 2> Ops;
18500
18501   Ops.push_back(Op.getOperand(0));
18502   if (Op->getGluedNode())
18503     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18504
18505   SDLoc OpDL(Op);
18506   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18507   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18508
18509   return NOOP;
18510 }
18511
18512 /// LowerOperation - Provide custom lowering hooks for some operations.
18513 ///
18514 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18515   switch (Op.getOpcode()) {
18516   default: llvm_unreachable("Should not custom lower this!");
18517   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18518   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18519     return LowerCMP_SWAP(Op, Subtarget, DAG);
18520   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18521   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18522   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18523   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18524   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18525   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18526   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18527   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18528   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18529   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18530   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18531   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18532   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18533   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18534   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18535   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18536   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18537   case ISD::SHL_PARTS:
18538   case ISD::SRA_PARTS:
18539   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18540   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18541   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18542   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18543   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18544   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18545   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18546   case ISD::SIGN_EXTEND_VECTOR_INREG:
18547     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18548   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18549   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18550   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18551   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18552   case ISD::FABS:
18553   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18554   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18555   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18556   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18557   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18558   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18559   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18560   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18561   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18562   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18563   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18564   case ISD::INTRINSIC_VOID:
18565   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18566   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18567   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18568   case ISD::FRAME_TO_ARGS_OFFSET:
18569                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18570   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18571   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18572   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18573   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18574   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18575   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18576   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18577   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18578   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18579   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18580   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18581   case ISD::UMUL_LOHI:
18582   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18583   case ISD::SRA:
18584   case ISD::SRL:
18585   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18586   case ISD::SADDO:
18587   case ISD::UADDO:
18588   case ISD::SSUBO:
18589   case ISD::USUBO:
18590   case ISD::SMULO:
18591   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18592   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18593   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18594   case ISD::ADDC:
18595   case ISD::ADDE:
18596   case ISD::SUBC:
18597   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18598   case ISD::ADD:                return LowerADD(Op, DAG);
18599   case ISD::SUB:                return LowerSUB(Op, DAG);
18600   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18601   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18602   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18603   case ISD::GC_TRANSITION_START:
18604                                 return LowerGC_TRANSITION_START(Op, DAG);
18605   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18606   }
18607 }
18608
18609 /// ReplaceNodeResults - Replace a node with an illegal result type
18610 /// with a new node built out of custom code.
18611 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18612                                            SmallVectorImpl<SDValue>&Results,
18613                                            SelectionDAG &DAG) const {
18614   SDLoc dl(N);
18615   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18616   switch (N->getOpcode()) {
18617   default:
18618     llvm_unreachable("Do not know how to custom type legalize this operation!");
18619   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18620   case X86ISD::FMINC:
18621   case X86ISD::FMIN:
18622   case X86ISD::FMAXC:
18623   case X86ISD::FMAX: {
18624     EVT VT = N->getValueType(0);
18625     if (VT != MVT::v2f32)
18626       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18627     SDValue UNDEF = DAG.getUNDEF(VT);
18628     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18629                               N->getOperand(0), UNDEF);
18630     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18631                               N->getOperand(1), UNDEF);
18632     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18633     return;
18634   }
18635   case ISD::SIGN_EXTEND_INREG:
18636   case ISD::ADDC:
18637   case ISD::ADDE:
18638   case ISD::SUBC:
18639   case ISD::SUBE:
18640     // We don't want to expand or promote these.
18641     return;
18642   case ISD::SDIV:
18643   case ISD::UDIV:
18644   case ISD::SREM:
18645   case ISD::UREM:
18646   case ISD::SDIVREM:
18647   case ISD::UDIVREM: {
18648     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18649     Results.push_back(V);
18650     return;
18651   }
18652   case ISD::FP_TO_SINT:
18653     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18654     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18655     if (N->getOperand(0).getValueType() == MVT::f16)
18656       break;
18657     // fallthrough
18658   case ISD::FP_TO_UINT: {
18659     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18660
18661     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18662       return;
18663
18664     std::pair<SDValue,SDValue> Vals =
18665         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18666     SDValue FIST = Vals.first, StackSlot = Vals.second;
18667     if (FIST.getNode()) {
18668       EVT VT = N->getValueType(0);
18669       // Return a load from the stack slot.
18670       if (StackSlot.getNode())
18671         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18672                                       MachinePointerInfo(),
18673                                       false, false, false, 0));
18674       else
18675         Results.push_back(FIST);
18676     }
18677     return;
18678   }
18679   case ISD::UINT_TO_FP: {
18680     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18681     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18682         N->getValueType(0) != MVT::v2f32)
18683       return;
18684     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18685                                  N->getOperand(0));
18686     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18687                                      MVT::f64);
18688     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18689     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18690                              DAG.getBitcast(MVT::v2i64, VBias));
18691     Or = DAG.getBitcast(MVT::v2f64, Or);
18692     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18693     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18694     return;
18695   }
18696   case ISD::FP_ROUND: {
18697     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18698         return;
18699     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18700     Results.push_back(V);
18701     return;
18702   }
18703   case ISD::FP_EXTEND: {
18704     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18705     // No other ValueType for FP_EXTEND should reach this point.
18706     assert(N->getValueType(0) == MVT::v2f32 &&
18707            "Do not know how to legalize this Node");
18708     return;
18709   }
18710   case ISD::INTRINSIC_W_CHAIN: {
18711     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18712     switch (IntNo) {
18713     default : llvm_unreachable("Do not know how to custom type "
18714                                "legalize this intrinsic operation!");
18715     case Intrinsic::x86_rdtsc:
18716       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18717                                      Results);
18718     case Intrinsic::x86_rdtscp:
18719       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18720                                      Results);
18721     case Intrinsic::x86_rdpmc:
18722       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18723     }
18724   }
18725   case ISD::READCYCLECOUNTER: {
18726     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18727                                    Results);
18728   }
18729   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18730     EVT T = N->getValueType(0);
18731     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18732     bool Regs64bit = T == MVT::i128;
18733     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18734     SDValue cpInL, cpInH;
18735     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18736                         DAG.getConstant(0, dl, HalfT));
18737     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18738                         DAG.getConstant(1, dl, HalfT));
18739     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18740                              Regs64bit ? X86::RAX : X86::EAX,
18741                              cpInL, SDValue());
18742     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18743                              Regs64bit ? X86::RDX : X86::EDX,
18744                              cpInH, cpInL.getValue(1));
18745     SDValue swapInL, swapInH;
18746     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18747                           DAG.getConstant(0, dl, HalfT));
18748     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18749                           DAG.getConstant(1, dl, HalfT));
18750     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18751                                Regs64bit ? X86::RBX : X86::EBX,
18752                                swapInL, cpInH.getValue(1));
18753     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18754                                Regs64bit ? X86::RCX : X86::ECX,
18755                                swapInH, swapInL.getValue(1));
18756     SDValue Ops[] = { swapInH.getValue(0),
18757                       N->getOperand(1),
18758                       swapInH.getValue(1) };
18759     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18760     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18761     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18762                                   X86ISD::LCMPXCHG8_DAG;
18763     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18764     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18765                                         Regs64bit ? X86::RAX : X86::EAX,
18766                                         HalfT, Result.getValue(1));
18767     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18768                                         Regs64bit ? X86::RDX : X86::EDX,
18769                                         HalfT, cpOutL.getValue(2));
18770     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18771
18772     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18773                                         MVT::i32, cpOutH.getValue(2));
18774     SDValue Success =
18775         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18776                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18777     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18778
18779     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18780     Results.push_back(Success);
18781     Results.push_back(EFLAGS.getValue(1));
18782     return;
18783   }
18784   case ISD::ATOMIC_SWAP:
18785   case ISD::ATOMIC_LOAD_ADD:
18786   case ISD::ATOMIC_LOAD_SUB:
18787   case ISD::ATOMIC_LOAD_AND:
18788   case ISD::ATOMIC_LOAD_OR:
18789   case ISD::ATOMIC_LOAD_XOR:
18790   case ISD::ATOMIC_LOAD_NAND:
18791   case ISD::ATOMIC_LOAD_MIN:
18792   case ISD::ATOMIC_LOAD_MAX:
18793   case ISD::ATOMIC_LOAD_UMIN:
18794   case ISD::ATOMIC_LOAD_UMAX:
18795   case ISD::ATOMIC_LOAD: {
18796     // Delegate to generic TypeLegalization. Situations we can really handle
18797     // should have already been dealt with by AtomicExpandPass.cpp.
18798     break;
18799   }
18800   case ISD::BITCAST: {
18801     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18802     EVT DstVT = N->getValueType(0);
18803     EVT SrcVT = N->getOperand(0)->getValueType(0);
18804
18805     if (SrcVT != MVT::f64 ||
18806         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18807       return;
18808
18809     unsigned NumElts = DstVT.getVectorNumElements();
18810     EVT SVT = DstVT.getVectorElementType();
18811     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18812     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18813                                    MVT::v2f64, N->getOperand(0));
18814     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18815
18816     if (ExperimentalVectorWideningLegalization) {
18817       // If we are legalizing vectors by widening, we already have the desired
18818       // legal vector type, just return it.
18819       Results.push_back(ToVecInt);
18820       return;
18821     }
18822
18823     SmallVector<SDValue, 8> Elts;
18824     for (unsigned i = 0, e = NumElts; i != e; ++i)
18825       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18826                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18827
18828     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18829   }
18830   }
18831 }
18832
18833 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18834   switch ((X86ISD::NodeType)Opcode) {
18835   case X86ISD::FIRST_NUMBER:       break;
18836   case X86ISD::BSF:                return "X86ISD::BSF";
18837   case X86ISD::BSR:                return "X86ISD::BSR";
18838   case X86ISD::SHLD:               return "X86ISD::SHLD";
18839   case X86ISD::SHRD:               return "X86ISD::SHRD";
18840   case X86ISD::FAND:               return "X86ISD::FAND";
18841   case X86ISD::FANDN:              return "X86ISD::FANDN";
18842   case X86ISD::FOR:                return "X86ISD::FOR";
18843   case X86ISD::FXOR:               return "X86ISD::FXOR";
18844   case X86ISD::FILD:               return "X86ISD::FILD";
18845   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18846   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18847   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18848   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18849   case X86ISD::FLD:                return "X86ISD::FLD";
18850   case X86ISD::FST:                return "X86ISD::FST";
18851   case X86ISD::CALL:               return "X86ISD::CALL";
18852   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18853   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18854   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18855   case X86ISD::BT:                 return "X86ISD::BT";
18856   case X86ISD::CMP:                return "X86ISD::CMP";
18857   case X86ISD::COMI:               return "X86ISD::COMI";
18858   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18859   case X86ISD::CMPM:               return "X86ISD::CMPM";
18860   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18861   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18862   case X86ISD::SETCC:              return "X86ISD::SETCC";
18863   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18864   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18865   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18866   case X86ISD::CMOV:               return "X86ISD::CMOV";
18867   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18868   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18869   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18870   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18871   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18872   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18873   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18874   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18875   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18876   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18877   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18878   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18879   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18880   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18881   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18882   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18883   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18884   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18885   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18886   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18887   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18888   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18889   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18890   case X86ISD::HADD:               return "X86ISD::HADD";
18891   case X86ISD::HSUB:               return "X86ISD::HSUB";
18892   case X86ISD::FHADD:              return "X86ISD::FHADD";
18893   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18894   case X86ISD::ABS:                return "X86ISD::ABS";
18895   case X86ISD::FMAX:               return "X86ISD::FMAX";
18896   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18897   case X86ISD::FMIN:               return "X86ISD::FMIN";
18898   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18899   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18900   case X86ISD::FMINC:              return "X86ISD::FMINC";
18901   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18902   case X86ISD::FRCP:               return "X86ISD::FRCP";
18903   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18904   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18905   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18906   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18907   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18908   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18909   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18910   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18911   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18912   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18913   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18914   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18915   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18916   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18917   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18918   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18919   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18920   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18921   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18922   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18923   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18924   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18925   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18926   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18927   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
18928   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18929   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18930   case X86ISD::VSHL:               return "X86ISD::VSHL";
18931   case X86ISD::VSRL:               return "X86ISD::VSRL";
18932   case X86ISD::VSRA:               return "X86ISD::VSRA";
18933   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18934   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18935   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18936   case X86ISD::CMPP:               return "X86ISD::CMPP";
18937   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18938   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18939   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18940   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18941   case X86ISD::ADD:                return "X86ISD::ADD";
18942   case X86ISD::SUB:                return "X86ISD::SUB";
18943   case X86ISD::ADC:                return "X86ISD::ADC";
18944   case X86ISD::SBB:                return "X86ISD::SBB";
18945   case X86ISD::SMUL:               return "X86ISD::SMUL";
18946   case X86ISD::UMUL:               return "X86ISD::UMUL";
18947   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18948   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18949   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18950   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18951   case X86ISD::INC:                return "X86ISD::INC";
18952   case X86ISD::DEC:                return "X86ISD::DEC";
18953   case X86ISD::OR:                 return "X86ISD::OR";
18954   case X86ISD::XOR:                return "X86ISD::XOR";
18955   case X86ISD::AND:                return "X86ISD::AND";
18956   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18957   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18958   case X86ISD::PTEST:              return "X86ISD::PTEST";
18959   case X86ISD::TESTP:              return "X86ISD::TESTP";
18960   case X86ISD::TESTM:              return "X86ISD::TESTM";
18961   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18962   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18963   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18964   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18965   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18966   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18967   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18968   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18969   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18970   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18971   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18972   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18973   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18974   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18975   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18976   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18977   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18978   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18979   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18980   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18981   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18982   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18983   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18984   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18985   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18986   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18987   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18988   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18989   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18990   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18991   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18992   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18993   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18994   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18995   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18996   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18997   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18998   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18999   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
19000   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
19001   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
19002   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
19003   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
19004   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
19005   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
19006   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
19007   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
19008   case X86ISD::SAHF:               return "X86ISD::SAHF";
19009   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
19010   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
19011   case X86ISD::FMADD:              return "X86ISD::FMADD";
19012   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
19013   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
19014   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
19015   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
19016   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
19017   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
19018   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
19019   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
19020   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
19021   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
19022   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
19023   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
19024   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19025   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19026   case X86ISD::XTEST:              return "X86ISD::XTEST";
19027   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19028   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19029   case X86ISD::SELECT:             return "X86ISD::SELECT";
19030   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19031   case X86ISD::RCP28:              return "X86ISD::RCP28";
19032   case X86ISD::EXP2:               return "X86ISD::EXP2";
19033   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19034   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19035   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19036   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19037   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19038   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19039   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19040   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19041   case X86ISD::ADDS:               return "X86ISD::ADDS";
19042   case X86ISD::SUBS:               return "X86ISD::SUBS";
19043   case X86ISD::AVG:                return "X86ISD::AVG";
19044   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19045   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19046   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19047   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19048   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19049   }
19050   return nullptr;
19051 }
19052
19053 // isLegalAddressingMode - Return true if the addressing mode represented
19054 // by AM is legal for this target, for a load/store of the specified type.
19055 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19056                                               const AddrMode &AM, Type *Ty,
19057                                               unsigned AS) const {
19058   // X86 supports extremely general addressing modes.
19059   CodeModel::Model M = getTargetMachine().getCodeModel();
19060   Reloc::Model R = getTargetMachine().getRelocationModel();
19061
19062   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19063   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19064     return false;
19065
19066   if (AM.BaseGV) {
19067     unsigned GVFlags =
19068       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19069
19070     // If a reference to this global requires an extra load, we can't fold it.
19071     if (isGlobalStubReference(GVFlags))
19072       return false;
19073
19074     // If BaseGV requires a register for the PIC base, we cannot also have a
19075     // BaseReg specified.
19076     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19077       return false;
19078
19079     // If lower 4G is not available, then we must use rip-relative addressing.
19080     if ((M != CodeModel::Small || R != Reloc::Static) &&
19081         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19082       return false;
19083   }
19084
19085   switch (AM.Scale) {
19086   case 0:
19087   case 1:
19088   case 2:
19089   case 4:
19090   case 8:
19091     // These scales always work.
19092     break;
19093   case 3:
19094   case 5:
19095   case 9:
19096     // These scales are formed with basereg+scalereg.  Only accept if there is
19097     // no basereg yet.
19098     if (AM.HasBaseReg)
19099       return false;
19100     break;
19101   default:  // Other stuff never works.
19102     return false;
19103   }
19104
19105   return true;
19106 }
19107
19108 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19109   unsigned Bits = Ty->getScalarSizeInBits();
19110
19111   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19112   // particularly cheaper than those without.
19113   if (Bits == 8)
19114     return false;
19115
19116   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19117   // variable shifts just as cheap as scalar ones.
19118   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19119     return false;
19120
19121   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19122   // fully general vector.
19123   return true;
19124 }
19125
19126 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19127   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19128     return false;
19129   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19130   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19131   return NumBits1 > NumBits2;
19132 }
19133
19134 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19135   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19136     return false;
19137
19138   if (!isTypeLegal(EVT::getEVT(Ty1)))
19139     return false;
19140
19141   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19142
19143   // Assuming the caller doesn't have a zeroext or signext return parameter,
19144   // truncation all the way down to i1 is valid.
19145   return true;
19146 }
19147
19148 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19149   return isInt<32>(Imm);
19150 }
19151
19152 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19153   // Can also use sub to handle negated immediates.
19154   return isInt<32>(Imm);
19155 }
19156
19157 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19158   if (!VT1.isInteger() || !VT2.isInteger())
19159     return false;
19160   unsigned NumBits1 = VT1.getSizeInBits();
19161   unsigned NumBits2 = VT2.getSizeInBits();
19162   return NumBits1 > NumBits2;
19163 }
19164
19165 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19166   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19167   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19168 }
19169
19170 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19171   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19172   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19173 }
19174
19175 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19176   EVT VT1 = Val.getValueType();
19177   if (isZExtFree(VT1, VT2))
19178     return true;
19179
19180   if (Val.getOpcode() != ISD::LOAD)
19181     return false;
19182
19183   if (!VT1.isSimple() || !VT1.isInteger() ||
19184       !VT2.isSimple() || !VT2.isInteger())
19185     return false;
19186
19187   switch (VT1.getSimpleVT().SimpleTy) {
19188   default: break;
19189   case MVT::i8:
19190   case MVT::i16:
19191   case MVT::i32:
19192     // X86 has 8, 16, and 32-bit zero-extending loads.
19193     return true;
19194   }
19195
19196   return false;
19197 }
19198
19199 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19200
19201 bool
19202 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19203   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19204     return false;
19205
19206   VT = VT.getScalarType();
19207
19208   if (!VT.isSimple())
19209     return false;
19210
19211   switch (VT.getSimpleVT().SimpleTy) {
19212   case MVT::f32:
19213   case MVT::f64:
19214     return true;
19215   default:
19216     break;
19217   }
19218
19219   return false;
19220 }
19221
19222 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19223   // i16 instructions are longer (0x66 prefix) and potentially slower.
19224   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19225 }
19226
19227 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19228 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19229 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19230 /// are assumed to be legal.
19231 bool
19232 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19233                                       EVT VT) const {
19234   if (!VT.isSimple())
19235     return false;
19236
19237   // Not for i1 vectors
19238   if (VT.getScalarType() == MVT::i1)
19239     return false;
19240
19241   // Very little shuffling can be done for 64-bit vectors right now.
19242   if (VT.getSizeInBits() == 64)
19243     return false;
19244
19245   // We only care that the types being shuffled are legal. The lowering can
19246   // handle any possible shuffle mask that results.
19247   return isTypeLegal(VT.getSimpleVT());
19248 }
19249
19250 bool
19251 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19252                                           EVT VT) const {
19253   // Just delegate to the generic legality, clear masks aren't special.
19254   return isShuffleMaskLegal(Mask, VT);
19255 }
19256
19257 //===----------------------------------------------------------------------===//
19258 //                           X86 Scheduler Hooks
19259 //===----------------------------------------------------------------------===//
19260
19261 /// Utility function to emit xbegin specifying the start of an RTM region.
19262 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19263                                      const TargetInstrInfo *TII) {
19264   DebugLoc DL = MI->getDebugLoc();
19265
19266   const BasicBlock *BB = MBB->getBasicBlock();
19267   MachineFunction::iterator I = MBB;
19268   ++I;
19269
19270   // For the v = xbegin(), we generate
19271   //
19272   // thisMBB:
19273   //  xbegin sinkMBB
19274   //
19275   // mainMBB:
19276   //  eax = -1
19277   //
19278   // sinkMBB:
19279   //  v = eax
19280
19281   MachineBasicBlock *thisMBB = MBB;
19282   MachineFunction *MF = MBB->getParent();
19283   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19284   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19285   MF->insert(I, mainMBB);
19286   MF->insert(I, sinkMBB);
19287
19288   // Transfer the remainder of BB and its successor edges to sinkMBB.
19289   sinkMBB->splice(sinkMBB->begin(), MBB,
19290                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19291   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19292
19293   // thisMBB:
19294   //  xbegin sinkMBB
19295   //  # fallthrough to mainMBB
19296   //  # abortion to sinkMBB
19297   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19298   thisMBB->addSuccessor(mainMBB);
19299   thisMBB->addSuccessor(sinkMBB);
19300
19301   // mainMBB:
19302   //  EAX = -1
19303   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19304   mainMBB->addSuccessor(sinkMBB);
19305
19306   // sinkMBB:
19307   // EAX is live into the sinkMBB
19308   sinkMBB->addLiveIn(X86::EAX);
19309   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19310           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19311     .addReg(X86::EAX);
19312
19313   MI->eraseFromParent();
19314   return sinkMBB;
19315 }
19316
19317 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19318 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19319 // in the .td file.
19320 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19321                                        const TargetInstrInfo *TII) {
19322   unsigned Opc;
19323   switch (MI->getOpcode()) {
19324   default: llvm_unreachable("illegal opcode!");
19325   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19326   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19327   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19328   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19329   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19330   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19331   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19332   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19333   }
19334
19335   DebugLoc dl = MI->getDebugLoc();
19336   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19337
19338   unsigned NumArgs = MI->getNumOperands();
19339   for (unsigned i = 1; i < NumArgs; ++i) {
19340     MachineOperand &Op = MI->getOperand(i);
19341     if (!(Op.isReg() && Op.isImplicit()))
19342       MIB.addOperand(Op);
19343   }
19344   if (MI->hasOneMemOperand())
19345     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19346
19347   BuildMI(*BB, MI, dl,
19348     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19349     .addReg(X86::XMM0);
19350
19351   MI->eraseFromParent();
19352   return BB;
19353 }
19354
19355 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19356 // defs in an instruction pattern
19357 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19358                                        const TargetInstrInfo *TII) {
19359   unsigned Opc;
19360   switch (MI->getOpcode()) {
19361   default: llvm_unreachable("illegal opcode!");
19362   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19363   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19364   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19365   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19366   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19367   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19368   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19369   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19370   }
19371
19372   DebugLoc dl = MI->getDebugLoc();
19373   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19374
19375   unsigned NumArgs = MI->getNumOperands(); // remove the results
19376   for (unsigned i = 1; i < NumArgs; ++i) {
19377     MachineOperand &Op = MI->getOperand(i);
19378     if (!(Op.isReg() && Op.isImplicit()))
19379       MIB.addOperand(Op);
19380   }
19381   if (MI->hasOneMemOperand())
19382     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19383
19384   BuildMI(*BB, MI, dl,
19385     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19386     .addReg(X86::ECX);
19387
19388   MI->eraseFromParent();
19389   return BB;
19390 }
19391
19392 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19393                                       const X86Subtarget *Subtarget) {
19394   DebugLoc dl = MI->getDebugLoc();
19395   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19396   // Address into RAX/EAX, other two args into ECX, EDX.
19397   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19398   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19399   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19400   for (int i = 0; i < X86::AddrNumOperands; ++i)
19401     MIB.addOperand(MI->getOperand(i));
19402
19403   unsigned ValOps = X86::AddrNumOperands;
19404   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19405     .addReg(MI->getOperand(ValOps).getReg());
19406   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19407     .addReg(MI->getOperand(ValOps+1).getReg());
19408
19409   // The instruction doesn't actually take any operands though.
19410   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19411
19412   MI->eraseFromParent(); // The pseudo is gone now.
19413   return BB;
19414 }
19415
19416 MachineBasicBlock *
19417 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19418                                                  MachineBasicBlock *MBB) const {
19419   // Emit va_arg instruction on X86-64.
19420
19421   // Operands to this pseudo-instruction:
19422   // 0  ) Output        : destination address (reg)
19423   // 1-5) Input         : va_list address (addr, i64mem)
19424   // 6  ) ArgSize       : Size (in bytes) of vararg type
19425   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19426   // 8  ) Align         : Alignment of type
19427   // 9  ) EFLAGS (implicit-def)
19428
19429   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19430   static_assert(X86::AddrNumOperands == 5,
19431                 "VAARG_64 assumes 5 address operands");
19432
19433   unsigned DestReg = MI->getOperand(0).getReg();
19434   MachineOperand &Base = MI->getOperand(1);
19435   MachineOperand &Scale = MI->getOperand(2);
19436   MachineOperand &Index = MI->getOperand(3);
19437   MachineOperand &Disp = MI->getOperand(4);
19438   MachineOperand &Segment = MI->getOperand(5);
19439   unsigned ArgSize = MI->getOperand(6).getImm();
19440   unsigned ArgMode = MI->getOperand(7).getImm();
19441   unsigned Align = MI->getOperand(8).getImm();
19442
19443   // Memory Reference
19444   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19445   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19446   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19447
19448   // Machine Information
19449   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19450   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19451   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19452   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19453   DebugLoc DL = MI->getDebugLoc();
19454
19455   // struct va_list {
19456   //   i32   gp_offset
19457   //   i32   fp_offset
19458   //   i64   overflow_area (address)
19459   //   i64   reg_save_area (address)
19460   // }
19461   // sizeof(va_list) = 24
19462   // alignment(va_list) = 8
19463
19464   unsigned TotalNumIntRegs = 6;
19465   unsigned TotalNumXMMRegs = 8;
19466   bool UseGPOffset = (ArgMode == 1);
19467   bool UseFPOffset = (ArgMode == 2);
19468   unsigned MaxOffset = TotalNumIntRegs * 8 +
19469                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19470
19471   /* Align ArgSize to a multiple of 8 */
19472   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19473   bool NeedsAlign = (Align > 8);
19474
19475   MachineBasicBlock *thisMBB = MBB;
19476   MachineBasicBlock *overflowMBB;
19477   MachineBasicBlock *offsetMBB;
19478   MachineBasicBlock *endMBB;
19479
19480   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19481   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19482   unsigned OffsetReg = 0;
19483
19484   if (!UseGPOffset && !UseFPOffset) {
19485     // If we only pull from the overflow region, we don't create a branch.
19486     // We don't need to alter control flow.
19487     OffsetDestReg = 0; // unused
19488     OverflowDestReg = DestReg;
19489
19490     offsetMBB = nullptr;
19491     overflowMBB = thisMBB;
19492     endMBB = thisMBB;
19493   } else {
19494     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19495     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19496     // If not, pull from overflow_area. (branch to overflowMBB)
19497     //
19498     //       thisMBB
19499     //         |     .
19500     //         |        .
19501     //     offsetMBB   overflowMBB
19502     //         |        .
19503     //         |     .
19504     //        endMBB
19505
19506     // Registers for the PHI in endMBB
19507     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19508     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19509
19510     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19511     MachineFunction *MF = MBB->getParent();
19512     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19513     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19514     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19515
19516     MachineFunction::iterator MBBIter = MBB;
19517     ++MBBIter;
19518
19519     // Insert the new basic blocks
19520     MF->insert(MBBIter, offsetMBB);
19521     MF->insert(MBBIter, overflowMBB);
19522     MF->insert(MBBIter, endMBB);
19523
19524     // Transfer the remainder of MBB and its successor edges to endMBB.
19525     endMBB->splice(endMBB->begin(), thisMBB,
19526                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19527     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19528
19529     // Make offsetMBB and overflowMBB successors of thisMBB
19530     thisMBB->addSuccessor(offsetMBB);
19531     thisMBB->addSuccessor(overflowMBB);
19532
19533     // endMBB is a successor of both offsetMBB and overflowMBB
19534     offsetMBB->addSuccessor(endMBB);
19535     overflowMBB->addSuccessor(endMBB);
19536
19537     // Load the offset value into a register
19538     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19539     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19540       .addOperand(Base)
19541       .addOperand(Scale)
19542       .addOperand(Index)
19543       .addDisp(Disp, UseFPOffset ? 4 : 0)
19544       .addOperand(Segment)
19545       .setMemRefs(MMOBegin, MMOEnd);
19546
19547     // Check if there is enough room left to pull this argument.
19548     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19549       .addReg(OffsetReg)
19550       .addImm(MaxOffset + 8 - ArgSizeA8);
19551
19552     // Branch to "overflowMBB" if offset >= max
19553     // Fall through to "offsetMBB" otherwise
19554     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19555       .addMBB(overflowMBB);
19556   }
19557
19558   // In offsetMBB, emit code to use the reg_save_area.
19559   if (offsetMBB) {
19560     assert(OffsetReg != 0);
19561
19562     // Read the reg_save_area address.
19563     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19564     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19565       .addOperand(Base)
19566       .addOperand(Scale)
19567       .addOperand(Index)
19568       .addDisp(Disp, 16)
19569       .addOperand(Segment)
19570       .setMemRefs(MMOBegin, MMOEnd);
19571
19572     // Zero-extend the offset
19573     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19574       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19575         .addImm(0)
19576         .addReg(OffsetReg)
19577         .addImm(X86::sub_32bit);
19578
19579     // Add the offset to the reg_save_area to get the final address.
19580     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19581       .addReg(OffsetReg64)
19582       .addReg(RegSaveReg);
19583
19584     // Compute the offset for the next argument
19585     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19586     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19587       .addReg(OffsetReg)
19588       .addImm(UseFPOffset ? 16 : 8);
19589
19590     // Store it back into the va_list.
19591     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19592       .addOperand(Base)
19593       .addOperand(Scale)
19594       .addOperand(Index)
19595       .addDisp(Disp, UseFPOffset ? 4 : 0)
19596       .addOperand(Segment)
19597       .addReg(NextOffsetReg)
19598       .setMemRefs(MMOBegin, MMOEnd);
19599
19600     // Jump to endMBB
19601     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19602       .addMBB(endMBB);
19603   }
19604
19605   //
19606   // Emit code to use overflow area
19607   //
19608
19609   // Load the overflow_area address into a register.
19610   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19611   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19612     .addOperand(Base)
19613     .addOperand(Scale)
19614     .addOperand(Index)
19615     .addDisp(Disp, 8)
19616     .addOperand(Segment)
19617     .setMemRefs(MMOBegin, MMOEnd);
19618
19619   // If we need to align it, do so. Otherwise, just copy the address
19620   // to OverflowDestReg.
19621   if (NeedsAlign) {
19622     // Align the overflow address
19623     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19624     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19625
19626     // aligned_addr = (addr + (align-1)) & ~(align-1)
19627     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19628       .addReg(OverflowAddrReg)
19629       .addImm(Align-1);
19630
19631     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19632       .addReg(TmpReg)
19633       .addImm(~(uint64_t)(Align-1));
19634   } else {
19635     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19636       .addReg(OverflowAddrReg);
19637   }
19638
19639   // Compute the next overflow address after this argument.
19640   // (the overflow address should be kept 8-byte aligned)
19641   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19642   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19643     .addReg(OverflowDestReg)
19644     .addImm(ArgSizeA8);
19645
19646   // Store the new overflow address.
19647   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19648     .addOperand(Base)
19649     .addOperand(Scale)
19650     .addOperand(Index)
19651     .addDisp(Disp, 8)
19652     .addOperand(Segment)
19653     .addReg(NextAddrReg)
19654     .setMemRefs(MMOBegin, MMOEnd);
19655
19656   // If we branched, emit the PHI to the front of endMBB.
19657   if (offsetMBB) {
19658     BuildMI(*endMBB, endMBB->begin(), DL,
19659             TII->get(X86::PHI), DestReg)
19660       .addReg(OffsetDestReg).addMBB(offsetMBB)
19661       .addReg(OverflowDestReg).addMBB(overflowMBB);
19662   }
19663
19664   // Erase the pseudo instruction
19665   MI->eraseFromParent();
19666
19667   return endMBB;
19668 }
19669
19670 MachineBasicBlock *
19671 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19672                                                  MachineInstr *MI,
19673                                                  MachineBasicBlock *MBB) const {
19674   // Emit code to save XMM registers to the stack. The ABI says that the
19675   // number of registers to save is given in %al, so it's theoretically
19676   // possible to do an indirect jump trick to avoid saving all of them,
19677   // however this code takes a simpler approach and just executes all
19678   // of the stores if %al is non-zero. It's less code, and it's probably
19679   // easier on the hardware branch predictor, and stores aren't all that
19680   // expensive anyway.
19681
19682   // Create the new basic blocks. One block contains all the XMM stores,
19683   // and one block is the final destination regardless of whether any
19684   // stores were performed.
19685   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19686   MachineFunction *F = MBB->getParent();
19687   MachineFunction::iterator MBBIter = MBB;
19688   ++MBBIter;
19689   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19690   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19691   F->insert(MBBIter, XMMSaveMBB);
19692   F->insert(MBBIter, EndMBB);
19693
19694   // Transfer the remainder of MBB and its successor edges to EndMBB.
19695   EndMBB->splice(EndMBB->begin(), MBB,
19696                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19697   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19698
19699   // The original block will now fall through to the XMM save block.
19700   MBB->addSuccessor(XMMSaveMBB);
19701   // The XMMSaveMBB will fall through to the end block.
19702   XMMSaveMBB->addSuccessor(EndMBB);
19703
19704   // Now add the instructions.
19705   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19706   DebugLoc DL = MI->getDebugLoc();
19707
19708   unsigned CountReg = MI->getOperand(0).getReg();
19709   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19710   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19711
19712   if (!Subtarget->isTargetWin64()) {
19713     // If %al is 0, branch around the XMM save block.
19714     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19715     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19716     MBB->addSuccessor(EndMBB);
19717   }
19718
19719   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19720   // that was just emitted, but clearly shouldn't be "saved".
19721   assert((MI->getNumOperands() <= 3 ||
19722           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19723           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19724          && "Expected last argument to be EFLAGS");
19725   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19726   // In the XMM save block, save all the XMM argument registers.
19727   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19728     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19729     MachineMemOperand *MMO =
19730       F->getMachineMemOperand(
19731           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19732         MachineMemOperand::MOStore,
19733         /*Size=*/16, /*Align=*/16);
19734     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19735       .addFrameIndex(RegSaveFrameIndex)
19736       .addImm(/*Scale=*/1)
19737       .addReg(/*IndexReg=*/0)
19738       .addImm(/*Disp=*/Offset)
19739       .addReg(/*Segment=*/0)
19740       .addReg(MI->getOperand(i).getReg())
19741       .addMemOperand(MMO);
19742   }
19743
19744   MI->eraseFromParent();   // The pseudo instruction is gone now.
19745
19746   return EndMBB;
19747 }
19748
19749 // The EFLAGS operand of SelectItr might be missing a kill marker
19750 // because there were multiple uses of EFLAGS, and ISel didn't know
19751 // which to mark. Figure out whether SelectItr should have had a
19752 // kill marker, and set it if it should. Returns the correct kill
19753 // marker value.
19754 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19755                                      MachineBasicBlock* BB,
19756                                      const TargetRegisterInfo* TRI) {
19757   // Scan forward through BB for a use/def of EFLAGS.
19758   MachineBasicBlock::iterator miI(std::next(SelectItr));
19759   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19760     const MachineInstr& mi = *miI;
19761     if (mi.readsRegister(X86::EFLAGS))
19762       return false;
19763     if (mi.definesRegister(X86::EFLAGS))
19764       break; // Should have kill-flag - update below.
19765   }
19766
19767   // If we hit the end of the block, check whether EFLAGS is live into a
19768   // successor.
19769   if (miI == BB->end()) {
19770     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19771                                           sEnd = BB->succ_end();
19772          sItr != sEnd; ++sItr) {
19773       MachineBasicBlock* succ = *sItr;
19774       if (succ->isLiveIn(X86::EFLAGS))
19775         return false;
19776     }
19777   }
19778
19779   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19780   // out. SelectMI should have a kill flag on EFLAGS.
19781   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19782   return true;
19783 }
19784
19785 MachineBasicBlock *
19786 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19787                                      MachineBasicBlock *BB) const {
19788   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19789   DebugLoc DL = MI->getDebugLoc();
19790
19791   // To "insert" a SELECT_CC instruction, we actually have to insert the
19792   // diamond control-flow pattern.  The incoming instruction knows the
19793   // destination vreg to set, the condition code register to branch on, the
19794   // true/false values to select between, and a branch opcode to use.
19795   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19796   MachineFunction::iterator It = BB;
19797   ++It;
19798
19799   //  thisMBB:
19800   //  ...
19801   //   TrueVal = ...
19802   //   cmpTY ccX, r1, r2
19803   //   bCC copy1MBB
19804   //   fallthrough --> copy0MBB
19805   MachineBasicBlock *thisMBB = BB;
19806   MachineFunction *F = BB->getParent();
19807
19808   // We also lower double CMOVs:
19809   //   (CMOV (CMOV F, T, cc1), T, cc2)
19810   // to two successives branches.  For that, we look for another CMOV as the
19811   // following instruction.
19812   //
19813   // Without this, we would add a PHI between the two jumps, which ends up
19814   // creating a few copies all around. For instance, for
19815   //
19816   //    (sitofp (zext (fcmp une)))
19817   //
19818   // we would generate:
19819   //
19820   //         ucomiss %xmm1, %xmm0
19821   //         movss  <1.0f>, %xmm0
19822   //         movaps  %xmm0, %xmm1
19823   //         jne     .LBB5_2
19824   //         xorps   %xmm1, %xmm1
19825   // .LBB5_2:
19826   //         jp      .LBB5_4
19827   //         movaps  %xmm1, %xmm0
19828   // .LBB5_4:
19829   //         retq
19830   //
19831   // because this custom-inserter would have generated:
19832   //
19833   //   A
19834   //   | \
19835   //   |  B
19836   //   | /
19837   //   C
19838   //   | \
19839   //   |  D
19840   //   | /
19841   //   E
19842   //
19843   // A: X = ...; Y = ...
19844   // B: empty
19845   // C: Z = PHI [X, A], [Y, B]
19846   // D: empty
19847   // E: PHI [X, C], [Z, D]
19848   //
19849   // If we lower both CMOVs in a single step, we can instead generate:
19850   //
19851   //   A
19852   //   | \
19853   //   |  C
19854   //   | /|
19855   //   |/ |
19856   //   |  |
19857   //   |  D
19858   //   | /
19859   //   E
19860   //
19861   // A: X = ...; Y = ...
19862   // D: empty
19863   // E: PHI [X, A], [X, C], [Y, D]
19864   //
19865   // Which, in our sitofp/fcmp example, gives us something like:
19866   //
19867   //         ucomiss %xmm1, %xmm0
19868   //         movss  <1.0f>, %xmm0
19869   //         jne     .LBB5_4
19870   //         jp      .LBB5_4
19871   //         xorps   %xmm0, %xmm0
19872   // .LBB5_4:
19873   //         retq
19874   //
19875   MachineInstr *NextCMOV = nullptr;
19876   MachineBasicBlock::iterator NextMIIt =
19877       std::next(MachineBasicBlock::iterator(MI));
19878   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19879       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19880       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19881     NextCMOV = &*NextMIIt;
19882
19883   MachineBasicBlock *jcc1MBB = nullptr;
19884
19885   // If we have a double CMOV, we lower it to two successive branches to
19886   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19887   if (NextCMOV) {
19888     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19889     F->insert(It, jcc1MBB);
19890     jcc1MBB->addLiveIn(X86::EFLAGS);
19891   }
19892
19893   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19894   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19895   F->insert(It, copy0MBB);
19896   F->insert(It, sinkMBB);
19897
19898   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19899   // live into the sink and copy blocks.
19900   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19901
19902   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19903   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19904       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19905     copy0MBB->addLiveIn(X86::EFLAGS);
19906     sinkMBB->addLiveIn(X86::EFLAGS);
19907   }
19908
19909   // Transfer the remainder of BB and its successor edges to sinkMBB.
19910   sinkMBB->splice(sinkMBB->begin(), BB,
19911                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19912   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19913
19914   // Add the true and fallthrough blocks as its successors.
19915   if (NextCMOV) {
19916     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19917     BB->addSuccessor(jcc1MBB);
19918
19919     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19920     // jump to the sinkMBB.
19921     jcc1MBB->addSuccessor(copy0MBB);
19922     jcc1MBB->addSuccessor(sinkMBB);
19923   } else {
19924     BB->addSuccessor(copy0MBB);
19925   }
19926
19927   // The true block target of the first (or only) branch is always sinkMBB.
19928   BB->addSuccessor(sinkMBB);
19929
19930   // Create the conditional branch instruction.
19931   unsigned Opc =
19932     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19933   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19934
19935   if (NextCMOV) {
19936     unsigned Opc2 = X86::GetCondBranchFromCond(
19937         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19938     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19939   }
19940
19941   //  copy0MBB:
19942   //   %FalseValue = ...
19943   //   # fallthrough to sinkMBB
19944   copy0MBB->addSuccessor(sinkMBB);
19945
19946   //  sinkMBB:
19947   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19948   //  ...
19949   MachineInstrBuilder MIB =
19950       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19951               MI->getOperand(0).getReg())
19952           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19953           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19954
19955   // If we have a double CMOV, the second Jcc provides the same incoming
19956   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19957   if (NextCMOV) {
19958     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19959     // Copy the PHI result to the register defined by the second CMOV.
19960     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19961             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19962         .addReg(MI->getOperand(0).getReg());
19963     NextCMOV->eraseFromParent();
19964   }
19965
19966   MI->eraseFromParent();   // The pseudo instruction is gone now.
19967   return sinkMBB;
19968 }
19969
19970 MachineBasicBlock *
19971 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19972                                         MachineBasicBlock *BB) const {
19973   MachineFunction *MF = BB->getParent();
19974   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19975   DebugLoc DL = MI->getDebugLoc();
19976   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19977
19978   assert(MF->shouldSplitStack());
19979
19980   const bool Is64Bit = Subtarget->is64Bit();
19981   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19982
19983   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19984   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19985
19986   // BB:
19987   //  ... [Till the alloca]
19988   // If stacklet is not large enough, jump to mallocMBB
19989   //
19990   // bumpMBB:
19991   //  Allocate by subtracting from RSP
19992   //  Jump to continueMBB
19993   //
19994   // mallocMBB:
19995   //  Allocate by call to runtime
19996   //
19997   // continueMBB:
19998   //  ...
19999   //  [rest of original BB]
20000   //
20001
20002   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20003   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20004   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
20005
20006   MachineRegisterInfo &MRI = MF->getRegInfo();
20007   const TargetRegisterClass *AddrRegClass =
20008       getRegClassFor(getPointerTy(MF->getDataLayout()));
20009
20010   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20011     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
20012     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
20013     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
20014     sizeVReg = MI->getOperand(1).getReg(),
20015     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
20016
20017   MachineFunction::iterator MBBIter = BB;
20018   ++MBBIter;
20019
20020   MF->insert(MBBIter, bumpMBB);
20021   MF->insert(MBBIter, mallocMBB);
20022   MF->insert(MBBIter, continueMBB);
20023
20024   continueMBB->splice(continueMBB->begin(), BB,
20025                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20026   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20027
20028   // Add code to the main basic block to check if the stack limit has been hit,
20029   // and if so, jump to mallocMBB otherwise to bumpMBB.
20030   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20031   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20032     .addReg(tmpSPVReg).addReg(sizeVReg);
20033   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20034     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20035     .addReg(SPLimitVReg);
20036   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20037
20038   // bumpMBB simply decreases the stack pointer, since we know the current
20039   // stacklet has enough space.
20040   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20041     .addReg(SPLimitVReg);
20042   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20043     .addReg(SPLimitVReg);
20044   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20045
20046   // Calls into a routine in libgcc to allocate more space from the heap.
20047   const uint32_t *RegMask =
20048       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20049   if (IsLP64) {
20050     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20051       .addReg(sizeVReg);
20052     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20053       .addExternalSymbol("__morestack_allocate_stack_space")
20054       .addRegMask(RegMask)
20055       .addReg(X86::RDI, RegState::Implicit)
20056       .addReg(X86::RAX, RegState::ImplicitDefine);
20057   } else if (Is64Bit) {
20058     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20059       .addReg(sizeVReg);
20060     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20061       .addExternalSymbol("__morestack_allocate_stack_space")
20062       .addRegMask(RegMask)
20063       .addReg(X86::EDI, RegState::Implicit)
20064       .addReg(X86::EAX, RegState::ImplicitDefine);
20065   } else {
20066     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20067       .addImm(12);
20068     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20069     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20070       .addExternalSymbol("__morestack_allocate_stack_space")
20071       .addRegMask(RegMask)
20072       .addReg(X86::EAX, RegState::ImplicitDefine);
20073   }
20074
20075   if (!Is64Bit)
20076     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20077       .addImm(16);
20078
20079   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20080     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20081   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20082
20083   // Set up the CFG correctly.
20084   BB->addSuccessor(bumpMBB);
20085   BB->addSuccessor(mallocMBB);
20086   mallocMBB->addSuccessor(continueMBB);
20087   bumpMBB->addSuccessor(continueMBB);
20088
20089   // Take care of the PHI nodes.
20090   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20091           MI->getOperand(0).getReg())
20092     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20093     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20094
20095   // Delete the original pseudo instruction.
20096   MI->eraseFromParent();
20097
20098   // And we're done.
20099   return continueMBB;
20100 }
20101
20102 MachineBasicBlock *
20103 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20104                                         MachineBasicBlock *BB) const {
20105   DebugLoc DL = MI->getDebugLoc();
20106
20107   assert(!Subtarget->isTargetMachO());
20108
20109   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20110                                                     DL);
20111
20112   MI->eraseFromParent();   // The pseudo instruction is gone now.
20113   return BB;
20114 }
20115
20116 MachineBasicBlock *
20117 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20118                                       MachineBasicBlock *BB) const {
20119   // This is pretty easy.  We're taking the value that we received from
20120   // our load from the relocation, sticking it in either RDI (x86-64)
20121   // or EAX and doing an indirect call.  The return value will then
20122   // be in the normal return register.
20123   MachineFunction *F = BB->getParent();
20124   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20125   DebugLoc DL = MI->getDebugLoc();
20126
20127   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20128   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20129
20130   // Get a register mask for the lowered call.
20131   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20132   // proper register mask.
20133   const uint32_t *RegMask =
20134       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20135   if (Subtarget->is64Bit()) {
20136     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20137                                       TII->get(X86::MOV64rm), X86::RDI)
20138     .addReg(X86::RIP)
20139     .addImm(0).addReg(0)
20140     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20141                       MI->getOperand(3).getTargetFlags())
20142     .addReg(0);
20143     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20144     addDirectMem(MIB, X86::RDI);
20145     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20146   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20147     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20148                                       TII->get(X86::MOV32rm), X86::EAX)
20149     .addReg(0)
20150     .addImm(0).addReg(0)
20151     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20152                       MI->getOperand(3).getTargetFlags())
20153     .addReg(0);
20154     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20155     addDirectMem(MIB, X86::EAX);
20156     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20157   } else {
20158     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20159                                       TII->get(X86::MOV32rm), X86::EAX)
20160     .addReg(TII->getGlobalBaseReg(F))
20161     .addImm(0).addReg(0)
20162     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20163                       MI->getOperand(3).getTargetFlags())
20164     .addReg(0);
20165     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20166     addDirectMem(MIB, X86::EAX);
20167     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20168   }
20169
20170   MI->eraseFromParent(); // The pseudo instruction is gone now.
20171   return BB;
20172 }
20173
20174 MachineBasicBlock *
20175 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20176                                     MachineBasicBlock *MBB) const {
20177   DebugLoc DL = MI->getDebugLoc();
20178   MachineFunction *MF = MBB->getParent();
20179   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20180   MachineRegisterInfo &MRI = MF->getRegInfo();
20181
20182   const BasicBlock *BB = MBB->getBasicBlock();
20183   MachineFunction::iterator I = MBB;
20184   ++I;
20185
20186   // Memory Reference
20187   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20188   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20189
20190   unsigned DstReg;
20191   unsigned MemOpndSlot = 0;
20192
20193   unsigned CurOp = 0;
20194
20195   DstReg = MI->getOperand(CurOp++).getReg();
20196   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20197   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20198   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20199   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20200
20201   MemOpndSlot = CurOp;
20202
20203   MVT PVT = getPointerTy(MF->getDataLayout());
20204   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20205          "Invalid Pointer Size!");
20206
20207   // For v = setjmp(buf), we generate
20208   //
20209   // thisMBB:
20210   //  buf[LabelOffset] = restoreMBB
20211   //  SjLjSetup restoreMBB
20212   //
20213   // mainMBB:
20214   //  v_main = 0
20215   //
20216   // sinkMBB:
20217   //  v = phi(main, restore)
20218   //
20219   // restoreMBB:
20220   //  if base pointer being used, load it from frame
20221   //  v_restore = 1
20222
20223   MachineBasicBlock *thisMBB = MBB;
20224   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20225   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20226   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20227   MF->insert(I, mainMBB);
20228   MF->insert(I, sinkMBB);
20229   MF->push_back(restoreMBB);
20230
20231   MachineInstrBuilder MIB;
20232
20233   // Transfer the remainder of BB and its successor edges to sinkMBB.
20234   sinkMBB->splice(sinkMBB->begin(), MBB,
20235                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20236   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20237
20238   // thisMBB:
20239   unsigned PtrStoreOpc = 0;
20240   unsigned LabelReg = 0;
20241   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20242   Reloc::Model RM = MF->getTarget().getRelocationModel();
20243   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20244                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20245
20246   // Prepare IP either in reg or imm.
20247   if (!UseImmLabel) {
20248     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20249     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20250     LabelReg = MRI.createVirtualRegister(PtrRC);
20251     if (Subtarget->is64Bit()) {
20252       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20253               .addReg(X86::RIP)
20254               .addImm(0)
20255               .addReg(0)
20256               .addMBB(restoreMBB)
20257               .addReg(0);
20258     } else {
20259       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20260       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20261               .addReg(XII->getGlobalBaseReg(MF))
20262               .addImm(0)
20263               .addReg(0)
20264               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20265               .addReg(0);
20266     }
20267   } else
20268     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20269   // Store IP
20270   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20271   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20272     if (i == X86::AddrDisp)
20273       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20274     else
20275       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20276   }
20277   if (!UseImmLabel)
20278     MIB.addReg(LabelReg);
20279   else
20280     MIB.addMBB(restoreMBB);
20281   MIB.setMemRefs(MMOBegin, MMOEnd);
20282   // Setup
20283   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20284           .addMBB(restoreMBB);
20285
20286   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20287   MIB.addRegMask(RegInfo->getNoPreservedMask());
20288   thisMBB->addSuccessor(mainMBB);
20289   thisMBB->addSuccessor(restoreMBB);
20290
20291   // mainMBB:
20292   //  EAX = 0
20293   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20294   mainMBB->addSuccessor(sinkMBB);
20295
20296   // sinkMBB:
20297   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20298           TII->get(X86::PHI), DstReg)
20299     .addReg(mainDstReg).addMBB(mainMBB)
20300     .addReg(restoreDstReg).addMBB(restoreMBB);
20301
20302   // restoreMBB:
20303   if (RegInfo->hasBasePointer(*MF)) {
20304     const bool Uses64BitFramePtr =
20305         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20306     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20307     X86FI->setRestoreBasePointer(MF);
20308     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20309     unsigned BasePtr = RegInfo->getBaseRegister();
20310     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20311     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20312                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20313       .setMIFlag(MachineInstr::FrameSetup);
20314   }
20315   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20316   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20317   restoreMBB->addSuccessor(sinkMBB);
20318
20319   MI->eraseFromParent();
20320   return sinkMBB;
20321 }
20322
20323 MachineBasicBlock *
20324 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20325                                      MachineBasicBlock *MBB) const {
20326   DebugLoc DL = MI->getDebugLoc();
20327   MachineFunction *MF = MBB->getParent();
20328   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20329   MachineRegisterInfo &MRI = MF->getRegInfo();
20330
20331   // Memory Reference
20332   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20333   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20334
20335   MVT PVT = getPointerTy(MF->getDataLayout());
20336   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20337          "Invalid Pointer Size!");
20338
20339   const TargetRegisterClass *RC =
20340     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20341   unsigned Tmp = MRI.createVirtualRegister(RC);
20342   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20343   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20344   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20345   unsigned SP = RegInfo->getStackRegister();
20346
20347   MachineInstrBuilder MIB;
20348
20349   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20350   const int64_t SPOffset = 2 * PVT.getStoreSize();
20351
20352   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20353   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20354
20355   // Reload FP
20356   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20357   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20358     MIB.addOperand(MI->getOperand(i));
20359   MIB.setMemRefs(MMOBegin, MMOEnd);
20360   // Reload IP
20361   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20362   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20363     if (i == X86::AddrDisp)
20364       MIB.addDisp(MI->getOperand(i), LabelOffset);
20365     else
20366       MIB.addOperand(MI->getOperand(i));
20367   }
20368   MIB.setMemRefs(MMOBegin, MMOEnd);
20369   // Reload SP
20370   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20371   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20372     if (i == X86::AddrDisp)
20373       MIB.addDisp(MI->getOperand(i), SPOffset);
20374     else
20375       MIB.addOperand(MI->getOperand(i));
20376   }
20377   MIB.setMemRefs(MMOBegin, MMOEnd);
20378   // Jump
20379   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20380
20381   MI->eraseFromParent();
20382   return MBB;
20383 }
20384
20385 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20386 // accumulator loops. Writing back to the accumulator allows the coalescer
20387 // to remove extra copies in the loop.
20388 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20389 MachineBasicBlock *
20390 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20391                                  MachineBasicBlock *MBB) const {
20392   MachineOperand &AddendOp = MI->getOperand(3);
20393
20394   // Bail out early if the addend isn't a register - we can't switch these.
20395   if (!AddendOp.isReg())
20396     return MBB;
20397
20398   MachineFunction &MF = *MBB->getParent();
20399   MachineRegisterInfo &MRI = MF.getRegInfo();
20400
20401   // Check whether the addend is defined by a PHI:
20402   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20403   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20404   if (!AddendDef.isPHI())
20405     return MBB;
20406
20407   // Look for the following pattern:
20408   // loop:
20409   //   %addend = phi [%entry, 0], [%loop, %result]
20410   //   ...
20411   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20412
20413   // Replace with:
20414   //   loop:
20415   //   %addend = phi [%entry, 0], [%loop, %result]
20416   //   ...
20417   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20418
20419   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20420     assert(AddendDef.getOperand(i).isReg());
20421     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20422     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20423     if (&PHISrcInst == MI) {
20424       // Found a matching instruction.
20425       unsigned NewFMAOpc = 0;
20426       switch (MI->getOpcode()) {
20427         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20428         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20429         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20430         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20431         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20432         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20433         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20434         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20435         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20436         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20437         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20438         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20439         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20440         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20441         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20442         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20443         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20444         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20445         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20446         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20447
20448         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20449         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20450         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20451         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20452         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20453         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20454         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20455         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20456         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20457         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20458         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20459         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20460         default: llvm_unreachable("Unrecognized FMA variant.");
20461       }
20462
20463       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20464       MachineInstrBuilder MIB =
20465         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20466         .addOperand(MI->getOperand(0))
20467         .addOperand(MI->getOperand(3))
20468         .addOperand(MI->getOperand(2))
20469         .addOperand(MI->getOperand(1));
20470       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20471       MI->eraseFromParent();
20472     }
20473   }
20474
20475   return MBB;
20476 }
20477
20478 MachineBasicBlock *
20479 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20480                                                MachineBasicBlock *BB) const {
20481   switch (MI->getOpcode()) {
20482   default: llvm_unreachable("Unexpected instr type to insert");
20483   case X86::TAILJMPd64:
20484   case X86::TAILJMPr64:
20485   case X86::TAILJMPm64:
20486   case X86::TAILJMPd64_REX:
20487   case X86::TAILJMPr64_REX:
20488   case X86::TAILJMPm64_REX:
20489     llvm_unreachable("TAILJMP64 would not be touched here.");
20490   case X86::TCRETURNdi64:
20491   case X86::TCRETURNri64:
20492   case X86::TCRETURNmi64:
20493     return BB;
20494   case X86::WIN_ALLOCA:
20495     return EmitLoweredWinAlloca(MI, BB);
20496   case X86::SEG_ALLOCA_32:
20497   case X86::SEG_ALLOCA_64:
20498     return EmitLoweredSegAlloca(MI, BB);
20499   case X86::TLSCall_32:
20500   case X86::TLSCall_64:
20501     return EmitLoweredTLSCall(MI, BB);
20502   case X86::CMOV_GR8:
20503   case X86::CMOV_FR32:
20504   case X86::CMOV_FR64:
20505   case X86::CMOV_V4F32:
20506   case X86::CMOV_V2F64:
20507   case X86::CMOV_V2I64:
20508   case X86::CMOV_V8F32:
20509   case X86::CMOV_V4F64:
20510   case X86::CMOV_V4I64:
20511   case X86::CMOV_V16F32:
20512   case X86::CMOV_V8F64:
20513   case X86::CMOV_V8I64:
20514   case X86::CMOV_GR16:
20515   case X86::CMOV_GR32:
20516   case X86::CMOV_RFP32:
20517   case X86::CMOV_RFP64:
20518   case X86::CMOV_RFP80:
20519   case X86::CMOV_V8I1:
20520   case X86::CMOV_V16I1:
20521   case X86::CMOV_V32I1:
20522   case X86::CMOV_V64I1:
20523     return EmitLoweredSelect(MI, BB);
20524
20525   case X86::FP32_TO_INT16_IN_MEM:
20526   case X86::FP32_TO_INT32_IN_MEM:
20527   case X86::FP32_TO_INT64_IN_MEM:
20528   case X86::FP64_TO_INT16_IN_MEM:
20529   case X86::FP64_TO_INT32_IN_MEM:
20530   case X86::FP64_TO_INT64_IN_MEM:
20531   case X86::FP80_TO_INT16_IN_MEM:
20532   case X86::FP80_TO_INT32_IN_MEM:
20533   case X86::FP80_TO_INT64_IN_MEM: {
20534     MachineFunction *F = BB->getParent();
20535     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20536     DebugLoc DL = MI->getDebugLoc();
20537
20538     // Change the floating point control register to use "round towards zero"
20539     // mode when truncating to an integer value.
20540     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20541     addFrameReference(BuildMI(*BB, MI, DL,
20542                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20543
20544     // Load the old value of the high byte of the control word...
20545     unsigned OldCW =
20546       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20547     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20548                       CWFrameIdx);
20549
20550     // Set the high part to be round to zero...
20551     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20552       .addImm(0xC7F);
20553
20554     // Reload the modified control word now...
20555     addFrameReference(BuildMI(*BB, MI, DL,
20556                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20557
20558     // Restore the memory image of control word to original value
20559     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20560       .addReg(OldCW);
20561
20562     // Get the X86 opcode to use.
20563     unsigned Opc;
20564     switch (MI->getOpcode()) {
20565     default: llvm_unreachable("illegal opcode!");
20566     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20567     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20568     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20569     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20570     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20571     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20572     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20573     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20574     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20575     }
20576
20577     X86AddressMode AM;
20578     MachineOperand &Op = MI->getOperand(0);
20579     if (Op.isReg()) {
20580       AM.BaseType = X86AddressMode::RegBase;
20581       AM.Base.Reg = Op.getReg();
20582     } else {
20583       AM.BaseType = X86AddressMode::FrameIndexBase;
20584       AM.Base.FrameIndex = Op.getIndex();
20585     }
20586     Op = MI->getOperand(1);
20587     if (Op.isImm())
20588       AM.Scale = Op.getImm();
20589     Op = MI->getOperand(2);
20590     if (Op.isImm())
20591       AM.IndexReg = Op.getImm();
20592     Op = MI->getOperand(3);
20593     if (Op.isGlobal()) {
20594       AM.GV = Op.getGlobal();
20595     } else {
20596       AM.Disp = Op.getImm();
20597     }
20598     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20599                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20600
20601     // Reload the original control word now.
20602     addFrameReference(BuildMI(*BB, MI, DL,
20603                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20604
20605     MI->eraseFromParent();   // The pseudo instruction is gone now.
20606     return BB;
20607   }
20608     // String/text processing lowering.
20609   case X86::PCMPISTRM128REG:
20610   case X86::VPCMPISTRM128REG:
20611   case X86::PCMPISTRM128MEM:
20612   case X86::VPCMPISTRM128MEM:
20613   case X86::PCMPESTRM128REG:
20614   case X86::VPCMPESTRM128REG:
20615   case X86::PCMPESTRM128MEM:
20616   case X86::VPCMPESTRM128MEM:
20617     assert(Subtarget->hasSSE42() &&
20618            "Target must have SSE4.2 or AVX features enabled");
20619     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20620
20621   // String/text processing lowering.
20622   case X86::PCMPISTRIREG:
20623   case X86::VPCMPISTRIREG:
20624   case X86::PCMPISTRIMEM:
20625   case X86::VPCMPISTRIMEM:
20626   case X86::PCMPESTRIREG:
20627   case X86::VPCMPESTRIREG:
20628   case X86::PCMPESTRIMEM:
20629   case X86::VPCMPESTRIMEM:
20630     assert(Subtarget->hasSSE42() &&
20631            "Target must have SSE4.2 or AVX features enabled");
20632     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20633
20634   // Thread synchronization.
20635   case X86::MONITOR:
20636     return EmitMonitor(MI, BB, Subtarget);
20637
20638   // xbegin
20639   case X86::XBEGIN:
20640     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20641
20642   case X86::VASTART_SAVE_XMM_REGS:
20643     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20644
20645   case X86::VAARG_64:
20646     return EmitVAARG64WithCustomInserter(MI, BB);
20647
20648   case X86::EH_SjLj_SetJmp32:
20649   case X86::EH_SjLj_SetJmp64:
20650     return emitEHSjLjSetJmp(MI, BB);
20651
20652   case X86::EH_SjLj_LongJmp32:
20653   case X86::EH_SjLj_LongJmp64:
20654     return emitEHSjLjLongJmp(MI, BB);
20655
20656   case TargetOpcode::STATEPOINT:
20657     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20658     // this point in the process.  We diverge later.
20659     return emitPatchPoint(MI, BB);
20660
20661   case TargetOpcode::STACKMAP:
20662   case TargetOpcode::PATCHPOINT:
20663     return emitPatchPoint(MI, BB);
20664
20665   case X86::VFMADDPDr213r:
20666   case X86::VFMADDPSr213r:
20667   case X86::VFMADDSDr213r:
20668   case X86::VFMADDSSr213r:
20669   case X86::VFMSUBPDr213r:
20670   case X86::VFMSUBPSr213r:
20671   case X86::VFMSUBSDr213r:
20672   case X86::VFMSUBSSr213r:
20673   case X86::VFNMADDPDr213r:
20674   case X86::VFNMADDPSr213r:
20675   case X86::VFNMADDSDr213r:
20676   case X86::VFNMADDSSr213r:
20677   case X86::VFNMSUBPDr213r:
20678   case X86::VFNMSUBPSr213r:
20679   case X86::VFNMSUBSDr213r:
20680   case X86::VFNMSUBSSr213r:
20681   case X86::VFMADDSUBPDr213r:
20682   case X86::VFMADDSUBPSr213r:
20683   case X86::VFMSUBADDPDr213r:
20684   case X86::VFMSUBADDPSr213r:
20685   case X86::VFMADDPDr213rY:
20686   case X86::VFMADDPSr213rY:
20687   case X86::VFMSUBPDr213rY:
20688   case X86::VFMSUBPSr213rY:
20689   case X86::VFNMADDPDr213rY:
20690   case X86::VFNMADDPSr213rY:
20691   case X86::VFNMSUBPDr213rY:
20692   case X86::VFNMSUBPSr213rY:
20693   case X86::VFMADDSUBPDr213rY:
20694   case X86::VFMADDSUBPSr213rY:
20695   case X86::VFMSUBADDPDr213rY:
20696   case X86::VFMSUBADDPSr213rY:
20697     return emitFMA3Instr(MI, BB);
20698   }
20699 }
20700
20701 //===----------------------------------------------------------------------===//
20702 //                           X86 Optimization Hooks
20703 //===----------------------------------------------------------------------===//
20704
20705 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20706                                                       APInt &KnownZero,
20707                                                       APInt &KnownOne,
20708                                                       const SelectionDAG &DAG,
20709                                                       unsigned Depth) const {
20710   unsigned BitWidth = KnownZero.getBitWidth();
20711   unsigned Opc = Op.getOpcode();
20712   assert((Opc >= ISD::BUILTIN_OP_END ||
20713           Opc == ISD::INTRINSIC_WO_CHAIN ||
20714           Opc == ISD::INTRINSIC_W_CHAIN ||
20715           Opc == ISD::INTRINSIC_VOID) &&
20716          "Should use MaskedValueIsZero if you don't know whether Op"
20717          " is a target node!");
20718
20719   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20720   switch (Opc) {
20721   default: break;
20722   case X86ISD::ADD:
20723   case X86ISD::SUB:
20724   case X86ISD::ADC:
20725   case X86ISD::SBB:
20726   case X86ISD::SMUL:
20727   case X86ISD::UMUL:
20728   case X86ISD::INC:
20729   case X86ISD::DEC:
20730   case X86ISD::OR:
20731   case X86ISD::XOR:
20732   case X86ISD::AND:
20733     // These nodes' second result is a boolean.
20734     if (Op.getResNo() == 0)
20735       break;
20736     // Fallthrough
20737   case X86ISD::SETCC:
20738     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20739     break;
20740   case ISD::INTRINSIC_WO_CHAIN: {
20741     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20742     unsigned NumLoBits = 0;
20743     switch (IntId) {
20744     default: break;
20745     case Intrinsic::x86_sse_movmsk_ps:
20746     case Intrinsic::x86_avx_movmsk_ps_256:
20747     case Intrinsic::x86_sse2_movmsk_pd:
20748     case Intrinsic::x86_avx_movmsk_pd_256:
20749     case Intrinsic::x86_mmx_pmovmskb:
20750     case Intrinsic::x86_sse2_pmovmskb_128:
20751     case Intrinsic::x86_avx2_pmovmskb: {
20752       // High bits of movmskp{s|d}, pmovmskb are known zero.
20753       switch (IntId) {
20754         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20755         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20756         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20757         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20758         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20759         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20760         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20761         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20762       }
20763       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20764       break;
20765     }
20766     }
20767     break;
20768   }
20769   }
20770 }
20771
20772 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20773   SDValue Op,
20774   const SelectionDAG &,
20775   unsigned Depth) const {
20776   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20777   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20778     return Op.getValueType().getScalarType().getSizeInBits();
20779
20780   // Fallback case.
20781   return 1;
20782 }
20783
20784 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20785 /// node is a GlobalAddress + offset.
20786 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20787                                        const GlobalValue* &GA,
20788                                        int64_t &Offset) const {
20789   if (N->getOpcode() == X86ISD::Wrapper) {
20790     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20791       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20792       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20793       return true;
20794     }
20795   }
20796   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20797 }
20798
20799 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20800 /// same as extracting the high 128-bit part of 256-bit vector and then
20801 /// inserting the result into the low part of a new 256-bit vector
20802 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20803   EVT VT = SVOp->getValueType(0);
20804   unsigned NumElems = VT.getVectorNumElements();
20805
20806   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20807   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20808     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20809         SVOp->getMaskElt(j) >= 0)
20810       return false;
20811
20812   return true;
20813 }
20814
20815 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20816 /// same as extracting the low 128-bit part of 256-bit vector and then
20817 /// inserting the result into the high part of a new 256-bit vector
20818 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20819   EVT VT = SVOp->getValueType(0);
20820   unsigned NumElems = VT.getVectorNumElements();
20821
20822   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20823   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20824     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20825         SVOp->getMaskElt(j) >= 0)
20826       return false;
20827
20828   return true;
20829 }
20830
20831 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20832 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20833                                         TargetLowering::DAGCombinerInfo &DCI,
20834                                         const X86Subtarget* Subtarget) {
20835   SDLoc dl(N);
20836   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20837   SDValue V1 = SVOp->getOperand(0);
20838   SDValue V2 = SVOp->getOperand(1);
20839   EVT VT = SVOp->getValueType(0);
20840   unsigned NumElems = VT.getVectorNumElements();
20841
20842   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20843       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20844     //
20845     //                   0,0,0,...
20846     //                      |
20847     //    V      UNDEF    BUILD_VECTOR    UNDEF
20848     //     \      /           \           /
20849     //  CONCAT_VECTOR         CONCAT_VECTOR
20850     //         \                  /
20851     //          \                /
20852     //          RESULT: V + zero extended
20853     //
20854     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20855         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20856         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20857       return SDValue();
20858
20859     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20860       return SDValue();
20861
20862     // To match the shuffle mask, the first half of the mask should
20863     // be exactly the first vector, and all the rest a splat with the
20864     // first element of the second one.
20865     for (unsigned i = 0; i != NumElems/2; ++i)
20866       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20867           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20868         return SDValue();
20869
20870     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20871     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20872       if (Ld->hasNUsesOfValue(1, 0)) {
20873         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20874         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20875         SDValue ResNode =
20876           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20877                                   Ld->getMemoryVT(),
20878                                   Ld->getPointerInfo(),
20879                                   Ld->getAlignment(),
20880                                   false/*isVolatile*/, true/*ReadMem*/,
20881                                   false/*WriteMem*/);
20882
20883         // Make sure the newly-created LOAD is in the same position as Ld in
20884         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20885         // and update uses of Ld's output chain to use the TokenFactor.
20886         if (Ld->hasAnyUseOfValue(1)) {
20887           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20888                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20889           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20890           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20891                                  SDValue(ResNode.getNode(), 1));
20892         }
20893
20894         return DAG.getBitcast(VT, ResNode);
20895       }
20896     }
20897
20898     // Emit a zeroed vector and insert the desired subvector on its
20899     // first half.
20900     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20901     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20902     return DCI.CombineTo(N, InsV);
20903   }
20904
20905   //===--------------------------------------------------------------------===//
20906   // Combine some shuffles into subvector extracts and inserts:
20907   //
20908
20909   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20910   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20911     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20912     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20913     return DCI.CombineTo(N, InsV);
20914   }
20915
20916   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20917   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20918     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20919     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20920     return DCI.CombineTo(N, InsV);
20921   }
20922
20923   return SDValue();
20924 }
20925
20926 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20927 /// possible.
20928 ///
20929 /// This is the leaf of the recursive combinine below. When we have found some
20930 /// chain of single-use x86 shuffle instructions and accumulated the combined
20931 /// shuffle mask represented by them, this will try to pattern match that mask
20932 /// into either a single instruction if there is a special purpose instruction
20933 /// for this operation, or into a PSHUFB instruction which is a fully general
20934 /// instruction but should only be used to replace chains over a certain depth.
20935 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20936                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20937                                    TargetLowering::DAGCombinerInfo &DCI,
20938                                    const X86Subtarget *Subtarget) {
20939   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20940
20941   // Find the operand that enters the chain. Note that multiple uses are OK
20942   // here, we're not going to remove the operand we find.
20943   SDValue Input = Op.getOperand(0);
20944   while (Input.getOpcode() == ISD::BITCAST)
20945     Input = Input.getOperand(0);
20946
20947   MVT VT = Input.getSimpleValueType();
20948   MVT RootVT = Root.getSimpleValueType();
20949   SDLoc DL(Root);
20950
20951   // Just remove no-op shuffle masks.
20952   if (Mask.size() == 1) {
20953     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20954                   /*AddTo*/ true);
20955     return true;
20956   }
20957
20958   // Use the float domain if the operand type is a floating point type.
20959   bool FloatDomain = VT.isFloatingPoint();
20960
20961   // For floating point shuffles, we don't have free copies in the shuffle
20962   // instructions or the ability to load as part of the instruction, so
20963   // canonicalize their shuffles to UNPCK or MOV variants.
20964   //
20965   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20966   // vectors because it can have a load folded into it that UNPCK cannot. This
20967   // doesn't preclude something switching to the shorter encoding post-RA.
20968   //
20969   // FIXME: Should teach these routines about AVX vector widths.
20970   if (FloatDomain && VT.getSizeInBits() == 128) {
20971     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20972       bool Lo = Mask.equals({0, 0});
20973       unsigned Shuffle;
20974       MVT ShuffleVT;
20975       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20976       // is no slower than UNPCKLPD but has the option to fold the input operand
20977       // into even an unaligned memory load.
20978       if (Lo && Subtarget->hasSSE3()) {
20979         Shuffle = X86ISD::MOVDDUP;
20980         ShuffleVT = MVT::v2f64;
20981       } else {
20982         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20983         // than the UNPCK variants.
20984         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20985         ShuffleVT = MVT::v4f32;
20986       }
20987       if (Depth == 1 && Root->getOpcode() == Shuffle)
20988         return false; // Nothing to do!
20989       Op = DAG.getBitcast(ShuffleVT, Input);
20990       DCI.AddToWorklist(Op.getNode());
20991       if (Shuffle == X86ISD::MOVDDUP)
20992         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20993       else
20994         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20995       DCI.AddToWorklist(Op.getNode());
20996       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20997                     /*AddTo*/ true);
20998       return true;
20999     }
21000     if (Subtarget->hasSSE3() &&
21001         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
21002       bool Lo = Mask.equals({0, 0, 2, 2});
21003       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
21004       MVT ShuffleVT = MVT::v4f32;
21005       if (Depth == 1 && Root->getOpcode() == Shuffle)
21006         return false; // Nothing to do!
21007       Op = DAG.getBitcast(ShuffleVT, Input);
21008       DCI.AddToWorklist(Op.getNode());
21009       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
21010       DCI.AddToWorklist(Op.getNode());
21011       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21012                     /*AddTo*/ true);
21013       return true;
21014     }
21015     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
21016       bool Lo = Mask.equals({0, 0, 1, 1});
21017       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21018       MVT ShuffleVT = MVT::v4f32;
21019       if (Depth == 1 && Root->getOpcode() == Shuffle)
21020         return false; // Nothing to do!
21021       Op = DAG.getBitcast(ShuffleVT, Input);
21022       DCI.AddToWorklist(Op.getNode());
21023       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21024       DCI.AddToWorklist(Op.getNode());
21025       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21026                     /*AddTo*/ true);
21027       return true;
21028     }
21029   }
21030
21031   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21032   // variants as none of these have single-instruction variants that are
21033   // superior to the UNPCK formulation.
21034   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21035       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21036        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21037        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21038        Mask.equals(
21039            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21040     bool Lo = Mask[0] == 0;
21041     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21042     if (Depth == 1 && Root->getOpcode() == Shuffle)
21043       return false; // Nothing to do!
21044     MVT ShuffleVT;
21045     switch (Mask.size()) {
21046     case 8:
21047       ShuffleVT = MVT::v8i16;
21048       break;
21049     case 16:
21050       ShuffleVT = MVT::v16i8;
21051       break;
21052     default:
21053       llvm_unreachable("Impossible mask size!");
21054     };
21055     Op = DAG.getBitcast(ShuffleVT, Input);
21056     DCI.AddToWorklist(Op.getNode());
21057     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21058     DCI.AddToWorklist(Op.getNode());
21059     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21060                   /*AddTo*/ true);
21061     return true;
21062   }
21063
21064   // Don't try to re-form single instruction chains under any circumstances now
21065   // that we've done encoding canonicalization for them.
21066   if (Depth < 2)
21067     return false;
21068
21069   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21070   // can replace them with a single PSHUFB instruction profitably. Intel's
21071   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21072   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21073   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21074     SmallVector<SDValue, 16> PSHUFBMask;
21075     int NumBytes = VT.getSizeInBits() / 8;
21076     int Ratio = NumBytes / Mask.size();
21077     for (int i = 0; i < NumBytes; ++i) {
21078       if (Mask[i / Ratio] == SM_SentinelUndef) {
21079         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21080         continue;
21081       }
21082       int M = Mask[i / Ratio] != SM_SentinelZero
21083                   ? Ratio * Mask[i / Ratio] + i % Ratio
21084                   : 255;
21085       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21086     }
21087     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21088     Op = DAG.getBitcast(ByteVT, Input);
21089     DCI.AddToWorklist(Op.getNode());
21090     SDValue PSHUFBMaskOp =
21091         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21092     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21093     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21094     DCI.AddToWorklist(Op.getNode());
21095     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21096                   /*AddTo*/ true);
21097     return true;
21098   }
21099
21100   // Failed to find any combines.
21101   return false;
21102 }
21103
21104 /// \brief Fully generic combining of x86 shuffle instructions.
21105 ///
21106 /// This should be the last combine run over the x86 shuffle instructions. Once
21107 /// they have been fully optimized, this will recursively consider all chains
21108 /// of single-use shuffle instructions, build a generic model of the cumulative
21109 /// shuffle operation, and check for simpler instructions which implement this
21110 /// operation. We use this primarily for two purposes:
21111 ///
21112 /// 1) Collapse generic shuffles to specialized single instructions when
21113 ///    equivalent. In most cases, this is just an encoding size win, but
21114 ///    sometimes we will collapse multiple generic shuffles into a single
21115 ///    special-purpose shuffle.
21116 /// 2) Look for sequences of shuffle instructions with 3 or more total
21117 ///    instructions, and replace them with the slightly more expensive SSSE3
21118 ///    PSHUFB instruction if available. We do this as the last combining step
21119 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21120 ///    a suitable short sequence of other instructions. The PHUFB will either
21121 ///    use a register or have to read from memory and so is slightly (but only
21122 ///    slightly) more expensive than the other shuffle instructions.
21123 ///
21124 /// Because this is inherently a quadratic operation (for each shuffle in
21125 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21126 /// This should never be an issue in practice as the shuffle lowering doesn't
21127 /// produce sequences of more than 8 instructions.
21128 ///
21129 /// FIXME: We will currently miss some cases where the redundant shuffling
21130 /// would simplify under the threshold for PSHUFB formation because of
21131 /// combine-ordering. To fix this, we should do the redundant instruction
21132 /// combining in this recursive walk.
21133 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21134                                           ArrayRef<int> RootMask,
21135                                           int Depth, bool HasPSHUFB,
21136                                           SelectionDAG &DAG,
21137                                           TargetLowering::DAGCombinerInfo &DCI,
21138                                           const X86Subtarget *Subtarget) {
21139   // Bound the depth of our recursive combine because this is ultimately
21140   // quadratic in nature.
21141   if (Depth > 8)
21142     return false;
21143
21144   // Directly rip through bitcasts to find the underlying operand.
21145   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21146     Op = Op.getOperand(0);
21147
21148   MVT VT = Op.getSimpleValueType();
21149   if (!VT.isVector())
21150     return false; // Bail if we hit a non-vector.
21151
21152   assert(Root.getSimpleValueType().isVector() &&
21153          "Shuffles operate on vector types!");
21154   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21155          "Can only combine shuffles of the same vector register size.");
21156
21157   if (!isTargetShuffle(Op.getOpcode()))
21158     return false;
21159   SmallVector<int, 16> OpMask;
21160   bool IsUnary;
21161   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21162   // We only can combine unary shuffles which we can decode the mask for.
21163   if (!HaveMask || !IsUnary)
21164     return false;
21165
21166   assert(VT.getVectorNumElements() == OpMask.size() &&
21167          "Different mask size from vector size!");
21168   assert(((RootMask.size() > OpMask.size() &&
21169            RootMask.size() % OpMask.size() == 0) ||
21170           (OpMask.size() > RootMask.size() &&
21171            OpMask.size() % RootMask.size() == 0) ||
21172           OpMask.size() == RootMask.size()) &&
21173          "The smaller number of elements must divide the larger.");
21174   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21175   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21176   assert(((RootRatio == 1 && OpRatio == 1) ||
21177           (RootRatio == 1) != (OpRatio == 1)) &&
21178          "Must not have a ratio for both incoming and op masks!");
21179
21180   SmallVector<int, 16> Mask;
21181   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21182
21183   // Merge this shuffle operation's mask into our accumulated mask. Note that
21184   // this shuffle's mask will be the first applied to the input, followed by the
21185   // root mask to get us all the way to the root value arrangement. The reason
21186   // for this order is that we are recursing up the operation chain.
21187   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21188     int RootIdx = i / RootRatio;
21189     if (RootMask[RootIdx] < 0) {
21190       // This is a zero or undef lane, we're done.
21191       Mask.push_back(RootMask[RootIdx]);
21192       continue;
21193     }
21194
21195     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21196     int OpIdx = RootMaskedIdx / OpRatio;
21197     if (OpMask[OpIdx] < 0) {
21198       // The incoming lanes are zero or undef, it doesn't matter which ones we
21199       // are using.
21200       Mask.push_back(OpMask[OpIdx]);
21201       continue;
21202     }
21203
21204     // Ok, we have non-zero lanes, map them through.
21205     Mask.push_back(OpMask[OpIdx] * OpRatio +
21206                    RootMaskedIdx % OpRatio);
21207   }
21208
21209   // See if we can recurse into the operand to combine more things.
21210   switch (Op.getOpcode()) {
21211     case X86ISD::PSHUFB:
21212       HasPSHUFB = true;
21213     case X86ISD::PSHUFD:
21214     case X86ISD::PSHUFHW:
21215     case X86ISD::PSHUFLW:
21216       if (Op.getOperand(0).hasOneUse() &&
21217           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21218                                         HasPSHUFB, DAG, DCI, Subtarget))
21219         return true;
21220       break;
21221
21222     case X86ISD::UNPCKL:
21223     case X86ISD::UNPCKH:
21224       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21225       // We can't check for single use, we have to check that this shuffle is the only user.
21226       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21227           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21228                                         HasPSHUFB, DAG, DCI, Subtarget))
21229           return true;
21230       break;
21231   }
21232
21233   // Minor canonicalization of the accumulated shuffle mask to make it easier
21234   // to match below. All this does is detect masks with squential pairs of
21235   // elements, and shrink them to the half-width mask. It does this in a loop
21236   // so it will reduce the size of the mask to the minimal width mask which
21237   // performs an equivalent shuffle.
21238   SmallVector<int, 16> WidenedMask;
21239   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21240     Mask = std::move(WidenedMask);
21241     WidenedMask.clear();
21242   }
21243
21244   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21245                                 Subtarget);
21246 }
21247
21248 /// \brief Get the PSHUF-style mask from PSHUF node.
21249 ///
21250 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21251 /// PSHUF-style masks that can be reused with such instructions.
21252 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21253   MVT VT = N.getSimpleValueType();
21254   SmallVector<int, 4> Mask;
21255   bool IsUnary;
21256   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21257   (void)HaveMask;
21258   assert(HaveMask);
21259
21260   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21261   // matter. Check that the upper masks are repeats and remove them.
21262   if (VT.getSizeInBits() > 128) {
21263     int LaneElts = 128 / VT.getScalarSizeInBits();
21264 #ifndef NDEBUG
21265     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21266       for (int j = 0; j < LaneElts; ++j)
21267         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21268                "Mask doesn't repeat in high 128-bit lanes!");
21269 #endif
21270     Mask.resize(LaneElts);
21271   }
21272
21273   switch (N.getOpcode()) {
21274   case X86ISD::PSHUFD:
21275     return Mask;
21276   case X86ISD::PSHUFLW:
21277     Mask.resize(4);
21278     return Mask;
21279   case X86ISD::PSHUFHW:
21280     Mask.erase(Mask.begin(), Mask.begin() + 4);
21281     for (int &M : Mask)
21282       M -= 4;
21283     return Mask;
21284   default:
21285     llvm_unreachable("No valid shuffle instruction found!");
21286   }
21287 }
21288
21289 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21290 ///
21291 /// We walk up the chain and look for a combinable shuffle, skipping over
21292 /// shuffles that we could hoist this shuffle's transformation past without
21293 /// altering anything.
21294 static SDValue
21295 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21296                              SelectionDAG &DAG,
21297                              TargetLowering::DAGCombinerInfo &DCI) {
21298   assert(N.getOpcode() == X86ISD::PSHUFD &&
21299          "Called with something other than an x86 128-bit half shuffle!");
21300   SDLoc DL(N);
21301
21302   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21303   // of the shuffles in the chain so that we can form a fresh chain to replace
21304   // this one.
21305   SmallVector<SDValue, 8> Chain;
21306   SDValue V = N.getOperand(0);
21307   for (; V.hasOneUse(); V = V.getOperand(0)) {
21308     switch (V.getOpcode()) {
21309     default:
21310       return SDValue(); // Nothing combined!
21311
21312     case ISD::BITCAST:
21313       // Skip bitcasts as we always know the type for the target specific
21314       // instructions.
21315       continue;
21316
21317     case X86ISD::PSHUFD:
21318       // Found another dword shuffle.
21319       break;
21320
21321     case X86ISD::PSHUFLW:
21322       // Check that the low words (being shuffled) are the identity in the
21323       // dword shuffle, and the high words are self-contained.
21324       if (Mask[0] != 0 || Mask[1] != 1 ||
21325           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21326         return SDValue();
21327
21328       Chain.push_back(V);
21329       continue;
21330
21331     case X86ISD::PSHUFHW:
21332       // Check that the high words (being shuffled) are the identity in the
21333       // dword shuffle, and the low words are self-contained.
21334       if (Mask[2] != 2 || Mask[3] != 3 ||
21335           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21336         return SDValue();
21337
21338       Chain.push_back(V);
21339       continue;
21340
21341     case X86ISD::UNPCKL:
21342     case X86ISD::UNPCKH:
21343       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21344       // shuffle into a preceding word shuffle.
21345       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21346           V.getSimpleValueType().getScalarType() != MVT::i16)
21347         return SDValue();
21348
21349       // Search for a half-shuffle which we can combine with.
21350       unsigned CombineOp =
21351           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21352       if (V.getOperand(0) != V.getOperand(1) ||
21353           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21354         return SDValue();
21355       Chain.push_back(V);
21356       V = V.getOperand(0);
21357       do {
21358         switch (V.getOpcode()) {
21359         default:
21360           return SDValue(); // Nothing to combine.
21361
21362         case X86ISD::PSHUFLW:
21363         case X86ISD::PSHUFHW:
21364           if (V.getOpcode() == CombineOp)
21365             break;
21366
21367           Chain.push_back(V);
21368
21369           // Fallthrough!
21370         case ISD::BITCAST:
21371           V = V.getOperand(0);
21372           continue;
21373         }
21374         break;
21375       } while (V.hasOneUse());
21376       break;
21377     }
21378     // Break out of the loop if we break out of the switch.
21379     break;
21380   }
21381
21382   if (!V.hasOneUse())
21383     // We fell out of the loop without finding a viable combining instruction.
21384     return SDValue();
21385
21386   // Merge this node's mask and our incoming mask.
21387   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21388   for (int &M : Mask)
21389     M = VMask[M];
21390   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21391                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21392
21393   // Rebuild the chain around this new shuffle.
21394   while (!Chain.empty()) {
21395     SDValue W = Chain.pop_back_val();
21396
21397     if (V.getValueType() != W.getOperand(0).getValueType())
21398       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21399
21400     switch (W.getOpcode()) {
21401     default:
21402       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21403
21404     case X86ISD::UNPCKL:
21405     case X86ISD::UNPCKH:
21406       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21407       break;
21408
21409     case X86ISD::PSHUFD:
21410     case X86ISD::PSHUFLW:
21411     case X86ISD::PSHUFHW:
21412       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21413       break;
21414     }
21415   }
21416   if (V.getValueType() != N.getValueType())
21417     V = DAG.getBitcast(N.getValueType(), V);
21418
21419   // Return the new chain to replace N.
21420   return V;
21421 }
21422
21423 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21424 ///
21425 /// We walk up the chain, skipping shuffles of the other half and looking
21426 /// through shuffles which switch halves trying to find a shuffle of the same
21427 /// pair of dwords.
21428 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21429                                         SelectionDAG &DAG,
21430                                         TargetLowering::DAGCombinerInfo &DCI) {
21431   assert(
21432       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21433       "Called with something other than an x86 128-bit half shuffle!");
21434   SDLoc DL(N);
21435   unsigned CombineOpcode = N.getOpcode();
21436
21437   // Walk up a single-use chain looking for a combinable shuffle.
21438   SDValue V = N.getOperand(0);
21439   for (; V.hasOneUse(); V = V.getOperand(0)) {
21440     switch (V.getOpcode()) {
21441     default:
21442       return false; // Nothing combined!
21443
21444     case ISD::BITCAST:
21445       // Skip bitcasts as we always know the type for the target specific
21446       // instructions.
21447       continue;
21448
21449     case X86ISD::PSHUFLW:
21450     case X86ISD::PSHUFHW:
21451       if (V.getOpcode() == CombineOpcode)
21452         break;
21453
21454       // Other-half shuffles are no-ops.
21455       continue;
21456     }
21457     // Break out of the loop if we break out of the switch.
21458     break;
21459   }
21460
21461   if (!V.hasOneUse())
21462     // We fell out of the loop without finding a viable combining instruction.
21463     return false;
21464
21465   // Combine away the bottom node as its shuffle will be accumulated into
21466   // a preceding shuffle.
21467   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21468
21469   // Record the old value.
21470   SDValue Old = V;
21471
21472   // Merge this node's mask and our incoming mask (adjusted to account for all
21473   // the pshufd instructions encountered).
21474   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21475   for (int &M : Mask)
21476     M = VMask[M];
21477   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21478                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21479
21480   // Check that the shuffles didn't cancel each other out. If not, we need to
21481   // combine to the new one.
21482   if (Old != V)
21483     // Replace the combinable shuffle with the combined one, updating all users
21484     // so that we re-evaluate the chain here.
21485     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21486
21487   return true;
21488 }
21489
21490 /// \brief Try to combine x86 target specific shuffles.
21491 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21492                                            TargetLowering::DAGCombinerInfo &DCI,
21493                                            const X86Subtarget *Subtarget) {
21494   SDLoc DL(N);
21495   MVT VT = N.getSimpleValueType();
21496   SmallVector<int, 4> Mask;
21497
21498   switch (N.getOpcode()) {
21499   case X86ISD::PSHUFD:
21500   case X86ISD::PSHUFLW:
21501   case X86ISD::PSHUFHW:
21502     Mask = getPSHUFShuffleMask(N);
21503     assert(Mask.size() == 4);
21504     break;
21505   default:
21506     return SDValue();
21507   }
21508
21509   // Nuke no-op shuffles that show up after combining.
21510   if (isNoopShuffleMask(Mask))
21511     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21512
21513   // Look for simplifications involving one or two shuffle instructions.
21514   SDValue V = N.getOperand(0);
21515   switch (N.getOpcode()) {
21516   default:
21517     break;
21518   case X86ISD::PSHUFLW:
21519   case X86ISD::PSHUFHW:
21520     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21521
21522     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21523       return SDValue(); // We combined away this shuffle, so we're done.
21524
21525     // See if this reduces to a PSHUFD which is no more expensive and can
21526     // combine with more operations. Note that it has to at least flip the
21527     // dwords as otherwise it would have been removed as a no-op.
21528     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21529       int DMask[] = {0, 1, 2, 3};
21530       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21531       DMask[DOffset + 0] = DOffset + 1;
21532       DMask[DOffset + 1] = DOffset + 0;
21533       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21534       V = DAG.getBitcast(DVT, V);
21535       DCI.AddToWorklist(V.getNode());
21536       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21537                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21538       DCI.AddToWorklist(V.getNode());
21539       return DAG.getBitcast(VT, V);
21540     }
21541
21542     // Look for shuffle patterns which can be implemented as a single unpack.
21543     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21544     // only works when we have a PSHUFD followed by two half-shuffles.
21545     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21546         (V.getOpcode() == X86ISD::PSHUFLW ||
21547          V.getOpcode() == X86ISD::PSHUFHW) &&
21548         V.getOpcode() != N.getOpcode() &&
21549         V.hasOneUse()) {
21550       SDValue D = V.getOperand(0);
21551       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21552         D = D.getOperand(0);
21553       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21554         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21555         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21556         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21557         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21558         int WordMask[8];
21559         for (int i = 0; i < 4; ++i) {
21560           WordMask[i + NOffset] = Mask[i] + NOffset;
21561           WordMask[i + VOffset] = VMask[i] + VOffset;
21562         }
21563         // Map the word mask through the DWord mask.
21564         int MappedMask[8];
21565         for (int i = 0; i < 8; ++i)
21566           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21567         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21568             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21569           // We can replace all three shuffles with an unpack.
21570           V = DAG.getBitcast(VT, D.getOperand(0));
21571           DCI.AddToWorklist(V.getNode());
21572           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21573                                                 : X86ISD::UNPCKH,
21574                              DL, VT, V, V);
21575         }
21576       }
21577     }
21578
21579     break;
21580
21581   case X86ISD::PSHUFD:
21582     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21583       return NewN;
21584
21585     break;
21586   }
21587
21588   return SDValue();
21589 }
21590
21591 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21592 ///
21593 /// We combine this directly on the abstract vector shuffle nodes so it is
21594 /// easier to generically match. We also insert dummy vector shuffle nodes for
21595 /// the operands which explicitly discard the lanes which are unused by this
21596 /// operation to try to flow through the rest of the combiner the fact that
21597 /// they're unused.
21598 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21599   SDLoc DL(N);
21600   EVT VT = N->getValueType(0);
21601
21602   // We only handle target-independent shuffles.
21603   // FIXME: It would be easy and harmless to use the target shuffle mask
21604   // extraction tool to support more.
21605   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21606     return SDValue();
21607
21608   auto *SVN = cast<ShuffleVectorSDNode>(N);
21609   ArrayRef<int> Mask = SVN->getMask();
21610   SDValue V1 = N->getOperand(0);
21611   SDValue V2 = N->getOperand(1);
21612
21613   // We require the first shuffle operand to be the SUB node, and the second to
21614   // be the ADD node.
21615   // FIXME: We should support the commuted patterns.
21616   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21617     return SDValue();
21618
21619   // If there are other uses of these operations we can't fold them.
21620   if (!V1->hasOneUse() || !V2->hasOneUse())
21621     return SDValue();
21622
21623   // Ensure that both operations have the same operands. Note that we can
21624   // commute the FADD operands.
21625   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21626   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21627       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21628     return SDValue();
21629
21630   // We're looking for blends between FADD and FSUB nodes. We insist on these
21631   // nodes being lined up in a specific expected pattern.
21632   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21633         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21634         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21635     return SDValue();
21636
21637   // Only specific types are legal at this point, assert so we notice if and
21638   // when these change.
21639   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21640           VT == MVT::v4f64) &&
21641          "Unknown vector type encountered!");
21642
21643   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21644 }
21645
21646 /// PerformShuffleCombine - Performs several different shuffle combines.
21647 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21648                                      TargetLowering::DAGCombinerInfo &DCI,
21649                                      const X86Subtarget *Subtarget) {
21650   SDLoc dl(N);
21651   SDValue N0 = N->getOperand(0);
21652   SDValue N1 = N->getOperand(1);
21653   EVT VT = N->getValueType(0);
21654
21655   // Don't create instructions with illegal types after legalize types has run.
21656   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21657   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21658     return SDValue();
21659
21660   // If we have legalized the vector types, look for blends of FADD and FSUB
21661   // nodes that we can fuse into an ADDSUB node.
21662   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21663     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21664       return AddSub;
21665
21666   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21667   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21668       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21669     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21670
21671   // During Type Legalization, when promoting illegal vector types,
21672   // the backend might introduce new shuffle dag nodes and bitcasts.
21673   //
21674   // This code performs the following transformation:
21675   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21676   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21677   //
21678   // We do this only if both the bitcast and the BINOP dag nodes have
21679   // one use. Also, perform this transformation only if the new binary
21680   // operation is legal. This is to avoid introducing dag nodes that
21681   // potentially need to be further expanded (or custom lowered) into a
21682   // less optimal sequence of dag nodes.
21683   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21684       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21685       N0.getOpcode() == ISD::BITCAST) {
21686     SDValue BC0 = N0.getOperand(0);
21687     EVT SVT = BC0.getValueType();
21688     unsigned Opcode = BC0.getOpcode();
21689     unsigned NumElts = VT.getVectorNumElements();
21690
21691     if (BC0.hasOneUse() && SVT.isVector() &&
21692         SVT.getVectorNumElements() * 2 == NumElts &&
21693         TLI.isOperationLegal(Opcode, VT)) {
21694       bool CanFold = false;
21695       switch (Opcode) {
21696       default : break;
21697       case ISD::ADD :
21698       case ISD::FADD :
21699       case ISD::SUB :
21700       case ISD::FSUB :
21701       case ISD::MUL :
21702       case ISD::FMUL :
21703         CanFold = true;
21704       }
21705
21706       unsigned SVTNumElts = SVT.getVectorNumElements();
21707       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21708       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21709         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21710       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21711         CanFold = SVOp->getMaskElt(i) < 0;
21712
21713       if (CanFold) {
21714         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21715         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21716         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21717         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21718       }
21719     }
21720   }
21721
21722   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21723   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21724   // consecutive, non-overlapping, and in the right order.
21725   SmallVector<SDValue, 16> Elts;
21726   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21727     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21728
21729   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21730     return LD;
21731
21732   if (isTargetShuffle(N->getOpcode())) {
21733     SDValue Shuffle =
21734         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21735     if (Shuffle.getNode())
21736       return Shuffle;
21737
21738     // Try recursively combining arbitrary sequences of x86 shuffle
21739     // instructions into higher-order shuffles. We do this after combining
21740     // specific PSHUF instruction sequences into their minimal form so that we
21741     // can evaluate how many specialized shuffle instructions are involved in
21742     // a particular chain.
21743     SmallVector<int, 1> NonceMask; // Just a placeholder.
21744     NonceMask.push_back(0);
21745     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21746                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21747                                       DCI, Subtarget))
21748       return SDValue(); // This routine will use CombineTo to replace N.
21749   }
21750
21751   return SDValue();
21752 }
21753
21754 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21755 /// specific shuffle of a load can be folded into a single element load.
21756 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21757 /// shuffles have been custom lowered so we need to handle those here.
21758 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21759                                          TargetLowering::DAGCombinerInfo &DCI) {
21760   if (DCI.isBeforeLegalizeOps())
21761     return SDValue();
21762
21763   SDValue InVec = N->getOperand(0);
21764   SDValue EltNo = N->getOperand(1);
21765
21766   if (!isa<ConstantSDNode>(EltNo))
21767     return SDValue();
21768
21769   EVT OriginalVT = InVec.getValueType();
21770
21771   if (InVec.getOpcode() == ISD::BITCAST) {
21772     // Don't duplicate a load with other uses.
21773     if (!InVec.hasOneUse())
21774       return SDValue();
21775     EVT BCVT = InVec.getOperand(0).getValueType();
21776     if (!BCVT.isVector() ||
21777         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21778       return SDValue();
21779     InVec = InVec.getOperand(0);
21780   }
21781
21782   EVT CurrentVT = InVec.getValueType();
21783
21784   if (!isTargetShuffle(InVec.getOpcode()))
21785     return SDValue();
21786
21787   // Don't duplicate a load with other uses.
21788   if (!InVec.hasOneUse())
21789     return SDValue();
21790
21791   SmallVector<int, 16> ShuffleMask;
21792   bool UnaryShuffle;
21793   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21794                             ShuffleMask, UnaryShuffle))
21795     return SDValue();
21796
21797   // Select the input vector, guarding against out of range extract vector.
21798   unsigned NumElems = CurrentVT.getVectorNumElements();
21799   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21800   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21801   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21802                                          : InVec.getOperand(1);
21803
21804   // If inputs to shuffle are the same for both ops, then allow 2 uses
21805   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21806                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21807
21808   if (LdNode.getOpcode() == ISD::BITCAST) {
21809     // Don't duplicate a load with other uses.
21810     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21811       return SDValue();
21812
21813     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21814     LdNode = LdNode.getOperand(0);
21815   }
21816
21817   if (!ISD::isNormalLoad(LdNode.getNode()))
21818     return SDValue();
21819
21820   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21821
21822   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21823     return SDValue();
21824
21825   EVT EltVT = N->getValueType(0);
21826   // If there's a bitcast before the shuffle, check if the load type and
21827   // alignment is valid.
21828   unsigned Align = LN0->getAlignment();
21829   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21830   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21831       EltVT.getTypeForEVT(*DAG.getContext()));
21832
21833   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21834     return SDValue();
21835
21836   // All checks match so transform back to vector_shuffle so that DAG combiner
21837   // can finish the job
21838   SDLoc dl(N);
21839
21840   // Create shuffle node taking into account the case that its a unary shuffle
21841   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21842                                    : InVec.getOperand(1);
21843   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21844                                  InVec.getOperand(0), Shuffle,
21845                                  &ShuffleMask[0]);
21846   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21847   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21848                      EltNo);
21849 }
21850
21851 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21852 /// special and don't usually play with other vector types, it's better to
21853 /// handle them early to be sure we emit efficient code by avoiding
21854 /// store-load conversions.
21855 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21856   if (N->getValueType(0) != MVT::x86mmx ||
21857       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21858       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21859     return SDValue();
21860
21861   SDValue V = N->getOperand(0);
21862   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21863   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21864     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21865                        N->getValueType(0), V.getOperand(0));
21866
21867   return SDValue();
21868 }
21869
21870 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21871 /// generation and convert it from being a bunch of shuffles and extracts
21872 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21873 /// storing the value and loading scalars back, while for x64 we should
21874 /// use 64-bit extracts and shifts.
21875 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21876                                          TargetLowering::DAGCombinerInfo &DCI) {
21877   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21878     return NewOp;
21879
21880   SDValue InputVector = N->getOperand(0);
21881   SDLoc dl(InputVector);
21882   // Detect mmx to i32 conversion through a v2i32 elt extract.
21883   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21884       N->getValueType(0) == MVT::i32 &&
21885       InputVector.getValueType() == MVT::v2i32) {
21886
21887     // The bitcast source is a direct mmx result.
21888     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21889     if (MMXSrc.getValueType() == MVT::x86mmx)
21890       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21891                          N->getValueType(0),
21892                          InputVector.getNode()->getOperand(0));
21893
21894     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21895     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21896     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21897         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21898         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21899         MMXSrcOp.getValueType() == MVT::v1i64 &&
21900         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21901       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21902                          N->getValueType(0),
21903                          MMXSrcOp.getOperand(0));
21904   }
21905
21906   EVT VT = N->getValueType(0);
21907
21908   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21909       InputVector.getOpcode() == ISD::BITCAST &&
21910       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21911     uint64_t ExtractedElt =
21912           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21913     uint64_t InputValue =
21914           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21915     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21916     return DAG.getConstant(Res, dl, MVT::i1);
21917   }
21918   // Only operate on vectors of 4 elements, where the alternative shuffling
21919   // gets to be more expensive.
21920   if (InputVector.getValueType() != MVT::v4i32)
21921     return SDValue();
21922
21923   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21924   // single use which is a sign-extend or zero-extend, and all elements are
21925   // used.
21926   SmallVector<SDNode *, 4> Uses;
21927   unsigned ExtractedElements = 0;
21928   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21929        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21930     if (UI.getUse().getResNo() != InputVector.getResNo())
21931       return SDValue();
21932
21933     SDNode *Extract = *UI;
21934     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21935       return SDValue();
21936
21937     if (Extract->getValueType(0) != MVT::i32)
21938       return SDValue();
21939     if (!Extract->hasOneUse())
21940       return SDValue();
21941     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21942         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21943       return SDValue();
21944     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21945       return SDValue();
21946
21947     // Record which element was extracted.
21948     ExtractedElements |=
21949       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21950
21951     Uses.push_back(Extract);
21952   }
21953
21954   // If not all the elements were used, this may not be worthwhile.
21955   if (ExtractedElements != 15)
21956     return SDValue();
21957
21958   // Ok, we've now decided to do the transformation.
21959   // If 64-bit shifts are legal, use the extract-shift sequence,
21960   // otherwise bounce the vector off the cache.
21961   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21962   SDValue Vals[4];
21963
21964   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21965     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21966     auto &DL = DAG.getDataLayout();
21967     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
21968     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21969       DAG.getConstant(0, dl, VecIdxTy));
21970     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21971       DAG.getConstant(1, dl, VecIdxTy));
21972
21973     SDValue ShAmt = DAG.getConstant(
21974         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
21975     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21976     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21977       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21978     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21979     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21980       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21981   } else {
21982     // Store the value to a temporary stack slot.
21983     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21984     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21985       MachinePointerInfo(), false, false, 0);
21986
21987     EVT ElementType = InputVector.getValueType().getVectorElementType();
21988     unsigned EltSize = ElementType.getSizeInBits() / 8;
21989
21990     // Replace each use (extract) with a load of the appropriate element.
21991     for (unsigned i = 0; i < 4; ++i) {
21992       uint64_t Offset = EltSize * i;
21993       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
21994       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
21995
21996       SDValue ScalarAddr =
21997           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
21998
21999       // Load the scalar.
22000       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
22001                             ScalarAddr, MachinePointerInfo(),
22002                             false, false, false, 0);
22003
22004     }
22005   }
22006
22007   // Replace the extracts
22008   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
22009     UE = Uses.end(); UI != UE; ++UI) {
22010     SDNode *Extract = *UI;
22011
22012     SDValue Idx = Extract->getOperand(1);
22013     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
22014     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
22015   }
22016
22017   // The replacement was made in place; don't return anything.
22018   return SDValue();
22019 }
22020
22021 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
22022 static std::pair<unsigned, bool>
22023 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
22024                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22025   if (!VT.isVector())
22026     return std::make_pair(0, false);
22027
22028   bool NeedSplit = false;
22029   switch (VT.getSimpleVT().SimpleTy) {
22030   default: return std::make_pair(0, false);
22031   case MVT::v4i64:
22032   case MVT::v2i64:
22033     if (!Subtarget->hasVLX())
22034       return std::make_pair(0, false);
22035     break;
22036   case MVT::v64i8:
22037   case MVT::v32i16:
22038     if (!Subtarget->hasBWI())
22039       return std::make_pair(0, false);
22040     break;
22041   case MVT::v16i32:
22042   case MVT::v8i64:
22043     if (!Subtarget->hasAVX512())
22044       return std::make_pair(0, false);
22045     break;
22046   case MVT::v32i8:
22047   case MVT::v16i16:
22048   case MVT::v8i32:
22049     if (!Subtarget->hasAVX2())
22050       NeedSplit = true;
22051     if (!Subtarget->hasAVX())
22052       return std::make_pair(0, false);
22053     break;
22054   case MVT::v16i8:
22055   case MVT::v8i16:
22056   case MVT::v4i32:
22057     if (!Subtarget->hasSSE2())
22058       return std::make_pair(0, false);
22059   }
22060
22061   // SSE2 has only a small subset of the operations.
22062   bool hasUnsigned = Subtarget->hasSSE41() ||
22063                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22064   bool hasSigned = Subtarget->hasSSE41() ||
22065                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22066
22067   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22068
22069   unsigned Opc = 0;
22070   // Check for x CC y ? x : y.
22071   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22072       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22073     switch (CC) {
22074     default: break;
22075     case ISD::SETULT:
22076     case ISD::SETULE:
22077       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22078     case ISD::SETUGT:
22079     case ISD::SETUGE:
22080       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22081     case ISD::SETLT:
22082     case ISD::SETLE:
22083       Opc = hasSigned ? ISD::SMIN : 0; break;
22084     case ISD::SETGT:
22085     case ISD::SETGE:
22086       Opc = hasSigned ? ISD::SMAX : 0; break;
22087     }
22088   // Check for x CC y ? y : x -- a min/max with reversed arms.
22089   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22090              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22091     switch (CC) {
22092     default: break;
22093     case ISD::SETULT:
22094     case ISD::SETULE:
22095       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22096     case ISD::SETUGT:
22097     case ISD::SETUGE:
22098       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22099     case ISD::SETLT:
22100     case ISD::SETLE:
22101       Opc = hasSigned ? ISD::SMAX : 0; break;
22102     case ISD::SETGT:
22103     case ISD::SETGE:
22104       Opc = hasSigned ? ISD::SMIN : 0; break;
22105     }
22106   }
22107
22108   return std::make_pair(Opc, NeedSplit);
22109 }
22110
22111 static SDValue
22112 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22113                                       const X86Subtarget *Subtarget) {
22114   SDLoc dl(N);
22115   SDValue Cond = N->getOperand(0);
22116   SDValue LHS = N->getOperand(1);
22117   SDValue RHS = N->getOperand(2);
22118
22119   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22120     SDValue CondSrc = Cond->getOperand(0);
22121     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22122       Cond = CondSrc->getOperand(0);
22123   }
22124
22125   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22126     return SDValue();
22127
22128   // A vselect where all conditions and data are constants can be optimized into
22129   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22130   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22131       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22132     return SDValue();
22133
22134   unsigned MaskValue = 0;
22135   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22136     return SDValue();
22137
22138   MVT VT = N->getSimpleValueType(0);
22139   unsigned NumElems = VT.getVectorNumElements();
22140   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22141   for (unsigned i = 0; i < NumElems; ++i) {
22142     // Be sure we emit undef where we can.
22143     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22144       ShuffleMask[i] = -1;
22145     else
22146       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22147   }
22148
22149   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22150   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22151     return SDValue();
22152   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22153 }
22154
22155 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22156 /// nodes.
22157 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22158                                     TargetLowering::DAGCombinerInfo &DCI,
22159                                     const X86Subtarget *Subtarget) {
22160   SDLoc DL(N);
22161   SDValue Cond = N->getOperand(0);
22162   // Get the LHS/RHS of the select.
22163   SDValue LHS = N->getOperand(1);
22164   SDValue RHS = N->getOperand(2);
22165   EVT VT = LHS.getValueType();
22166   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22167
22168   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22169   // instructions match the semantics of the common C idiom x<y?x:y but not
22170   // x<=y?x:y, because of how they handle negative zero (which can be
22171   // ignored in unsafe-math mode).
22172   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22173   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22174       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22175       (Subtarget->hasSSE2() ||
22176        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22177     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22178
22179     unsigned Opcode = 0;
22180     // Check for x CC y ? x : y.
22181     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22182         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22183       switch (CC) {
22184       default: break;
22185       case ISD::SETULT:
22186         // Converting this to a min would handle NaNs incorrectly, and swapping
22187         // the operands would cause it to handle comparisons between positive
22188         // and negative zero incorrectly.
22189         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22190           if (!DAG.getTarget().Options.UnsafeFPMath &&
22191               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22192             break;
22193           std::swap(LHS, RHS);
22194         }
22195         Opcode = X86ISD::FMIN;
22196         break;
22197       case ISD::SETOLE:
22198         // Converting this to a min would handle comparisons between positive
22199         // and negative zero incorrectly.
22200         if (!DAG.getTarget().Options.UnsafeFPMath &&
22201             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22202           break;
22203         Opcode = X86ISD::FMIN;
22204         break;
22205       case ISD::SETULE:
22206         // Converting this to a min would handle both negative zeros and NaNs
22207         // incorrectly, but we can swap the operands to fix both.
22208         std::swap(LHS, RHS);
22209       case ISD::SETOLT:
22210       case ISD::SETLT:
22211       case ISD::SETLE:
22212         Opcode = X86ISD::FMIN;
22213         break;
22214
22215       case ISD::SETOGE:
22216         // Converting this to a max would handle comparisons between positive
22217         // and negative zero incorrectly.
22218         if (!DAG.getTarget().Options.UnsafeFPMath &&
22219             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22220           break;
22221         Opcode = X86ISD::FMAX;
22222         break;
22223       case ISD::SETUGT:
22224         // Converting this to a max would handle NaNs incorrectly, and swapping
22225         // the operands would cause it to handle comparisons between positive
22226         // and negative zero incorrectly.
22227         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22228           if (!DAG.getTarget().Options.UnsafeFPMath &&
22229               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22230             break;
22231           std::swap(LHS, RHS);
22232         }
22233         Opcode = X86ISD::FMAX;
22234         break;
22235       case ISD::SETUGE:
22236         // Converting this to a max would handle both negative zeros and NaNs
22237         // incorrectly, but we can swap the operands to fix both.
22238         std::swap(LHS, RHS);
22239       case ISD::SETOGT:
22240       case ISD::SETGT:
22241       case ISD::SETGE:
22242         Opcode = X86ISD::FMAX;
22243         break;
22244       }
22245     // Check for x CC y ? y : x -- a min/max with reversed arms.
22246     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22247                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22248       switch (CC) {
22249       default: break;
22250       case ISD::SETOGE:
22251         // Converting this to a min would handle comparisons between positive
22252         // and negative zero incorrectly, and swapping the operands would
22253         // cause it to handle NaNs incorrectly.
22254         if (!DAG.getTarget().Options.UnsafeFPMath &&
22255             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22256           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22257             break;
22258           std::swap(LHS, RHS);
22259         }
22260         Opcode = X86ISD::FMIN;
22261         break;
22262       case ISD::SETUGT:
22263         // Converting this to a min would handle NaNs incorrectly.
22264         if (!DAG.getTarget().Options.UnsafeFPMath &&
22265             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22266           break;
22267         Opcode = X86ISD::FMIN;
22268         break;
22269       case ISD::SETUGE:
22270         // Converting this to a min would handle both negative zeros and NaNs
22271         // incorrectly, but we can swap the operands to fix both.
22272         std::swap(LHS, RHS);
22273       case ISD::SETOGT:
22274       case ISD::SETGT:
22275       case ISD::SETGE:
22276         Opcode = X86ISD::FMIN;
22277         break;
22278
22279       case ISD::SETULT:
22280         // Converting this to a max would handle NaNs incorrectly.
22281         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22282           break;
22283         Opcode = X86ISD::FMAX;
22284         break;
22285       case ISD::SETOLE:
22286         // Converting this to a max would handle comparisons between positive
22287         // and negative zero incorrectly, and swapping the operands would
22288         // cause it to handle NaNs incorrectly.
22289         if (!DAG.getTarget().Options.UnsafeFPMath &&
22290             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22291           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22292             break;
22293           std::swap(LHS, RHS);
22294         }
22295         Opcode = X86ISD::FMAX;
22296         break;
22297       case ISD::SETULE:
22298         // Converting this to a max would handle both negative zeros and NaNs
22299         // incorrectly, but we can swap the operands to fix both.
22300         std::swap(LHS, RHS);
22301       case ISD::SETOLT:
22302       case ISD::SETLT:
22303       case ISD::SETLE:
22304         Opcode = X86ISD::FMAX;
22305         break;
22306       }
22307     }
22308
22309     if (Opcode)
22310       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22311   }
22312
22313   EVT CondVT = Cond.getValueType();
22314   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22315       CondVT.getVectorElementType() == MVT::i1) {
22316     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22317     // lowering on KNL. In this case we convert it to
22318     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22319     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22320     // Since SKX these selects have a proper lowering.
22321     EVT OpVT = LHS.getValueType();
22322     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22323         (OpVT.getVectorElementType() == MVT::i8 ||
22324          OpVT.getVectorElementType() == MVT::i16) &&
22325         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22326       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22327       DCI.AddToWorklist(Cond.getNode());
22328       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22329     }
22330   }
22331   // If this is a select between two integer constants, try to do some
22332   // optimizations.
22333   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22334     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22335       // Don't do this for crazy integer types.
22336       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22337         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22338         // so that TrueC (the true value) is larger than FalseC.
22339         bool NeedsCondInvert = false;
22340
22341         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22342             // Efficiently invertible.
22343             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22344              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22345               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22346           NeedsCondInvert = true;
22347           std::swap(TrueC, FalseC);
22348         }
22349
22350         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22351         if (FalseC->getAPIntValue() == 0 &&
22352             TrueC->getAPIntValue().isPowerOf2()) {
22353           if (NeedsCondInvert) // Invert the condition if needed.
22354             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22355                                DAG.getConstant(1, DL, Cond.getValueType()));
22356
22357           // Zero extend the condition if needed.
22358           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22359
22360           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22361           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22362                              DAG.getConstant(ShAmt, DL, MVT::i8));
22363         }
22364
22365         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22366         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22367           if (NeedsCondInvert) // Invert the condition if needed.
22368             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22369                                DAG.getConstant(1, DL, Cond.getValueType()));
22370
22371           // Zero extend the condition if needed.
22372           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22373                              FalseC->getValueType(0), Cond);
22374           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22375                              SDValue(FalseC, 0));
22376         }
22377
22378         // Optimize cases that will turn into an LEA instruction.  This requires
22379         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22380         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22381           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22382           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22383
22384           bool isFastMultiplier = false;
22385           if (Diff < 10) {
22386             switch ((unsigned char)Diff) {
22387               default: break;
22388               case 1:  // result = add base, cond
22389               case 2:  // result = lea base(    , cond*2)
22390               case 3:  // result = lea base(cond, cond*2)
22391               case 4:  // result = lea base(    , cond*4)
22392               case 5:  // result = lea base(cond, cond*4)
22393               case 8:  // result = lea base(    , cond*8)
22394               case 9:  // result = lea base(cond, cond*8)
22395                 isFastMultiplier = true;
22396                 break;
22397             }
22398           }
22399
22400           if (isFastMultiplier) {
22401             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22402             if (NeedsCondInvert) // Invert the condition if needed.
22403               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22404                                  DAG.getConstant(1, DL, Cond.getValueType()));
22405
22406             // Zero extend the condition if needed.
22407             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22408                                Cond);
22409             // Scale the condition by the difference.
22410             if (Diff != 1)
22411               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22412                                  DAG.getConstant(Diff, DL,
22413                                                  Cond.getValueType()));
22414
22415             // Add the base if non-zero.
22416             if (FalseC->getAPIntValue() != 0)
22417               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22418                                  SDValue(FalseC, 0));
22419             return Cond;
22420           }
22421         }
22422       }
22423   }
22424
22425   // Canonicalize max and min:
22426   // (x > y) ? x : y -> (x >= y) ? x : y
22427   // (x < y) ? x : y -> (x <= y) ? x : y
22428   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22429   // the need for an extra compare
22430   // against zero. e.g.
22431   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22432   // subl   %esi, %edi
22433   // testl  %edi, %edi
22434   // movl   $0, %eax
22435   // cmovgl %edi, %eax
22436   // =>
22437   // xorl   %eax, %eax
22438   // subl   %esi, $edi
22439   // cmovsl %eax, %edi
22440   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22441       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22442       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22443     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22444     switch (CC) {
22445     default: break;
22446     case ISD::SETLT:
22447     case ISD::SETGT: {
22448       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22449       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22450                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22451       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22452     }
22453     }
22454   }
22455
22456   // Early exit check
22457   if (!TLI.isTypeLegal(VT))
22458     return SDValue();
22459
22460   // Match VSELECTs into subs with unsigned saturation.
22461   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22462       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22463       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22464        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22465     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22466
22467     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22468     // left side invert the predicate to simplify logic below.
22469     SDValue Other;
22470     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22471       Other = RHS;
22472       CC = ISD::getSetCCInverse(CC, true);
22473     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22474       Other = LHS;
22475     }
22476
22477     if (Other.getNode() && Other->getNumOperands() == 2 &&
22478         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22479       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22480       SDValue CondRHS = Cond->getOperand(1);
22481
22482       // Look for a general sub with unsigned saturation first.
22483       // x >= y ? x-y : 0 --> subus x, y
22484       // x >  y ? x-y : 0 --> subus x, y
22485       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22486           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22487         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22488
22489       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22490         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22491           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22492             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22493               // If the RHS is a constant we have to reverse the const
22494               // canonicalization.
22495               // x > C-1 ? x+-C : 0 --> subus x, C
22496               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22497                   CondRHSConst->getAPIntValue() ==
22498                       (-OpRHSConst->getAPIntValue() - 1))
22499                 return DAG.getNode(
22500                     X86ISD::SUBUS, DL, VT, OpLHS,
22501                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22502
22503           // Another special case: If C was a sign bit, the sub has been
22504           // canonicalized into a xor.
22505           // FIXME: Would it be better to use computeKnownBits to determine
22506           //        whether it's safe to decanonicalize the xor?
22507           // x s< 0 ? x^C : 0 --> subus x, C
22508           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22509               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22510               OpRHSConst->getAPIntValue().isSignBit())
22511             // Note that we have to rebuild the RHS constant here to ensure we
22512             // don't rely on particular values of undef lanes.
22513             return DAG.getNode(
22514                 X86ISD::SUBUS, DL, VT, OpLHS,
22515                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22516         }
22517     }
22518   }
22519
22520   // Try to match a min/max vector operation.
22521   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22522     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22523     unsigned Opc = ret.first;
22524     bool NeedSplit = ret.second;
22525
22526     if (Opc && NeedSplit) {
22527       unsigned NumElems = VT.getVectorNumElements();
22528       // Extract the LHS vectors
22529       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22530       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22531
22532       // Extract the RHS vectors
22533       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22534       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22535
22536       // Create min/max for each subvector
22537       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22538       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22539
22540       // Merge the result
22541       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22542     } else if (Opc)
22543       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22544   }
22545
22546   // Simplify vector selection if condition value type matches vselect
22547   // operand type
22548   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22549     assert(Cond.getValueType().isVector() &&
22550            "vector select expects a vector selector!");
22551
22552     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22553     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22554
22555     // Try invert the condition if true value is not all 1s and false value
22556     // is not all 0s.
22557     if (!TValIsAllOnes && !FValIsAllZeros &&
22558         // Check if the selector will be produced by CMPP*/PCMP*
22559         Cond.getOpcode() == ISD::SETCC &&
22560         // Check if SETCC has already been promoted
22561         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22562             CondVT) {
22563       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22564       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22565
22566       if (TValIsAllZeros || FValIsAllOnes) {
22567         SDValue CC = Cond.getOperand(2);
22568         ISD::CondCode NewCC =
22569           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22570                                Cond.getOperand(0).getValueType().isInteger());
22571         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22572         std::swap(LHS, RHS);
22573         TValIsAllOnes = FValIsAllOnes;
22574         FValIsAllZeros = TValIsAllZeros;
22575       }
22576     }
22577
22578     if (TValIsAllOnes || FValIsAllZeros) {
22579       SDValue Ret;
22580
22581       if (TValIsAllOnes && FValIsAllZeros)
22582         Ret = Cond;
22583       else if (TValIsAllOnes)
22584         Ret =
22585             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22586       else if (FValIsAllZeros)
22587         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22588                           DAG.getBitcast(CondVT, LHS));
22589
22590       return DAG.getBitcast(VT, Ret);
22591     }
22592   }
22593
22594   // We should generate an X86ISD::BLENDI from a vselect if its argument
22595   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22596   // constants. This specific pattern gets generated when we split a
22597   // selector for a 512 bit vector in a machine without AVX512 (but with
22598   // 256-bit vectors), during legalization:
22599   //
22600   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22601   //
22602   // Iff we find this pattern and the build_vectors are built from
22603   // constants, we translate the vselect into a shuffle_vector that we
22604   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22605   if ((N->getOpcode() == ISD::VSELECT ||
22606        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22607       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22608     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22609     if (Shuffle.getNode())
22610       return Shuffle;
22611   }
22612
22613   // If this is a *dynamic* select (non-constant condition) and we can match
22614   // this node with one of the variable blend instructions, restructure the
22615   // condition so that the blends can use the high bit of each element and use
22616   // SimplifyDemandedBits to simplify the condition operand.
22617   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22618       !DCI.isBeforeLegalize() &&
22619       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22620     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22621
22622     // Don't optimize vector selects that map to mask-registers.
22623     if (BitWidth == 1)
22624       return SDValue();
22625
22626     // We can only handle the cases where VSELECT is directly legal on the
22627     // subtarget. We custom lower VSELECT nodes with constant conditions and
22628     // this makes it hard to see whether a dynamic VSELECT will correctly
22629     // lower, so we both check the operation's status and explicitly handle the
22630     // cases where a *dynamic* blend will fail even though a constant-condition
22631     // blend could be custom lowered.
22632     // FIXME: We should find a better way to handle this class of problems.
22633     // Potentially, we should combine constant-condition vselect nodes
22634     // pre-legalization into shuffles and not mark as many types as custom
22635     // lowered.
22636     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22637       return SDValue();
22638     // FIXME: We don't support i16-element blends currently. We could and
22639     // should support them by making *all* the bits in the condition be set
22640     // rather than just the high bit and using an i8-element blend.
22641     if (VT.getScalarType() == MVT::i16)
22642       return SDValue();
22643     // Dynamic blending was only available from SSE4.1 onward.
22644     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22645       return SDValue();
22646     // Byte blends are only available in AVX2
22647     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22648         !Subtarget->hasAVX2())
22649       return SDValue();
22650
22651     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22652     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22653
22654     APInt KnownZero, KnownOne;
22655     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22656                                           DCI.isBeforeLegalizeOps());
22657     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22658         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22659                                  TLO)) {
22660       // If we changed the computation somewhere in the DAG, this change
22661       // will affect all users of Cond.
22662       // Make sure it is fine and update all the nodes so that we do not
22663       // use the generic VSELECT anymore. Otherwise, we may perform
22664       // wrong optimizations as we messed up with the actual expectation
22665       // for the vector boolean values.
22666       if (Cond != TLO.Old) {
22667         // Check all uses of that condition operand to check whether it will be
22668         // consumed by non-BLEND instructions, which may depend on all bits are
22669         // set properly.
22670         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22671              I != E; ++I)
22672           if (I->getOpcode() != ISD::VSELECT)
22673             // TODO: Add other opcodes eventually lowered into BLEND.
22674             return SDValue();
22675
22676         // Update all the users of the condition, before committing the change,
22677         // so that the VSELECT optimizations that expect the correct vector
22678         // boolean value will not be triggered.
22679         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22680              I != E; ++I)
22681           DAG.ReplaceAllUsesOfValueWith(
22682               SDValue(*I, 0),
22683               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22684                           Cond, I->getOperand(1), I->getOperand(2)));
22685         DCI.CommitTargetLoweringOpt(TLO);
22686         return SDValue();
22687       }
22688       // At this point, only Cond is changed. Change the condition
22689       // just for N to keep the opportunity to optimize all other
22690       // users their own way.
22691       DAG.ReplaceAllUsesOfValueWith(
22692           SDValue(N, 0),
22693           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22694                       TLO.New, N->getOperand(1), N->getOperand(2)));
22695       return SDValue();
22696     }
22697   }
22698
22699   return SDValue();
22700 }
22701
22702 // Check whether a boolean test is testing a boolean value generated by
22703 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22704 // code.
22705 //
22706 // Simplify the following patterns:
22707 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22708 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22709 // to (Op EFLAGS Cond)
22710 //
22711 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22712 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22713 // to (Op EFLAGS !Cond)
22714 //
22715 // where Op could be BRCOND or CMOV.
22716 //
22717 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22718   // Quit if not CMP and SUB with its value result used.
22719   if (Cmp.getOpcode() != X86ISD::CMP &&
22720       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22721       return SDValue();
22722
22723   // Quit if not used as a boolean value.
22724   if (CC != X86::COND_E && CC != X86::COND_NE)
22725     return SDValue();
22726
22727   // Check CMP operands. One of them should be 0 or 1 and the other should be
22728   // an SetCC or extended from it.
22729   SDValue Op1 = Cmp.getOperand(0);
22730   SDValue Op2 = Cmp.getOperand(1);
22731
22732   SDValue SetCC;
22733   const ConstantSDNode* C = nullptr;
22734   bool needOppositeCond = (CC == X86::COND_E);
22735   bool checkAgainstTrue = false; // Is it a comparison against 1?
22736
22737   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22738     SetCC = Op2;
22739   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22740     SetCC = Op1;
22741   else // Quit if all operands are not constants.
22742     return SDValue();
22743
22744   if (C->getZExtValue() == 1) {
22745     needOppositeCond = !needOppositeCond;
22746     checkAgainstTrue = true;
22747   } else if (C->getZExtValue() != 0)
22748     // Quit if the constant is neither 0 or 1.
22749     return SDValue();
22750
22751   bool truncatedToBoolWithAnd = false;
22752   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22753   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22754          SetCC.getOpcode() == ISD::TRUNCATE ||
22755          SetCC.getOpcode() == ISD::AND) {
22756     if (SetCC.getOpcode() == ISD::AND) {
22757       int OpIdx = -1;
22758       ConstantSDNode *CS;
22759       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22760           CS->getZExtValue() == 1)
22761         OpIdx = 1;
22762       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22763           CS->getZExtValue() == 1)
22764         OpIdx = 0;
22765       if (OpIdx == -1)
22766         break;
22767       SetCC = SetCC.getOperand(OpIdx);
22768       truncatedToBoolWithAnd = true;
22769     } else
22770       SetCC = SetCC.getOperand(0);
22771   }
22772
22773   switch (SetCC.getOpcode()) {
22774   case X86ISD::SETCC_CARRY:
22775     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22776     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22777     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22778     // truncated to i1 using 'and'.
22779     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22780       break;
22781     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22782            "Invalid use of SETCC_CARRY!");
22783     // FALL THROUGH
22784   case X86ISD::SETCC:
22785     // Set the condition code or opposite one if necessary.
22786     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22787     if (needOppositeCond)
22788       CC = X86::GetOppositeBranchCondition(CC);
22789     return SetCC.getOperand(1);
22790   case X86ISD::CMOV: {
22791     // Check whether false/true value has canonical one, i.e. 0 or 1.
22792     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22793     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22794     // Quit if true value is not a constant.
22795     if (!TVal)
22796       return SDValue();
22797     // Quit if false value is not a constant.
22798     if (!FVal) {
22799       SDValue Op = SetCC.getOperand(0);
22800       // Skip 'zext' or 'trunc' node.
22801       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22802           Op.getOpcode() == ISD::TRUNCATE)
22803         Op = Op.getOperand(0);
22804       // A special case for rdrand/rdseed, where 0 is set if false cond is
22805       // found.
22806       if ((Op.getOpcode() != X86ISD::RDRAND &&
22807            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22808         return SDValue();
22809     }
22810     // Quit if false value is not the constant 0 or 1.
22811     bool FValIsFalse = true;
22812     if (FVal && FVal->getZExtValue() != 0) {
22813       if (FVal->getZExtValue() != 1)
22814         return SDValue();
22815       // If FVal is 1, opposite cond is needed.
22816       needOppositeCond = !needOppositeCond;
22817       FValIsFalse = false;
22818     }
22819     // Quit if TVal is not the constant opposite of FVal.
22820     if (FValIsFalse && TVal->getZExtValue() != 1)
22821       return SDValue();
22822     if (!FValIsFalse && TVal->getZExtValue() != 0)
22823       return SDValue();
22824     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22825     if (needOppositeCond)
22826       CC = X86::GetOppositeBranchCondition(CC);
22827     return SetCC.getOperand(3);
22828   }
22829   }
22830
22831   return SDValue();
22832 }
22833
22834 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22835 /// Match:
22836 ///   (X86or (X86setcc) (X86setcc))
22837 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22838 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22839                                            X86::CondCode &CC1, SDValue &Flags,
22840                                            bool &isAnd) {
22841   if (Cond->getOpcode() == X86ISD::CMP) {
22842     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22843     if (!CondOp1C || !CondOp1C->isNullValue())
22844       return false;
22845
22846     Cond = Cond->getOperand(0);
22847   }
22848
22849   isAnd = false;
22850
22851   SDValue SetCC0, SetCC1;
22852   switch (Cond->getOpcode()) {
22853   default: return false;
22854   case ISD::AND:
22855   case X86ISD::AND:
22856     isAnd = true;
22857     // fallthru
22858   case ISD::OR:
22859   case X86ISD::OR:
22860     SetCC0 = Cond->getOperand(0);
22861     SetCC1 = Cond->getOperand(1);
22862     break;
22863   };
22864
22865   // Make sure we have SETCC nodes, using the same flags value.
22866   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22867       SetCC1.getOpcode() != X86ISD::SETCC ||
22868       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22869     return false;
22870
22871   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22872   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22873   Flags = SetCC0->getOperand(1);
22874   return true;
22875 }
22876
22877 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22878 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22879                                   TargetLowering::DAGCombinerInfo &DCI,
22880                                   const X86Subtarget *Subtarget) {
22881   SDLoc DL(N);
22882
22883   // If the flag operand isn't dead, don't touch this CMOV.
22884   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22885     return SDValue();
22886
22887   SDValue FalseOp = N->getOperand(0);
22888   SDValue TrueOp = N->getOperand(1);
22889   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22890   SDValue Cond = N->getOperand(3);
22891
22892   if (CC == X86::COND_E || CC == X86::COND_NE) {
22893     switch (Cond.getOpcode()) {
22894     default: break;
22895     case X86ISD::BSR:
22896     case X86ISD::BSF:
22897       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22898       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22899         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22900     }
22901   }
22902
22903   SDValue Flags;
22904
22905   Flags = checkBoolTestSetCCCombine(Cond, CC);
22906   if (Flags.getNode() &&
22907       // Extra check as FCMOV only supports a subset of X86 cond.
22908       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22909     SDValue Ops[] = { FalseOp, TrueOp,
22910                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22911     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22912   }
22913
22914   // If this is a select between two integer constants, try to do some
22915   // optimizations.  Note that the operands are ordered the opposite of SELECT
22916   // operands.
22917   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22918     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22919       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22920       // larger than FalseC (the false value).
22921       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22922         CC = X86::GetOppositeBranchCondition(CC);
22923         std::swap(TrueC, FalseC);
22924         std::swap(TrueOp, FalseOp);
22925       }
22926
22927       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22928       // This is efficient for any integer data type (including i8/i16) and
22929       // shift amount.
22930       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22931         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22932                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22933
22934         // Zero extend the condition if needed.
22935         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22936
22937         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22938         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22939                            DAG.getConstant(ShAmt, DL, MVT::i8));
22940         if (N->getNumValues() == 2)  // Dead flag value?
22941           return DCI.CombineTo(N, Cond, SDValue());
22942         return Cond;
22943       }
22944
22945       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22946       // for any integer data type, including i8/i16.
22947       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22948         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22949                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22950
22951         // Zero extend the condition if needed.
22952         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22953                            FalseC->getValueType(0), Cond);
22954         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22955                            SDValue(FalseC, 0));
22956
22957         if (N->getNumValues() == 2)  // Dead flag value?
22958           return DCI.CombineTo(N, Cond, SDValue());
22959         return Cond;
22960       }
22961
22962       // Optimize cases that will turn into an LEA instruction.  This requires
22963       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22964       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22965         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22966         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22967
22968         bool isFastMultiplier = false;
22969         if (Diff < 10) {
22970           switch ((unsigned char)Diff) {
22971           default: break;
22972           case 1:  // result = add base, cond
22973           case 2:  // result = lea base(    , cond*2)
22974           case 3:  // result = lea base(cond, cond*2)
22975           case 4:  // result = lea base(    , cond*4)
22976           case 5:  // result = lea base(cond, cond*4)
22977           case 8:  // result = lea base(    , cond*8)
22978           case 9:  // result = lea base(cond, cond*8)
22979             isFastMultiplier = true;
22980             break;
22981           }
22982         }
22983
22984         if (isFastMultiplier) {
22985           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22986           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22987                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22988           // Zero extend the condition if needed.
22989           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22990                              Cond);
22991           // Scale the condition by the difference.
22992           if (Diff != 1)
22993             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22994                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22995
22996           // Add the base if non-zero.
22997           if (FalseC->getAPIntValue() != 0)
22998             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22999                                SDValue(FalseC, 0));
23000           if (N->getNumValues() == 2)  // Dead flag value?
23001             return DCI.CombineTo(N, Cond, SDValue());
23002           return Cond;
23003         }
23004       }
23005     }
23006   }
23007
23008   // Handle these cases:
23009   //   (select (x != c), e, c) -> select (x != c), e, x),
23010   //   (select (x == c), c, e) -> select (x == c), x, e)
23011   // where the c is an integer constant, and the "select" is the combination
23012   // of CMOV and CMP.
23013   //
23014   // The rationale for this change is that the conditional-move from a constant
23015   // needs two instructions, however, conditional-move from a register needs
23016   // only one instruction.
23017   //
23018   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
23019   //  some instruction-combining opportunities. This opt needs to be
23020   //  postponed as late as possible.
23021   //
23022   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
23023     // the DCI.xxxx conditions are provided to postpone the optimization as
23024     // late as possible.
23025
23026     ConstantSDNode *CmpAgainst = nullptr;
23027     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23028         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23029         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23030
23031       if (CC == X86::COND_NE &&
23032           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23033         CC = X86::GetOppositeBranchCondition(CC);
23034         std::swap(TrueOp, FalseOp);
23035       }
23036
23037       if (CC == X86::COND_E &&
23038           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23039         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23040                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23041         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23042       }
23043     }
23044   }
23045
23046   // Fold and/or of setcc's to double CMOV:
23047   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23048   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23049   //
23050   // This combine lets us generate:
23051   //   cmovcc1 (jcc1 if we don't have CMOV)
23052   //   cmovcc2 (same)
23053   // instead of:
23054   //   setcc1
23055   //   setcc2
23056   //   and/or
23057   //   cmovne (jne if we don't have CMOV)
23058   // When we can't use the CMOV instruction, it might increase branch
23059   // mispredicts.
23060   // When we can use CMOV, or when there is no mispredict, this improves
23061   // throughput and reduces register pressure.
23062   //
23063   if (CC == X86::COND_NE) {
23064     SDValue Flags;
23065     X86::CondCode CC0, CC1;
23066     bool isAndSetCC;
23067     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23068       if (isAndSetCC) {
23069         std::swap(FalseOp, TrueOp);
23070         CC0 = X86::GetOppositeBranchCondition(CC0);
23071         CC1 = X86::GetOppositeBranchCondition(CC1);
23072       }
23073
23074       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23075         Flags};
23076       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23077       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23078       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23079       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23080       return CMOV;
23081     }
23082   }
23083
23084   return SDValue();
23085 }
23086
23087 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23088                                                 const X86Subtarget *Subtarget) {
23089   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23090   switch (IntNo) {
23091   default: return SDValue();
23092   // SSE/AVX/AVX2 blend intrinsics.
23093   case Intrinsic::x86_avx2_pblendvb:
23094     // Don't try to simplify this intrinsic if we don't have AVX2.
23095     if (!Subtarget->hasAVX2())
23096       return SDValue();
23097     // FALL-THROUGH
23098   case Intrinsic::x86_avx_blendv_pd_256:
23099   case Intrinsic::x86_avx_blendv_ps_256:
23100     // Don't try to simplify this intrinsic if we don't have AVX.
23101     if (!Subtarget->hasAVX())
23102       return SDValue();
23103     // FALL-THROUGH
23104   case Intrinsic::x86_sse41_blendvps:
23105   case Intrinsic::x86_sse41_blendvpd:
23106   case Intrinsic::x86_sse41_pblendvb: {
23107     SDValue Op0 = N->getOperand(1);
23108     SDValue Op1 = N->getOperand(2);
23109     SDValue Mask = N->getOperand(3);
23110
23111     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23112     if (!Subtarget->hasSSE41())
23113       return SDValue();
23114
23115     // fold (blend A, A, Mask) -> A
23116     if (Op0 == Op1)
23117       return Op0;
23118     // fold (blend A, B, allZeros) -> A
23119     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23120       return Op0;
23121     // fold (blend A, B, allOnes) -> B
23122     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23123       return Op1;
23124
23125     // Simplify the case where the mask is a constant i32 value.
23126     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23127       if (C->isNullValue())
23128         return Op0;
23129       if (C->isAllOnesValue())
23130         return Op1;
23131     }
23132
23133     return SDValue();
23134   }
23135
23136   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23137   case Intrinsic::x86_sse2_psrai_w:
23138   case Intrinsic::x86_sse2_psrai_d:
23139   case Intrinsic::x86_avx2_psrai_w:
23140   case Intrinsic::x86_avx2_psrai_d:
23141   case Intrinsic::x86_sse2_psra_w:
23142   case Intrinsic::x86_sse2_psra_d:
23143   case Intrinsic::x86_avx2_psra_w:
23144   case Intrinsic::x86_avx2_psra_d: {
23145     SDValue Op0 = N->getOperand(1);
23146     SDValue Op1 = N->getOperand(2);
23147     EVT VT = Op0.getValueType();
23148     assert(VT.isVector() && "Expected a vector type!");
23149
23150     if (isa<BuildVectorSDNode>(Op1))
23151       Op1 = Op1.getOperand(0);
23152
23153     if (!isa<ConstantSDNode>(Op1))
23154       return SDValue();
23155
23156     EVT SVT = VT.getVectorElementType();
23157     unsigned SVTBits = SVT.getSizeInBits();
23158
23159     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23160     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23161     uint64_t ShAmt = C.getZExtValue();
23162
23163     // Don't try to convert this shift into a ISD::SRA if the shift
23164     // count is bigger than or equal to the element size.
23165     if (ShAmt >= SVTBits)
23166       return SDValue();
23167
23168     // Trivial case: if the shift count is zero, then fold this
23169     // into the first operand.
23170     if (ShAmt == 0)
23171       return Op0;
23172
23173     // Replace this packed shift intrinsic with a target independent
23174     // shift dag node.
23175     SDLoc DL(N);
23176     SDValue Splat = DAG.getConstant(C, DL, VT);
23177     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23178   }
23179   }
23180 }
23181
23182 /// PerformMulCombine - Optimize a single multiply with constant into two
23183 /// in order to implement it with two cheaper instructions, e.g.
23184 /// LEA + SHL, LEA + LEA.
23185 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23186                                  TargetLowering::DAGCombinerInfo &DCI) {
23187   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23188     return SDValue();
23189
23190   EVT VT = N->getValueType(0);
23191   if (VT != MVT::i64 && VT != MVT::i32)
23192     return SDValue();
23193
23194   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23195   if (!C)
23196     return SDValue();
23197   uint64_t MulAmt = C->getZExtValue();
23198   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23199     return SDValue();
23200
23201   uint64_t MulAmt1 = 0;
23202   uint64_t MulAmt2 = 0;
23203   if ((MulAmt % 9) == 0) {
23204     MulAmt1 = 9;
23205     MulAmt2 = MulAmt / 9;
23206   } else if ((MulAmt % 5) == 0) {
23207     MulAmt1 = 5;
23208     MulAmt2 = MulAmt / 5;
23209   } else if ((MulAmt % 3) == 0) {
23210     MulAmt1 = 3;
23211     MulAmt2 = MulAmt / 3;
23212   }
23213   if (MulAmt2 &&
23214       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23215     SDLoc DL(N);
23216
23217     if (isPowerOf2_64(MulAmt2) &&
23218         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23219       // If second multiplifer is pow2, issue it first. We want the multiply by
23220       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23221       // is an add.
23222       std::swap(MulAmt1, MulAmt2);
23223
23224     SDValue NewMul;
23225     if (isPowerOf2_64(MulAmt1))
23226       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23227                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23228     else
23229       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23230                            DAG.getConstant(MulAmt1, DL, VT));
23231
23232     if (isPowerOf2_64(MulAmt2))
23233       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23234                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23235     else
23236       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23237                            DAG.getConstant(MulAmt2, DL, VT));
23238
23239     // Do not add new nodes to DAG combiner worklist.
23240     DCI.CombineTo(N, NewMul, false);
23241   }
23242   return SDValue();
23243 }
23244
23245 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23246   SDValue N0 = N->getOperand(0);
23247   SDValue N1 = N->getOperand(1);
23248   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23249   EVT VT = N0.getValueType();
23250
23251   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23252   // since the result of setcc_c is all zero's or all ones.
23253   if (VT.isInteger() && !VT.isVector() &&
23254       N1C && N0.getOpcode() == ISD::AND &&
23255       N0.getOperand(1).getOpcode() == ISD::Constant) {
23256     SDValue N00 = N0.getOperand(0);
23257     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23258         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23259           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23260          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23261       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23262       APInt ShAmt = N1C->getAPIntValue();
23263       Mask = Mask.shl(ShAmt);
23264       if (Mask != 0) {
23265         SDLoc DL(N);
23266         return DAG.getNode(ISD::AND, DL, VT,
23267                            N00, DAG.getConstant(Mask, DL, VT));
23268       }
23269     }
23270   }
23271
23272   // Hardware support for vector shifts is sparse which makes us scalarize the
23273   // vector operations in many cases. Also, on sandybridge ADD is faster than
23274   // shl.
23275   // (shl V, 1) -> add V,V
23276   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23277     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23278       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23279       // We shift all of the values by one. In many cases we do not have
23280       // hardware support for this operation. This is better expressed as an ADD
23281       // of two values.
23282       if (N1SplatC->getAPIntValue() == 1)
23283         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23284     }
23285
23286   return SDValue();
23287 }
23288
23289 /// \brief Returns a vector of 0s if the node in input is a vector logical
23290 /// shift by a constant amount which is known to be bigger than or equal
23291 /// to the vector element size in bits.
23292 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23293                                       const X86Subtarget *Subtarget) {
23294   EVT VT = N->getValueType(0);
23295
23296   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23297       (!Subtarget->hasInt256() ||
23298        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23299     return SDValue();
23300
23301   SDValue Amt = N->getOperand(1);
23302   SDLoc DL(N);
23303   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23304     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23305       APInt ShiftAmt = AmtSplat->getAPIntValue();
23306       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23307
23308       // SSE2/AVX2 logical shifts always return a vector of 0s
23309       // if the shift amount is bigger than or equal to
23310       // the element size. The constant shift amount will be
23311       // encoded as a 8-bit immediate.
23312       if (ShiftAmt.trunc(8).uge(MaxAmount))
23313         return getZeroVector(VT, Subtarget, DAG, DL);
23314     }
23315
23316   return SDValue();
23317 }
23318
23319 /// PerformShiftCombine - Combine shifts.
23320 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23321                                    TargetLowering::DAGCombinerInfo &DCI,
23322                                    const X86Subtarget *Subtarget) {
23323   if (N->getOpcode() == ISD::SHL)
23324     if (SDValue V = PerformSHLCombine(N, DAG))
23325       return V;
23326
23327   // Try to fold this logical shift into a zero vector.
23328   if (N->getOpcode() != ISD::SRA)
23329     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23330       return V;
23331
23332   return SDValue();
23333 }
23334
23335 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23336 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23337 // and friends.  Likewise for OR -> CMPNEQSS.
23338 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23339                             TargetLowering::DAGCombinerInfo &DCI,
23340                             const X86Subtarget *Subtarget) {
23341   unsigned opcode;
23342
23343   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23344   // we're requiring SSE2 for both.
23345   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23346     SDValue N0 = N->getOperand(0);
23347     SDValue N1 = N->getOperand(1);
23348     SDValue CMP0 = N0->getOperand(1);
23349     SDValue CMP1 = N1->getOperand(1);
23350     SDLoc DL(N);
23351
23352     // The SETCCs should both refer to the same CMP.
23353     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23354       return SDValue();
23355
23356     SDValue CMP00 = CMP0->getOperand(0);
23357     SDValue CMP01 = CMP0->getOperand(1);
23358     EVT     VT    = CMP00.getValueType();
23359
23360     if (VT == MVT::f32 || VT == MVT::f64) {
23361       bool ExpectingFlags = false;
23362       // Check for any users that want flags:
23363       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23364            !ExpectingFlags && UI != UE; ++UI)
23365         switch (UI->getOpcode()) {
23366         default:
23367         case ISD::BR_CC:
23368         case ISD::BRCOND:
23369         case ISD::SELECT:
23370           ExpectingFlags = true;
23371           break;
23372         case ISD::CopyToReg:
23373         case ISD::SIGN_EXTEND:
23374         case ISD::ZERO_EXTEND:
23375         case ISD::ANY_EXTEND:
23376           break;
23377         }
23378
23379       if (!ExpectingFlags) {
23380         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23381         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23382
23383         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23384           X86::CondCode tmp = cc0;
23385           cc0 = cc1;
23386           cc1 = tmp;
23387         }
23388
23389         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23390             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23391           // FIXME: need symbolic constants for these magic numbers.
23392           // See X86ATTInstPrinter.cpp:printSSECC().
23393           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23394           if (Subtarget->hasAVX512()) {
23395             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23396                                          CMP01,
23397                                          DAG.getConstant(x86cc, DL, MVT::i8));
23398             if (N->getValueType(0) != MVT::i1)
23399               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23400                                  FSetCC);
23401             return FSetCC;
23402           }
23403           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23404                                               CMP00.getValueType(), CMP00, CMP01,
23405                                               DAG.getConstant(x86cc, DL,
23406                                                               MVT::i8));
23407
23408           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23409           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23410
23411           if (is64BitFP && !Subtarget->is64Bit()) {
23412             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23413             // 64-bit integer, since that's not a legal type. Since
23414             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23415             // bits, but can do this little dance to extract the lowest 32 bits
23416             // and work with those going forward.
23417             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23418                                            OnesOrZeroesF);
23419             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23420             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23421                                         Vector32, DAG.getIntPtrConstant(0, DL));
23422             IntVT = MVT::i32;
23423           }
23424
23425           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23426           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23427                                       DAG.getConstant(1, DL, IntVT));
23428           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23429                                               ANDed);
23430           return OneBitOfTruth;
23431         }
23432       }
23433     }
23434   }
23435   return SDValue();
23436 }
23437
23438 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23439 /// so it can be folded inside ANDNP.
23440 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23441   EVT VT = N->getValueType(0);
23442
23443   // Match direct AllOnes for 128 and 256-bit vectors
23444   if (ISD::isBuildVectorAllOnes(N))
23445     return true;
23446
23447   // Look through a bit convert.
23448   if (N->getOpcode() == ISD::BITCAST)
23449     N = N->getOperand(0).getNode();
23450
23451   // Sometimes the operand may come from a insert_subvector building a 256-bit
23452   // allones vector
23453   if (VT.is256BitVector() &&
23454       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23455     SDValue V1 = N->getOperand(0);
23456     SDValue V2 = N->getOperand(1);
23457
23458     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23459         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23460         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23461         ISD::isBuildVectorAllOnes(V2.getNode()))
23462       return true;
23463   }
23464
23465   return false;
23466 }
23467
23468 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23469 // register. In most cases we actually compare or select YMM-sized registers
23470 // and mixing the two types creates horrible code. This method optimizes
23471 // some of the transition sequences.
23472 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23473                                  TargetLowering::DAGCombinerInfo &DCI,
23474                                  const X86Subtarget *Subtarget) {
23475   EVT VT = N->getValueType(0);
23476   if (!VT.is256BitVector())
23477     return SDValue();
23478
23479   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23480           N->getOpcode() == ISD::ZERO_EXTEND ||
23481           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23482
23483   SDValue Narrow = N->getOperand(0);
23484   EVT NarrowVT = Narrow->getValueType(0);
23485   if (!NarrowVT.is128BitVector())
23486     return SDValue();
23487
23488   if (Narrow->getOpcode() != ISD::XOR &&
23489       Narrow->getOpcode() != ISD::AND &&
23490       Narrow->getOpcode() != ISD::OR)
23491     return SDValue();
23492
23493   SDValue N0  = Narrow->getOperand(0);
23494   SDValue N1  = Narrow->getOperand(1);
23495   SDLoc DL(Narrow);
23496
23497   // The Left side has to be a trunc.
23498   if (N0.getOpcode() != ISD::TRUNCATE)
23499     return SDValue();
23500
23501   // The type of the truncated inputs.
23502   EVT WideVT = N0->getOperand(0)->getValueType(0);
23503   if (WideVT != VT)
23504     return SDValue();
23505
23506   // The right side has to be a 'trunc' or a constant vector.
23507   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23508   ConstantSDNode *RHSConstSplat = nullptr;
23509   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23510     RHSConstSplat = RHSBV->getConstantSplatNode();
23511   if (!RHSTrunc && !RHSConstSplat)
23512     return SDValue();
23513
23514   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23515
23516   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23517     return SDValue();
23518
23519   // Set N0 and N1 to hold the inputs to the new wide operation.
23520   N0 = N0->getOperand(0);
23521   if (RHSConstSplat) {
23522     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23523                      SDValue(RHSConstSplat, 0));
23524     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23525     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23526   } else if (RHSTrunc) {
23527     N1 = N1->getOperand(0);
23528   }
23529
23530   // Generate the wide operation.
23531   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23532   unsigned Opcode = N->getOpcode();
23533   switch (Opcode) {
23534   case ISD::ANY_EXTEND:
23535     return Op;
23536   case ISD::ZERO_EXTEND: {
23537     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23538     APInt Mask = APInt::getAllOnesValue(InBits);
23539     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23540     return DAG.getNode(ISD::AND, DL, VT,
23541                        Op, DAG.getConstant(Mask, DL, VT));
23542   }
23543   case ISD::SIGN_EXTEND:
23544     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23545                        Op, DAG.getValueType(NarrowVT));
23546   default:
23547     llvm_unreachable("Unexpected opcode");
23548   }
23549 }
23550
23551 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23552                                  TargetLowering::DAGCombinerInfo &DCI,
23553                                  const X86Subtarget *Subtarget) {
23554   SDValue N0 = N->getOperand(0);
23555   SDValue N1 = N->getOperand(1);
23556   SDLoc DL(N);
23557
23558   // A vector zext_in_reg may be represented as a shuffle,
23559   // feeding into a bitcast (this represents anyext) feeding into
23560   // an and with a mask.
23561   // We'd like to try to combine that into a shuffle with zero
23562   // plus a bitcast, removing the and.
23563   if (N0.getOpcode() != ISD::BITCAST ||
23564       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23565     return SDValue();
23566
23567   // The other side of the AND should be a splat of 2^C, where C
23568   // is the number of bits in the source type.
23569   if (N1.getOpcode() == ISD::BITCAST)
23570     N1 = N1.getOperand(0);
23571   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23572     return SDValue();
23573   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23574
23575   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23576   EVT SrcType = Shuffle->getValueType(0);
23577
23578   // We expect a single-source shuffle
23579   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23580     return SDValue();
23581
23582   unsigned SrcSize = SrcType.getScalarSizeInBits();
23583
23584   APInt SplatValue, SplatUndef;
23585   unsigned SplatBitSize;
23586   bool HasAnyUndefs;
23587   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23588                                 SplatBitSize, HasAnyUndefs))
23589     return SDValue();
23590
23591   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23592   // Make sure the splat matches the mask we expect
23593   if (SplatBitSize > ResSize ||
23594       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23595     return SDValue();
23596
23597   // Make sure the input and output size make sense
23598   if (SrcSize >= ResSize || ResSize % SrcSize)
23599     return SDValue();
23600
23601   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23602   // The number of u's between each two values depends on the ratio between
23603   // the source and dest type.
23604   unsigned ZextRatio = ResSize / SrcSize;
23605   bool IsZext = true;
23606   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23607     if (i % ZextRatio) {
23608       if (Shuffle->getMaskElt(i) > 0) {
23609         // Expected undef
23610         IsZext = false;
23611         break;
23612       }
23613     } else {
23614       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23615         // Expected element number
23616         IsZext = false;
23617         break;
23618       }
23619     }
23620   }
23621
23622   if (!IsZext)
23623     return SDValue();
23624
23625   // Ok, perform the transformation - replace the shuffle with
23626   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23627   // (instead of undef) where the k elements come from the zero vector.
23628   SmallVector<int, 8> Mask;
23629   unsigned NumElems = SrcType.getVectorNumElements();
23630   for (unsigned i = 0; i < NumElems; ++i)
23631     if (i % ZextRatio)
23632       Mask.push_back(NumElems);
23633     else
23634       Mask.push_back(i / ZextRatio);
23635
23636   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23637     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23638   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23639 }
23640
23641 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23642                                  TargetLowering::DAGCombinerInfo &DCI,
23643                                  const X86Subtarget *Subtarget) {
23644   if (DCI.isBeforeLegalizeOps())
23645     return SDValue();
23646
23647   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23648     return Zext;
23649
23650   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23651     return R;
23652
23653   EVT VT = N->getValueType(0);
23654   SDValue N0 = N->getOperand(0);
23655   SDValue N1 = N->getOperand(1);
23656   SDLoc DL(N);
23657
23658   // Create BEXTR instructions
23659   // BEXTR is ((X >> imm) & (2**size-1))
23660   if (VT == MVT::i32 || VT == MVT::i64) {
23661     // Check for BEXTR.
23662     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23663         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23664       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23665       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23666       if (MaskNode && ShiftNode) {
23667         uint64_t Mask = MaskNode->getZExtValue();
23668         uint64_t Shift = ShiftNode->getZExtValue();
23669         if (isMask_64(Mask)) {
23670           uint64_t MaskSize = countPopulation(Mask);
23671           if (Shift + MaskSize <= VT.getSizeInBits())
23672             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23673                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23674                                                VT));
23675         }
23676       }
23677     } // BEXTR
23678
23679     return SDValue();
23680   }
23681
23682   // Want to form ANDNP nodes:
23683   // 1) In the hopes of then easily combining them with OR and AND nodes
23684   //    to form PBLEND/PSIGN.
23685   // 2) To match ANDN packed intrinsics
23686   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23687     return SDValue();
23688
23689   // Check LHS for vnot
23690   if (N0.getOpcode() == ISD::XOR &&
23691       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23692       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23693     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23694
23695   // Check RHS for vnot
23696   if (N1.getOpcode() == ISD::XOR &&
23697       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23698       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23699     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23700
23701   return SDValue();
23702 }
23703
23704 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23705                                 TargetLowering::DAGCombinerInfo &DCI,
23706                                 const X86Subtarget *Subtarget) {
23707   if (DCI.isBeforeLegalizeOps())
23708     return SDValue();
23709
23710   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23711     return R;
23712
23713   SDValue N0 = N->getOperand(0);
23714   SDValue N1 = N->getOperand(1);
23715   EVT VT = N->getValueType(0);
23716
23717   // look for psign/blend
23718   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23719     if (!Subtarget->hasSSSE3() ||
23720         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23721       return SDValue();
23722
23723     // Canonicalize pandn to RHS
23724     if (N0.getOpcode() == X86ISD::ANDNP)
23725       std::swap(N0, N1);
23726     // or (and (m, y), (pandn m, x))
23727     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23728       SDValue Mask = N1.getOperand(0);
23729       SDValue X    = N1.getOperand(1);
23730       SDValue Y;
23731       if (N0.getOperand(0) == Mask)
23732         Y = N0.getOperand(1);
23733       if (N0.getOperand(1) == Mask)
23734         Y = N0.getOperand(0);
23735
23736       // Check to see if the mask appeared in both the AND and ANDNP and
23737       if (!Y.getNode())
23738         return SDValue();
23739
23740       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23741       // Look through mask bitcast.
23742       if (Mask.getOpcode() == ISD::BITCAST)
23743         Mask = Mask.getOperand(0);
23744       if (X.getOpcode() == ISD::BITCAST)
23745         X = X.getOperand(0);
23746       if (Y.getOpcode() == ISD::BITCAST)
23747         Y = Y.getOperand(0);
23748
23749       EVT MaskVT = Mask.getValueType();
23750
23751       // Validate that the Mask operand is a vector sra node.
23752       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23753       // there is no psrai.b
23754       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23755       unsigned SraAmt = ~0;
23756       if (Mask.getOpcode() == ISD::SRA) {
23757         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23758           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23759             SraAmt = AmtConst->getZExtValue();
23760       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23761         SDValue SraC = Mask.getOperand(1);
23762         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23763       }
23764       if ((SraAmt + 1) != EltBits)
23765         return SDValue();
23766
23767       SDLoc DL(N);
23768
23769       // Now we know we at least have a plendvb with the mask val.  See if
23770       // we can form a psignb/w/d.
23771       // psign = x.type == y.type == mask.type && y = sub(0, x);
23772       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23773           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23774           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23775         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23776                "Unsupported VT for PSIGN");
23777         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23778         return DAG.getBitcast(VT, Mask);
23779       }
23780       // PBLENDVB only available on SSE 4.1
23781       if (!Subtarget->hasSSE41())
23782         return SDValue();
23783
23784       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23785
23786       X = DAG.getBitcast(BlendVT, X);
23787       Y = DAG.getBitcast(BlendVT, Y);
23788       Mask = DAG.getBitcast(BlendVT, Mask);
23789       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23790       return DAG.getBitcast(VT, Mask);
23791     }
23792   }
23793
23794   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23795     return SDValue();
23796
23797   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23798   MachineFunction &MF = DAG.getMachineFunction();
23799   bool OptForSize =
23800       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23801
23802   // SHLD/SHRD instructions have lower register pressure, but on some
23803   // platforms they have higher latency than the equivalent
23804   // series of shifts/or that would otherwise be generated.
23805   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23806   // have higher latencies and we are not optimizing for size.
23807   if (!OptForSize && Subtarget->isSHLDSlow())
23808     return SDValue();
23809
23810   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23811     std::swap(N0, N1);
23812   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23813     return SDValue();
23814   if (!N0.hasOneUse() || !N1.hasOneUse())
23815     return SDValue();
23816
23817   SDValue ShAmt0 = N0.getOperand(1);
23818   if (ShAmt0.getValueType() != MVT::i8)
23819     return SDValue();
23820   SDValue ShAmt1 = N1.getOperand(1);
23821   if (ShAmt1.getValueType() != MVT::i8)
23822     return SDValue();
23823   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23824     ShAmt0 = ShAmt0.getOperand(0);
23825   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23826     ShAmt1 = ShAmt1.getOperand(0);
23827
23828   SDLoc DL(N);
23829   unsigned Opc = X86ISD::SHLD;
23830   SDValue Op0 = N0.getOperand(0);
23831   SDValue Op1 = N1.getOperand(0);
23832   if (ShAmt0.getOpcode() == ISD::SUB) {
23833     Opc = X86ISD::SHRD;
23834     std::swap(Op0, Op1);
23835     std::swap(ShAmt0, ShAmt1);
23836   }
23837
23838   unsigned Bits = VT.getSizeInBits();
23839   if (ShAmt1.getOpcode() == ISD::SUB) {
23840     SDValue Sum = ShAmt1.getOperand(0);
23841     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23842       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23843       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23844         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23845       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23846         return DAG.getNode(Opc, DL, VT,
23847                            Op0, Op1,
23848                            DAG.getNode(ISD::TRUNCATE, DL,
23849                                        MVT::i8, ShAmt0));
23850     }
23851   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23852     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23853     if (ShAmt0C &&
23854         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23855       return DAG.getNode(Opc, DL, VT,
23856                          N0.getOperand(0), N1.getOperand(0),
23857                          DAG.getNode(ISD::TRUNCATE, DL,
23858                                        MVT::i8, ShAmt0));
23859   }
23860
23861   return SDValue();
23862 }
23863
23864 // Generate NEG and CMOV for integer abs.
23865 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23866   EVT VT = N->getValueType(0);
23867
23868   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23869   // 8-bit integer abs to NEG and CMOV.
23870   if (VT.isInteger() && VT.getSizeInBits() == 8)
23871     return SDValue();
23872
23873   SDValue N0 = N->getOperand(0);
23874   SDValue N1 = N->getOperand(1);
23875   SDLoc DL(N);
23876
23877   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23878   // and change it to SUB and CMOV.
23879   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23880       N0.getOpcode() == ISD::ADD &&
23881       N0.getOperand(1) == N1 &&
23882       N1.getOpcode() == ISD::SRA &&
23883       N1.getOperand(0) == N0.getOperand(0))
23884     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23885       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23886         // Generate SUB & CMOV.
23887         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23888                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23889
23890         SDValue Ops[] = { N0.getOperand(0), Neg,
23891                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23892                           SDValue(Neg.getNode(), 1) };
23893         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23894       }
23895   return SDValue();
23896 }
23897
23898 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23899 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23900                                  TargetLowering::DAGCombinerInfo &DCI,
23901                                  const X86Subtarget *Subtarget) {
23902   if (DCI.isBeforeLegalizeOps())
23903     return SDValue();
23904
23905   if (Subtarget->hasCMov())
23906     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23907       return RV;
23908
23909   return SDValue();
23910 }
23911
23912 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23913 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23914                                   TargetLowering::DAGCombinerInfo &DCI,
23915                                   const X86Subtarget *Subtarget) {
23916   LoadSDNode *Ld = cast<LoadSDNode>(N);
23917   EVT RegVT = Ld->getValueType(0);
23918   EVT MemVT = Ld->getMemoryVT();
23919   SDLoc dl(Ld);
23920   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23921
23922   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23923   // into two 16-byte operations.
23924   ISD::LoadExtType Ext = Ld->getExtensionType();
23925   unsigned Alignment = Ld->getAlignment();
23926   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23927   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23928       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23929     unsigned NumElems = RegVT.getVectorNumElements();
23930     if (NumElems < 2)
23931       return SDValue();
23932
23933     SDValue Ptr = Ld->getBasePtr();
23934     SDValue Increment =
23935         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23936
23937     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23938                                   NumElems/2);
23939     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23940                                 Ld->getPointerInfo(), Ld->isVolatile(),
23941                                 Ld->isNonTemporal(), Ld->isInvariant(),
23942                                 Alignment);
23943     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23944     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23945                                 Ld->getPointerInfo(), Ld->isVolatile(),
23946                                 Ld->isNonTemporal(), Ld->isInvariant(),
23947                                 std::min(16U, Alignment));
23948     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23949                              Load1.getValue(1),
23950                              Load2.getValue(1));
23951
23952     SDValue NewVec = DAG.getUNDEF(RegVT);
23953     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23954     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23955     return DCI.CombineTo(N, NewVec, TF, true);
23956   }
23957
23958   return SDValue();
23959 }
23960
23961 /// PerformMLOADCombine - Resolve extending loads
23962 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23963                                    TargetLowering::DAGCombinerInfo &DCI,
23964                                    const X86Subtarget *Subtarget) {
23965   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23966   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23967     return SDValue();
23968
23969   EVT VT = Mld->getValueType(0);
23970   unsigned NumElems = VT.getVectorNumElements();
23971   EVT LdVT = Mld->getMemoryVT();
23972   SDLoc dl(Mld);
23973
23974   assert(LdVT != VT && "Cannot extend to the same type");
23975   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23976   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23977   // From, To sizes and ElemCount must be pow of two
23978   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23979     "Unexpected size for extending masked load");
23980
23981   unsigned SizeRatio  = ToSz / FromSz;
23982   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23983
23984   // Create a type on which we perform the shuffle
23985   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23986           LdVT.getScalarType(), NumElems*SizeRatio);
23987   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23988
23989   // Convert Src0 value
23990   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23991   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23992     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23993     for (unsigned i = 0; i != NumElems; ++i)
23994       ShuffleVec[i] = i * SizeRatio;
23995
23996     // Can't shuffle using an illegal type.
23997     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23998             && "WideVecVT should be legal");
23999     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
24000                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
24001   }
24002   // Prepare the new mask
24003   SDValue NewMask;
24004   SDValue Mask = Mld->getMask();
24005   if (Mask.getValueType() == VT) {
24006     // Mask and original value have the same type
24007     NewMask = DAG.getBitcast(WideVecVT, Mask);
24008     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24009     for (unsigned i = 0; i != NumElems; ++i)
24010       ShuffleVec[i] = i * SizeRatio;
24011     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24012       ShuffleVec[i] = NumElems*SizeRatio;
24013     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24014                                    DAG.getConstant(0, dl, WideVecVT),
24015                                    &ShuffleVec[0]);
24016   }
24017   else {
24018     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24019     unsigned WidenNumElts = NumElems*SizeRatio;
24020     unsigned MaskNumElts = VT.getVectorNumElements();
24021     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24022                                      WidenNumElts);
24023
24024     unsigned NumConcat = WidenNumElts / MaskNumElts;
24025     SmallVector<SDValue, 16> Ops(NumConcat);
24026     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24027     Ops[0] = Mask;
24028     for (unsigned i = 1; i != NumConcat; ++i)
24029       Ops[i] = ZeroVal;
24030
24031     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24032   }
24033
24034   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24035                                      Mld->getBasePtr(), NewMask, WideSrc0,
24036                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24037                                      ISD::NON_EXTLOAD);
24038   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24039   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24040
24041 }
24042 /// PerformMSTORECombine - Resolve truncating stores
24043 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24044                                     const X86Subtarget *Subtarget) {
24045   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24046   if (!Mst->isTruncatingStore())
24047     return SDValue();
24048
24049   EVT VT = Mst->getValue().getValueType();
24050   unsigned NumElems = VT.getVectorNumElements();
24051   EVT StVT = Mst->getMemoryVT();
24052   SDLoc dl(Mst);
24053
24054   assert(StVT != VT && "Cannot truncate to the same type");
24055   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24056   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24057
24058   // From, To sizes and ElemCount must be pow of two
24059   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24060     "Unexpected size for truncating masked store");
24061   // We are going to use the original vector elt for storing.
24062   // Accumulated smaller vector elements must be a multiple of the store size.
24063   assert (((NumElems * FromSz) % ToSz) == 0 &&
24064           "Unexpected ratio for truncating masked store");
24065
24066   unsigned SizeRatio  = FromSz / ToSz;
24067   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24068
24069   // Create a type on which we perform the shuffle
24070   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24071           StVT.getScalarType(), NumElems*SizeRatio);
24072
24073   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24074
24075   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24076   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24077   for (unsigned i = 0; i != NumElems; ++i)
24078     ShuffleVec[i] = i * SizeRatio;
24079
24080   // Can't shuffle using an illegal type.
24081   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24082           && "WideVecVT should be legal");
24083
24084   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24085                                         DAG.getUNDEF(WideVecVT),
24086                                         &ShuffleVec[0]);
24087
24088   SDValue NewMask;
24089   SDValue Mask = Mst->getMask();
24090   if (Mask.getValueType() == VT) {
24091     // Mask and original value have the same type
24092     NewMask = DAG.getBitcast(WideVecVT, Mask);
24093     for (unsigned i = 0; i != NumElems; ++i)
24094       ShuffleVec[i] = i * SizeRatio;
24095     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24096       ShuffleVec[i] = NumElems*SizeRatio;
24097     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24098                                    DAG.getConstant(0, dl, WideVecVT),
24099                                    &ShuffleVec[0]);
24100   }
24101   else {
24102     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24103     unsigned WidenNumElts = NumElems*SizeRatio;
24104     unsigned MaskNumElts = VT.getVectorNumElements();
24105     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24106                                      WidenNumElts);
24107
24108     unsigned NumConcat = WidenNumElts / MaskNumElts;
24109     SmallVector<SDValue, 16> Ops(NumConcat);
24110     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24111     Ops[0] = Mask;
24112     for (unsigned i = 1; i != NumConcat; ++i)
24113       Ops[i] = ZeroVal;
24114
24115     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24116   }
24117
24118   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24119                             NewMask, StVT, Mst->getMemOperand(), false);
24120 }
24121 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24122 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24123                                    const X86Subtarget *Subtarget) {
24124   StoreSDNode *St = cast<StoreSDNode>(N);
24125   EVT VT = St->getValue().getValueType();
24126   EVT StVT = St->getMemoryVT();
24127   SDLoc dl(St);
24128   SDValue StoredVal = St->getOperand(1);
24129   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24130
24131   // If we are saving a concatenation of two XMM registers and 32-byte stores
24132   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24133   unsigned Alignment = St->getAlignment();
24134   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24135   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24136       StVT == VT && !IsAligned) {
24137     unsigned NumElems = VT.getVectorNumElements();
24138     if (NumElems < 2)
24139       return SDValue();
24140
24141     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24142     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24143
24144     SDValue Stride =
24145         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24146     SDValue Ptr0 = St->getBasePtr();
24147     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24148
24149     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24150                                 St->getPointerInfo(), St->isVolatile(),
24151                                 St->isNonTemporal(), Alignment);
24152     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24153                                 St->getPointerInfo(), St->isVolatile(),
24154                                 St->isNonTemporal(),
24155                                 std::min(16U, Alignment));
24156     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24157   }
24158
24159   // Optimize trunc store (of multiple scalars) to shuffle and store.
24160   // First, pack all of the elements in one place. Next, store to memory
24161   // in fewer chunks.
24162   if (St->isTruncatingStore() && VT.isVector()) {
24163     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24164     unsigned NumElems = VT.getVectorNumElements();
24165     assert(StVT != VT && "Cannot truncate to the same type");
24166     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24167     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24168
24169     // From, To sizes and ElemCount must be pow of two
24170     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24171     // We are going to use the original vector elt for storing.
24172     // Accumulated smaller vector elements must be a multiple of the store size.
24173     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24174
24175     unsigned SizeRatio  = FromSz / ToSz;
24176
24177     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24178
24179     // Create a type on which we perform the shuffle
24180     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24181             StVT.getScalarType(), NumElems*SizeRatio);
24182
24183     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24184
24185     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24186     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24187     for (unsigned i = 0; i != NumElems; ++i)
24188       ShuffleVec[i] = i * SizeRatio;
24189
24190     // Can't shuffle using an illegal type.
24191     if (!TLI.isTypeLegal(WideVecVT))
24192       return SDValue();
24193
24194     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24195                                          DAG.getUNDEF(WideVecVT),
24196                                          &ShuffleVec[0]);
24197     // At this point all of the data is stored at the bottom of the
24198     // register. We now need to save it to mem.
24199
24200     // Find the largest store unit
24201     MVT StoreType = MVT::i8;
24202     for (MVT Tp : MVT::integer_valuetypes()) {
24203       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24204         StoreType = Tp;
24205     }
24206
24207     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24208     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24209         (64 <= NumElems * ToSz))
24210       StoreType = MVT::f64;
24211
24212     // Bitcast the original vector into a vector of store-size units
24213     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24214             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24215     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24216     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24217     SmallVector<SDValue, 8> Chains;
24218     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24219                                         TLI.getPointerTy(DAG.getDataLayout()));
24220     SDValue Ptr = St->getBasePtr();
24221
24222     // Perform one or more big stores into memory.
24223     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24224       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24225                                    StoreType, ShuffWide,
24226                                    DAG.getIntPtrConstant(i, dl));
24227       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24228                                 St->getPointerInfo(), St->isVolatile(),
24229                                 St->isNonTemporal(), St->getAlignment());
24230       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24231       Chains.push_back(Ch);
24232     }
24233
24234     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24235   }
24236
24237   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24238   // the FP state in cases where an emms may be missing.
24239   // A preferable solution to the general problem is to figure out the right
24240   // places to insert EMMS.  This qualifies as a quick hack.
24241
24242   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24243   if (VT.getSizeInBits() != 64)
24244     return SDValue();
24245
24246   const Function *F = DAG.getMachineFunction().getFunction();
24247   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24248   bool F64IsLegal =
24249       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24250   if ((VT.isVector() ||
24251        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24252       isa<LoadSDNode>(St->getValue()) &&
24253       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24254       St->getChain().hasOneUse() && !St->isVolatile()) {
24255     SDNode* LdVal = St->getValue().getNode();
24256     LoadSDNode *Ld = nullptr;
24257     int TokenFactorIndex = -1;
24258     SmallVector<SDValue, 8> Ops;
24259     SDNode* ChainVal = St->getChain().getNode();
24260     // Must be a store of a load.  We currently handle two cases:  the load
24261     // is a direct child, and it's under an intervening TokenFactor.  It is
24262     // possible to dig deeper under nested TokenFactors.
24263     if (ChainVal == LdVal)
24264       Ld = cast<LoadSDNode>(St->getChain());
24265     else if (St->getValue().hasOneUse() &&
24266              ChainVal->getOpcode() == ISD::TokenFactor) {
24267       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24268         if (ChainVal->getOperand(i).getNode() == LdVal) {
24269           TokenFactorIndex = i;
24270           Ld = cast<LoadSDNode>(St->getValue());
24271         } else
24272           Ops.push_back(ChainVal->getOperand(i));
24273       }
24274     }
24275
24276     if (!Ld || !ISD::isNormalLoad(Ld))
24277       return SDValue();
24278
24279     // If this is not the MMX case, i.e. we are just turning i64 load/store
24280     // into f64 load/store, avoid the transformation if there are multiple
24281     // uses of the loaded value.
24282     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24283       return SDValue();
24284
24285     SDLoc LdDL(Ld);
24286     SDLoc StDL(N);
24287     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24288     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24289     // pair instead.
24290     if (Subtarget->is64Bit() || F64IsLegal) {
24291       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24292       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24293                                   Ld->getPointerInfo(), Ld->isVolatile(),
24294                                   Ld->isNonTemporal(), Ld->isInvariant(),
24295                                   Ld->getAlignment());
24296       SDValue NewChain = NewLd.getValue(1);
24297       if (TokenFactorIndex != -1) {
24298         Ops.push_back(NewChain);
24299         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24300       }
24301       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24302                           St->getPointerInfo(),
24303                           St->isVolatile(), St->isNonTemporal(),
24304                           St->getAlignment());
24305     }
24306
24307     // Otherwise, lower to two pairs of 32-bit loads / stores.
24308     SDValue LoAddr = Ld->getBasePtr();
24309     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24310                                  DAG.getConstant(4, LdDL, MVT::i32));
24311
24312     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24313                                Ld->getPointerInfo(),
24314                                Ld->isVolatile(), Ld->isNonTemporal(),
24315                                Ld->isInvariant(), Ld->getAlignment());
24316     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24317                                Ld->getPointerInfo().getWithOffset(4),
24318                                Ld->isVolatile(), Ld->isNonTemporal(),
24319                                Ld->isInvariant(),
24320                                MinAlign(Ld->getAlignment(), 4));
24321
24322     SDValue NewChain = LoLd.getValue(1);
24323     if (TokenFactorIndex != -1) {
24324       Ops.push_back(LoLd);
24325       Ops.push_back(HiLd);
24326       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24327     }
24328
24329     LoAddr = St->getBasePtr();
24330     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24331                          DAG.getConstant(4, StDL, MVT::i32));
24332
24333     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24334                                 St->getPointerInfo(),
24335                                 St->isVolatile(), St->isNonTemporal(),
24336                                 St->getAlignment());
24337     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24338                                 St->getPointerInfo().getWithOffset(4),
24339                                 St->isVolatile(),
24340                                 St->isNonTemporal(),
24341                                 MinAlign(St->getAlignment(), 4));
24342     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24343   }
24344
24345   // This is similar to the above case, but here we handle a scalar 64-bit
24346   // integer store that is extracted from a vector on a 32-bit target.
24347   // If we have SSE2, then we can treat it like a floating-point double
24348   // to get past legalization. The execution dependencies fixup pass will
24349   // choose the optimal machine instruction for the store if this really is
24350   // an integer or v2f32 rather than an f64.
24351   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24352       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24353     SDValue OldExtract = St->getOperand(1);
24354     SDValue ExtOp0 = OldExtract.getOperand(0);
24355     unsigned VecSize = ExtOp0.getValueSizeInBits();
24356     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24357     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24358     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24359                                      BitCast, OldExtract.getOperand(1));
24360     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24361                         St->getPointerInfo(), St->isVolatile(),
24362                         St->isNonTemporal(), St->getAlignment());
24363   }
24364
24365   return SDValue();
24366 }
24367
24368 /// Return 'true' if this vector operation is "horizontal"
24369 /// and return the operands for the horizontal operation in LHS and RHS.  A
24370 /// horizontal operation performs the binary operation on successive elements
24371 /// of its first operand, then on successive elements of its second operand,
24372 /// returning the resulting values in a vector.  For example, if
24373 ///   A = < float a0, float a1, float a2, float a3 >
24374 /// and
24375 ///   B = < float b0, float b1, float b2, float b3 >
24376 /// then the result of doing a horizontal operation on A and B is
24377 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24378 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24379 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24380 /// set to A, RHS to B, and the routine returns 'true'.
24381 /// Note that the binary operation should have the property that if one of the
24382 /// operands is UNDEF then the result is UNDEF.
24383 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24384   // Look for the following pattern: if
24385   //   A = < float a0, float a1, float a2, float a3 >
24386   //   B = < float b0, float b1, float b2, float b3 >
24387   // and
24388   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24389   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24390   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24391   // which is A horizontal-op B.
24392
24393   // At least one of the operands should be a vector shuffle.
24394   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24395       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24396     return false;
24397
24398   MVT VT = LHS.getSimpleValueType();
24399
24400   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24401          "Unsupported vector type for horizontal add/sub");
24402
24403   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24404   // operate independently on 128-bit lanes.
24405   unsigned NumElts = VT.getVectorNumElements();
24406   unsigned NumLanes = VT.getSizeInBits()/128;
24407   unsigned NumLaneElts = NumElts / NumLanes;
24408   assert((NumLaneElts % 2 == 0) &&
24409          "Vector type should have an even number of elements in each lane");
24410   unsigned HalfLaneElts = NumLaneElts/2;
24411
24412   // View LHS in the form
24413   //   LHS = VECTOR_SHUFFLE A, B, LMask
24414   // If LHS is not a shuffle then pretend it is the shuffle
24415   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24416   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24417   // type VT.
24418   SDValue A, B;
24419   SmallVector<int, 16> LMask(NumElts);
24420   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24421     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24422       A = LHS.getOperand(0);
24423     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24424       B = LHS.getOperand(1);
24425     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24426     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24427   } else {
24428     if (LHS.getOpcode() != ISD::UNDEF)
24429       A = LHS;
24430     for (unsigned i = 0; i != NumElts; ++i)
24431       LMask[i] = i;
24432   }
24433
24434   // Likewise, view RHS in the form
24435   //   RHS = VECTOR_SHUFFLE C, D, RMask
24436   SDValue C, D;
24437   SmallVector<int, 16> RMask(NumElts);
24438   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24439     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24440       C = RHS.getOperand(0);
24441     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24442       D = RHS.getOperand(1);
24443     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24444     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24445   } else {
24446     if (RHS.getOpcode() != ISD::UNDEF)
24447       C = RHS;
24448     for (unsigned i = 0; i != NumElts; ++i)
24449       RMask[i] = i;
24450   }
24451
24452   // Check that the shuffles are both shuffling the same vectors.
24453   if (!(A == C && B == D) && !(A == D && B == C))
24454     return false;
24455
24456   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24457   if (!A.getNode() && !B.getNode())
24458     return false;
24459
24460   // If A and B occur in reverse order in RHS, then "swap" them (which means
24461   // rewriting the mask).
24462   if (A != C)
24463     ShuffleVectorSDNode::commuteMask(RMask);
24464
24465   // At this point LHS and RHS are equivalent to
24466   //   LHS = VECTOR_SHUFFLE A, B, LMask
24467   //   RHS = VECTOR_SHUFFLE A, B, RMask
24468   // Check that the masks correspond to performing a horizontal operation.
24469   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24470     for (unsigned i = 0; i != NumLaneElts; ++i) {
24471       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24472
24473       // Ignore any UNDEF components.
24474       if (LIdx < 0 || RIdx < 0 ||
24475           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24476           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24477         continue;
24478
24479       // Check that successive elements are being operated on.  If not, this is
24480       // not a horizontal operation.
24481       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24482       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24483       if (!(LIdx == Index && RIdx == Index + 1) &&
24484           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24485         return false;
24486     }
24487   }
24488
24489   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24490   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24491   return true;
24492 }
24493
24494 /// Do target-specific dag combines on floating point adds.
24495 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24496                                   const X86Subtarget *Subtarget) {
24497   EVT VT = N->getValueType(0);
24498   SDValue LHS = N->getOperand(0);
24499   SDValue RHS = N->getOperand(1);
24500
24501   // Try to synthesize horizontal adds from adds of shuffles.
24502   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24503        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24504       isHorizontalBinOp(LHS, RHS, true))
24505     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24506   return SDValue();
24507 }
24508
24509 /// Do target-specific dag combines on floating point subs.
24510 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24511                                   const X86Subtarget *Subtarget) {
24512   EVT VT = N->getValueType(0);
24513   SDValue LHS = N->getOperand(0);
24514   SDValue RHS = N->getOperand(1);
24515
24516   // Try to synthesize horizontal subs from subs of shuffles.
24517   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24518        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24519       isHorizontalBinOp(LHS, RHS, false))
24520     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24521   return SDValue();
24522 }
24523
24524 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24525 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24526   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24527
24528   // F[X]OR(0.0, x) -> x
24529   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24530     if (C->getValueAPF().isPosZero())
24531       return N->getOperand(1);
24532
24533   // F[X]OR(x, 0.0) -> x
24534   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24535     if (C->getValueAPF().isPosZero())
24536       return N->getOperand(0);
24537   return SDValue();
24538 }
24539
24540 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24541 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24542   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24543
24544   // Only perform optimizations if UnsafeMath is used.
24545   if (!DAG.getTarget().Options.UnsafeFPMath)
24546     return SDValue();
24547
24548   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24549   // into FMINC and FMAXC, which are Commutative operations.
24550   unsigned NewOp = 0;
24551   switch (N->getOpcode()) {
24552     default: llvm_unreachable("unknown opcode");
24553     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24554     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24555   }
24556
24557   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24558                      N->getOperand(0), N->getOperand(1));
24559 }
24560
24561 /// Do target-specific dag combines on X86ISD::FAND nodes.
24562 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24563   // FAND(0.0, x) -> 0.0
24564   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24565     if (C->getValueAPF().isPosZero())
24566       return N->getOperand(0);
24567
24568   // FAND(x, 0.0) -> 0.0
24569   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24570     if (C->getValueAPF().isPosZero())
24571       return N->getOperand(1);
24572
24573   return SDValue();
24574 }
24575
24576 /// Do target-specific dag combines on X86ISD::FANDN nodes
24577 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24578   // FANDN(0.0, x) -> x
24579   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24580     if (C->getValueAPF().isPosZero())
24581       return N->getOperand(1);
24582
24583   // FANDN(x, 0.0) -> 0.0
24584   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24585     if (C->getValueAPF().isPosZero())
24586       return N->getOperand(1);
24587
24588   return SDValue();
24589 }
24590
24591 static SDValue PerformBTCombine(SDNode *N,
24592                                 SelectionDAG &DAG,
24593                                 TargetLowering::DAGCombinerInfo &DCI) {
24594   // BT ignores high bits in the bit index operand.
24595   SDValue Op1 = N->getOperand(1);
24596   if (Op1.hasOneUse()) {
24597     unsigned BitWidth = Op1.getValueSizeInBits();
24598     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24599     APInt KnownZero, KnownOne;
24600     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24601                                           !DCI.isBeforeLegalizeOps());
24602     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24603     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24604         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24605       DCI.CommitTargetLoweringOpt(TLO);
24606   }
24607   return SDValue();
24608 }
24609
24610 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24611   SDValue Op = N->getOperand(0);
24612   if (Op.getOpcode() == ISD::BITCAST)
24613     Op = Op.getOperand(0);
24614   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24615   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24616       VT.getVectorElementType().getSizeInBits() ==
24617       OpVT.getVectorElementType().getSizeInBits()) {
24618     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24619   }
24620   return SDValue();
24621 }
24622
24623 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24624                                                const X86Subtarget *Subtarget) {
24625   EVT VT = N->getValueType(0);
24626   if (!VT.isVector())
24627     return SDValue();
24628
24629   SDValue N0 = N->getOperand(0);
24630   SDValue N1 = N->getOperand(1);
24631   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24632   SDLoc dl(N);
24633
24634   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24635   // both SSE and AVX2 since there is no sign-extended shift right
24636   // operation on a vector with 64-bit elements.
24637   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24638   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24639   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24640       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24641     SDValue N00 = N0.getOperand(0);
24642
24643     // EXTLOAD has a better solution on AVX2,
24644     // it may be replaced with X86ISD::VSEXT node.
24645     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24646       if (!ISD::isNormalLoad(N00.getNode()))
24647         return SDValue();
24648
24649     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24650         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24651                                   N00, N1);
24652       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24653     }
24654   }
24655   return SDValue();
24656 }
24657
24658 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24659                                   TargetLowering::DAGCombinerInfo &DCI,
24660                                   const X86Subtarget *Subtarget) {
24661   SDValue N0 = N->getOperand(0);
24662   EVT VT = N->getValueType(0);
24663   EVT SVT = VT.getScalarType();
24664   EVT InVT = N0.getValueType();
24665   EVT InSVT = InVT.getScalarType();
24666   SDLoc DL(N);
24667
24668   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24669   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24670   // This exposes the sext to the sdivrem lowering, so that it directly extends
24671   // from AH (which we otherwise need to do contortions to access).
24672   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24673       InVT == MVT::i8 && VT == MVT::i32) {
24674     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24675     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24676                             N0.getOperand(0), N0.getOperand(1));
24677     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24678     return R.getValue(1);
24679   }
24680
24681   if (!DCI.isBeforeLegalizeOps()) {
24682     if (InVT == MVT::i1) {
24683       SDValue Zero = DAG.getConstant(0, DL, VT);
24684       SDValue AllOnes =
24685         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24686       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24687     }
24688     return SDValue();
24689   }
24690
24691   if (VT.isVector() && Subtarget->hasSSE2()) {
24692     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24693       EVT InVT = N.getValueType();
24694       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24695                                    Size / InVT.getScalarSizeInBits());
24696       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24697                                     DAG.getUNDEF(InVT));
24698       Opnds[0] = N;
24699       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24700     };
24701
24702     // If target-size is less than 128-bits, extend to a type that would extend
24703     // to 128 bits, extend that and extract the original target vector.
24704     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24705         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24706         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24707       unsigned Scale = 128 / VT.getSizeInBits();
24708       EVT ExVT =
24709           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24710       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24711       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24712       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24713                          DAG.getIntPtrConstant(0, DL));
24714     }
24715
24716     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24717     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24718     if (VT.getSizeInBits() == 128 &&
24719         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24720         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24721       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24722       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24723     }
24724
24725     // On pre-AVX2 targets, split into 128-bit nodes of
24726     // ISD::SIGN_EXTEND_VECTOR_INREG.
24727     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24728         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24729         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24730       unsigned NumVecs = VT.getSizeInBits() / 128;
24731       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24732       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24733       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24734
24735       SmallVector<SDValue, 8> Opnds;
24736       for (unsigned i = 0, Offset = 0; i != NumVecs;
24737            ++i, Offset += NumSubElts) {
24738         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24739                                      DAG.getIntPtrConstant(Offset, DL));
24740         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24741         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24742         Opnds.push_back(SrcVec);
24743       }
24744       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24745     }
24746   }
24747
24748   if (!Subtarget->hasFp256())
24749     return SDValue();
24750
24751   if (VT.isVector() && VT.getSizeInBits() == 256)
24752     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24753       return R;
24754
24755   return SDValue();
24756 }
24757
24758 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24759                                  const X86Subtarget* Subtarget) {
24760   SDLoc dl(N);
24761   EVT VT = N->getValueType(0);
24762
24763   // Let legalize expand this if it isn't a legal type yet.
24764   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24765     return SDValue();
24766
24767   EVT ScalarVT = VT.getScalarType();
24768   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24769       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24770        !Subtarget->hasAVX512()))
24771     return SDValue();
24772
24773   SDValue A = N->getOperand(0);
24774   SDValue B = N->getOperand(1);
24775   SDValue C = N->getOperand(2);
24776
24777   bool NegA = (A.getOpcode() == ISD::FNEG);
24778   bool NegB = (B.getOpcode() == ISD::FNEG);
24779   bool NegC = (C.getOpcode() == ISD::FNEG);
24780
24781   // Negative multiplication when NegA xor NegB
24782   bool NegMul = (NegA != NegB);
24783   if (NegA)
24784     A = A.getOperand(0);
24785   if (NegB)
24786     B = B.getOperand(0);
24787   if (NegC)
24788     C = C.getOperand(0);
24789
24790   unsigned Opcode;
24791   if (!NegMul)
24792     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24793   else
24794     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24795
24796   return DAG.getNode(Opcode, dl, VT, A, B, C);
24797 }
24798
24799 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24800                                   TargetLowering::DAGCombinerInfo &DCI,
24801                                   const X86Subtarget *Subtarget) {
24802   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24803   //           (and (i32 x86isd::setcc_carry), 1)
24804   // This eliminates the zext. This transformation is necessary because
24805   // ISD::SETCC is always legalized to i8.
24806   SDLoc dl(N);
24807   SDValue N0 = N->getOperand(0);
24808   EVT VT = N->getValueType(0);
24809
24810   if (N0.getOpcode() == ISD::AND &&
24811       N0.hasOneUse() &&
24812       N0.getOperand(0).hasOneUse()) {
24813     SDValue N00 = N0.getOperand(0);
24814     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24815       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24816       if (!C || C->getZExtValue() != 1)
24817         return SDValue();
24818       return DAG.getNode(ISD::AND, dl, VT,
24819                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24820                                      N00.getOperand(0), N00.getOperand(1)),
24821                          DAG.getConstant(1, dl, VT));
24822     }
24823   }
24824
24825   if (N0.getOpcode() == ISD::TRUNCATE &&
24826       N0.hasOneUse() &&
24827       N0.getOperand(0).hasOneUse()) {
24828     SDValue N00 = N0.getOperand(0);
24829     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24830       return DAG.getNode(ISD::AND, dl, VT,
24831                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24832                                      N00.getOperand(0), N00.getOperand(1)),
24833                          DAG.getConstant(1, dl, VT));
24834     }
24835   }
24836
24837   if (VT.is256BitVector())
24838     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24839       return R;
24840
24841   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24842   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24843   // This exposes the zext to the udivrem lowering, so that it directly extends
24844   // from AH (which we otherwise need to do contortions to access).
24845   if (N0.getOpcode() == ISD::UDIVREM &&
24846       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24847       (VT == MVT::i32 || VT == MVT::i64)) {
24848     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24849     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24850                             N0.getOperand(0), N0.getOperand(1));
24851     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24852     return R.getValue(1);
24853   }
24854
24855   return SDValue();
24856 }
24857
24858 // Optimize x == -y --> x+y == 0
24859 //          x != -y --> x+y != 0
24860 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24861                                       const X86Subtarget* Subtarget) {
24862   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24863   SDValue LHS = N->getOperand(0);
24864   SDValue RHS = N->getOperand(1);
24865   EVT VT = N->getValueType(0);
24866   SDLoc DL(N);
24867
24868   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24869     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24870       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24871         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24872                                    LHS.getOperand(1));
24873         return DAG.getSetCC(DL, N->getValueType(0), addV,
24874                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24875       }
24876   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24877     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24878       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24879         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24880                                    RHS.getOperand(1));
24881         return DAG.getSetCC(DL, N->getValueType(0), addV,
24882                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24883       }
24884
24885   if (VT.getScalarType() == MVT::i1 &&
24886       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24887     bool IsSEXT0 =
24888         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24889         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24890     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24891
24892     if (!IsSEXT0 || !IsVZero1) {
24893       // Swap the operands and update the condition code.
24894       std::swap(LHS, RHS);
24895       CC = ISD::getSetCCSwappedOperands(CC);
24896
24897       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24898                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24899       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24900     }
24901
24902     if (IsSEXT0 && IsVZero1) {
24903       assert(VT == LHS.getOperand(0).getValueType() &&
24904              "Uexpected operand type");
24905       if (CC == ISD::SETGT)
24906         return DAG.getConstant(0, DL, VT);
24907       if (CC == ISD::SETLE)
24908         return DAG.getConstant(1, DL, VT);
24909       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24910         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24911
24912       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24913              "Unexpected condition code!");
24914       return LHS.getOperand(0);
24915     }
24916   }
24917
24918   return SDValue();
24919 }
24920
24921 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24922                                          SelectionDAG &DAG) {
24923   SDLoc dl(Load);
24924   MVT VT = Load->getSimpleValueType(0);
24925   MVT EVT = VT.getVectorElementType();
24926   SDValue Addr = Load->getOperand(1);
24927   SDValue NewAddr = DAG.getNode(
24928       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24929       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24930                       Addr.getSimpleValueType()));
24931
24932   SDValue NewLoad =
24933       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24934                   DAG.getMachineFunction().getMachineMemOperand(
24935                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24936   return NewLoad;
24937 }
24938
24939 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24940                                       const X86Subtarget *Subtarget) {
24941   SDLoc dl(N);
24942   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24943   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24944          "X86insertps is only defined for v4x32");
24945
24946   SDValue Ld = N->getOperand(1);
24947   if (MayFoldLoad(Ld)) {
24948     // Extract the countS bits from the immediate so we can get the proper
24949     // address when narrowing the vector load to a specific element.
24950     // When the second source op is a memory address, insertps doesn't use
24951     // countS and just gets an f32 from that address.
24952     unsigned DestIndex =
24953         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24954
24955     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24956
24957     // Create this as a scalar to vector to match the instruction pattern.
24958     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24959     // countS bits are ignored when loading from memory on insertps, which
24960     // means we don't need to explicitly set them to 0.
24961     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24962                        LoadScalarToVector, N->getOperand(2));
24963   }
24964   return SDValue();
24965 }
24966
24967 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24968   SDValue V0 = N->getOperand(0);
24969   SDValue V1 = N->getOperand(1);
24970   SDLoc DL(N);
24971   EVT VT = N->getValueType(0);
24972
24973   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24974   // operands and changing the mask to 1. This saves us a bunch of
24975   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24976   // x86InstrInfo knows how to commute this back after instruction selection
24977   // if it would help register allocation.
24978
24979   // TODO: If optimizing for size or a processor that doesn't suffer from
24980   // partial register update stalls, this should be transformed into a MOVSD
24981   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24982
24983   if (VT == MVT::v2f64)
24984     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24985       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24986         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24987         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24988       }
24989
24990   return SDValue();
24991 }
24992
24993 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24994 // as "sbb reg,reg", since it can be extended without zext and produces
24995 // an all-ones bit which is more useful than 0/1 in some cases.
24996 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24997                                MVT VT) {
24998   if (VT == MVT::i8)
24999     return DAG.getNode(ISD::AND, DL, VT,
25000                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25001                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
25002                                    EFLAGS),
25003                        DAG.getConstant(1, DL, VT));
25004   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
25005   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
25006                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
25007                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
25008                                  EFLAGS));
25009 }
25010
25011 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
25012 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
25013                                    TargetLowering::DAGCombinerInfo &DCI,
25014                                    const X86Subtarget *Subtarget) {
25015   SDLoc DL(N);
25016   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
25017   SDValue EFLAGS = N->getOperand(1);
25018
25019   if (CC == X86::COND_A) {
25020     // Try to convert COND_A into COND_B in an attempt to facilitate
25021     // materializing "setb reg".
25022     //
25023     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
25024     // cannot take an immediate as its first operand.
25025     //
25026     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25027         EFLAGS.getValueType().isInteger() &&
25028         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25029       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25030                                    EFLAGS.getNode()->getVTList(),
25031                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25032       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25033       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25034     }
25035   }
25036
25037   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25038   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25039   // cases.
25040   if (CC == X86::COND_B)
25041     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25042
25043   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25044     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25045     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25046   }
25047
25048   return SDValue();
25049 }
25050
25051 // Optimize branch condition evaluation.
25052 //
25053 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25054                                     TargetLowering::DAGCombinerInfo &DCI,
25055                                     const X86Subtarget *Subtarget) {
25056   SDLoc DL(N);
25057   SDValue Chain = N->getOperand(0);
25058   SDValue Dest = N->getOperand(1);
25059   SDValue EFLAGS = N->getOperand(3);
25060   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25061
25062   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25063     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25064     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25065                        Flags);
25066   }
25067
25068   return SDValue();
25069 }
25070
25071 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25072                                                          SelectionDAG &DAG) {
25073   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25074   // optimize away operation when it's from a constant.
25075   //
25076   // The general transformation is:
25077   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25078   //       AND(VECTOR_CMP(x,y), constant2)
25079   //    constant2 = UNARYOP(constant)
25080
25081   // Early exit if this isn't a vector operation, the operand of the
25082   // unary operation isn't a bitwise AND, or if the sizes of the operations
25083   // aren't the same.
25084   EVT VT = N->getValueType(0);
25085   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25086       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25087       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25088     return SDValue();
25089
25090   // Now check that the other operand of the AND is a constant. We could
25091   // make the transformation for non-constant splats as well, but it's unclear
25092   // that would be a benefit as it would not eliminate any operations, just
25093   // perform one more step in scalar code before moving to the vector unit.
25094   if (BuildVectorSDNode *BV =
25095           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25096     // Bail out if the vector isn't a constant.
25097     if (!BV->isConstant())
25098       return SDValue();
25099
25100     // Everything checks out. Build up the new and improved node.
25101     SDLoc DL(N);
25102     EVT IntVT = BV->getValueType(0);
25103     // Create a new constant of the appropriate type for the transformed
25104     // DAG.
25105     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25106     // The AND node needs bitcasts to/from an integer vector type around it.
25107     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25108     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25109                                  N->getOperand(0)->getOperand(0), MaskConst);
25110     SDValue Res = DAG.getBitcast(VT, NewAnd);
25111     return Res;
25112   }
25113
25114   return SDValue();
25115 }
25116
25117 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25118                                         const X86Subtarget *Subtarget) {
25119   SDValue Op0 = N->getOperand(0);
25120   EVT VT = N->getValueType(0);
25121   EVT InVT = Op0.getValueType();
25122   EVT InSVT = InVT.getScalarType();
25123   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25124
25125   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25126   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25127   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25128     SDLoc dl(N);
25129     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25130                                  InVT.getVectorNumElements());
25131     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25132
25133     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25134       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25135
25136     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25137   }
25138
25139   return SDValue();
25140 }
25141
25142 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25143                                         const X86Subtarget *Subtarget) {
25144   // First try to optimize away the conversion entirely when it's
25145   // conditionally from a constant. Vectors only.
25146   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25147     return Res;
25148
25149   // Now move on to more general possibilities.
25150   SDValue Op0 = N->getOperand(0);
25151   EVT VT = N->getValueType(0);
25152   EVT InVT = Op0.getValueType();
25153   EVT InSVT = InVT.getScalarType();
25154
25155   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25156   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25157   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25158     SDLoc dl(N);
25159     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25160                                  InVT.getVectorNumElements());
25161     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25162     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25163   }
25164
25165   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25166   // a 32-bit target where SSE doesn't support i64->FP operations.
25167   if (Op0.getOpcode() == ISD::LOAD) {
25168     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25169     EVT LdVT = Ld->getValueType(0);
25170
25171     // This transformation is not supported if the result type is f16
25172     if (VT == MVT::f16)
25173       return SDValue();
25174
25175     if (!Ld->isVolatile() && !VT.isVector() &&
25176         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25177         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25178       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25179           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25180       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25181       return FILDChain;
25182     }
25183   }
25184   return SDValue();
25185 }
25186
25187 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25188 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25189                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25190   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25191   // the result is either zero or one (depending on the input carry bit).
25192   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25193   if (X86::isZeroNode(N->getOperand(0)) &&
25194       X86::isZeroNode(N->getOperand(1)) &&
25195       // We don't have a good way to replace an EFLAGS use, so only do this when
25196       // dead right now.
25197       SDValue(N, 1).use_empty()) {
25198     SDLoc DL(N);
25199     EVT VT = N->getValueType(0);
25200     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25201     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25202                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25203                                            DAG.getConstant(X86::COND_B, DL,
25204                                                            MVT::i8),
25205                                            N->getOperand(2)),
25206                                DAG.getConstant(1, DL, VT));
25207     return DCI.CombineTo(N, Res1, CarryOut);
25208   }
25209
25210   return SDValue();
25211 }
25212
25213 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25214 //      (add Y, (setne X, 0)) -> sbb -1, Y
25215 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25216 //      (sub (setne X, 0), Y) -> adc -1, Y
25217 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25218   SDLoc DL(N);
25219
25220   // Look through ZExts.
25221   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25222   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25223     return SDValue();
25224
25225   SDValue SetCC = Ext.getOperand(0);
25226   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25227     return SDValue();
25228
25229   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25230   if (CC != X86::COND_E && CC != X86::COND_NE)
25231     return SDValue();
25232
25233   SDValue Cmp = SetCC.getOperand(1);
25234   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25235       !X86::isZeroNode(Cmp.getOperand(1)) ||
25236       !Cmp.getOperand(0).getValueType().isInteger())
25237     return SDValue();
25238
25239   SDValue CmpOp0 = Cmp.getOperand(0);
25240   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25241                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25242
25243   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25244   if (CC == X86::COND_NE)
25245     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25246                        DL, OtherVal.getValueType(), OtherVal,
25247                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25248                        NewCmp);
25249   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25250                      DL, OtherVal.getValueType(), OtherVal,
25251                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25252 }
25253
25254 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25255 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25256                                  const X86Subtarget *Subtarget) {
25257   EVT VT = N->getValueType(0);
25258   SDValue Op0 = N->getOperand(0);
25259   SDValue Op1 = N->getOperand(1);
25260
25261   // Try to synthesize horizontal adds from adds of shuffles.
25262   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25263        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25264       isHorizontalBinOp(Op0, Op1, true))
25265     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25266
25267   return OptimizeConditionalInDecrement(N, DAG);
25268 }
25269
25270 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25271                                  const X86Subtarget *Subtarget) {
25272   SDValue Op0 = N->getOperand(0);
25273   SDValue Op1 = N->getOperand(1);
25274
25275   // X86 can't encode an immediate LHS of a sub. See if we can push the
25276   // negation into a preceding instruction.
25277   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25278     // If the RHS of the sub is a XOR with one use and a constant, invert the
25279     // immediate. Then add one to the LHS of the sub so we can turn
25280     // X-Y -> X+~Y+1, saving one register.
25281     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25282         isa<ConstantSDNode>(Op1.getOperand(1))) {
25283       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25284       EVT VT = Op0.getValueType();
25285       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25286                                    Op1.getOperand(0),
25287                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25288       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25289                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25290     }
25291   }
25292
25293   // Try to synthesize horizontal adds from adds of shuffles.
25294   EVT VT = N->getValueType(0);
25295   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25296        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25297       isHorizontalBinOp(Op0, Op1, true))
25298     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25299
25300   return OptimizeConditionalInDecrement(N, DAG);
25301 }
25302
25303 /// performVZEXTCombine - Performs build vector combines
25304 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25305                                    TargetLowering::DAGCombinerInfo &DCI,
25306                                    const X86Subtarget *Subtarget) {
25307   SDLoc DL(N);
25308   MVT VT = N->getSimpleValueType(0);
25309   SDValue Op = N->getOperand(0);
25310   MVT OpVT = Op.getSimpleValueType();
25311   MVT OpEltVT = OpVT.getVectorElementType();
25312   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25313
25314   // (vzext (bitcast (vzext (x)) -> (vzext x)
25315   SDValue V = Op;
25316   while (V.getOpcode() == ISD::BITCAST)
25317     V = V.getOperand(0);
25318
25319   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25320     MVT InnerVT = V.getSimpleValueType();
25321     MVT InnerEltVT = InnerVT.getVectorElementType();
25322
25323     // If the element sizes match exactly, we can just do one larger vzext. This
25324     // is always an exact type match as vzext operates on integer types.
25325     if (OpEltVT == InnerEltVT) {
25326       assert(OpVT == InnerVT && "Types must match for vzext!");
25327       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25328     }
25329
25330     // The only other way we can combine them is if only a single element of the
25331     // inner vzext is used in the input to the outer vzext.
25332     if (InnerEltVT.getSizeInBits() < InputBits)
25333       return SDValue();
25334
25335     // In this case, the inner vzext is completely dead because we're going to
25336     // only look at bits inside of the low element. Just do the outer vzext on
25337     // a bitcast of the input to the inner.
25338     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25339   }
25340
25341   // Check if we can bypass extracting and re-inserting an element of an input
25342   // vector. Essentialy:
25343   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25344   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25345       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25346       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25347     SDValue ExtractedV = V.getOperand(0);
25348     SDValue OrigV = ExtractedV.getOperand(0);
25349     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25350       if (ExtractIdx->getZExtValue() == 0) {
25351         MVT OrigVT = OrigV.getSimpleValueType();
25352         // Extract a subvector if necessary...
25353         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25354           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25355           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25356                                     OrigVT.getVectorNumElements() / Ratio);
25357           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25358                               DAG.getIntPtrConstant(0, DL));
25359         }
25360         Op = DAG.getBitcast(OpVT, OrigV);
25361         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25362       }
25363   }
25364
25365   return SDValue();
25366 }
25367
25368 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25369                                              DAGCombinerInfo &DCI) const {
25370   SelectionDAG &DAG = DCI.DAG;
25371   switch (N->getOpcode()) {
25372   default: break;
25373   case ISD::EXTRACT_VECTOR_ELT:
25374     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25375   case ISD::VSELECT:
25376   case ISD::SELECT:
25377   case X86ISD::SHRUNKBLEND:
25378     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25379   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25380   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25381   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25382   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25383   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25384   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25385   case ISD::SHL:
25386   case ISD::SRA:
25387   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25388   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25389   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25390   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25391   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25392   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25393   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25394   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25395   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25396   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25397   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25398   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25399   case X86ISD::FXOR:
25400   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25401   case X86ISD::FMIN:
25402   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25403   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25404   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25405   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25406   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25407   case ISD::ANY_EXTEND:
25408   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25409   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25410   case ISD::SIGN_EXTEND_INREG:
25411     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25412   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25413   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25414   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25415   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25416   case X86ISD::SHUFP:       // Handle all target specific shuffles
25417   case X86ISD::PALIGNR:
25418   case X86ISD::UNPCKH:
25419   case X86ISD::UNPCKL:
25420   case X86ISD::MOVHLPS:
25421   case X86ISD::MOVLHPS:
25422   case X86ISD::PSHUFB:
25423   case X86ISD::PSHUFD:
25424   case X86ISD::PSHUFHW:
25425   case X86ISD::PSHUFLW:
25426   case X86ISD::MOVSS:
25427   case X86ISD::MOVSD:
25428   case X86ISD::VPERMILPI:
25429   case X86ISD::VPERM2X128:
25430   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25431   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25432   case ISD::INTRINSIC_WO_CHAIN:
25433     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25434   case X86ISD::INSERTPS: {
25435     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25436       return PerformINSERTPSCombine(N, DAG, Subtarget);
25437     break;
25438   }
25439   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25440   }
25441
25442   return SDValue();
25443 }
25444
25445 /// isTypeDesirableForOp - Return true if the target has native support for
25446 /// the specified value type and it is 'desirable' to use the type for the
25447 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25448 /// instruction encodings are longer and some i16 instructions are slow.
25449 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25450   if (!isTypeLegal(VT))
25451     return false;
25452   if (VT != MVT::i16)
25453     return true;
25454
25455   switch (Opc) {
25456   default:
25457     return true;
25458   case ISD::LOAD:
25459   case ISD::SIGN_EXTEND:
25460   case ISD::ZERO_EXTEND:
25461   case ISD::ANY_EXTEND:
25462   case ISD::SHL:
25463   case ISD::SRL:
25464   case ISD::SUB:
25465   case ISD::ADD:
25466   case ISD::MUL:
25467   case ISD::AND:
25468   case ISD::OR:
25469   case ISD::XOR:
25470     return false;
25471   }
25472 }
25473
25474 /// IsDesirableToPromoteOp - This method query the target whether it is
25475 /// beneficial for dag combiner to promote the specified node. If true, it
25476 /// should return the desired promotion type by reference.
25477 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25478   EVT VT = Op.getValueType();
25479   if (VT != MVT::i16)
25480     return false;
25481
25482   bool Promote = false;
25483   bool Commute = false;
25484   switch (Op.getOpcode()) {
25485   default: break;
25486   case ISD::LOAD: {
25487     LoadSDNode *LD = cast<LoadSDNode>(Op);
25488     // If the non-extending load has a single use and it's not live out, then it
25489     // might be folded.
25490     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25491                                                      Op.hasOneUse()*/) {
25492       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25493              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25494         // The only case where we'd want to promote LOAD (rather then it being
25495         // promoted as an operand is when it's only use is liveout.
25496         if (UI->getOpcode() != ISD::CopyToReg)
25497           return false;
25498       }
25499     }
25500     Promote = true;
25501     break;
25502   }
25503   case ISD::SIGN_EXTEND:
25504   case ISD::ZERO_EXTEND:
25505   case ISD::ANY_EXTEND:
25506     Promote = true;
25507     break;
25508   case ISD::SHL:
25509   case ISD::SRL: {
25510     SDValue N0 = Op.getOperand(0);
25511     // Look out for (store (shl (load), x)).
25512     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25513       return false;
25514     Promote = true;
25515     break;
25516   }
25517   case ISD::ADD:
25518   case ISD::MUL:
25519   case ISD::AND:
25520   case ISD::OR:
25521   case ISD::XOR:
25522     Commute = true;
25523     // fallthrough
25524   case ISD::SUB: {
25525     SDValue N0 = Op.getOperand(0);
25526     SDValue N1 = Op.getOperand(1);
25527     if (!Commute && MayFoldLoad(N1))
25528       return false;
25529     // Avoid disabling potential load folding opportunities.
25530     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25531       return false;
25532     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25533       return false;
25534     Promote = true;
25535   }
25536   }
25537
25538   PVT = MVT::i32;
25539   return Promote;
25540 }
25541
25542 //===----------------------------------------------------------------------===//
25543 //                           X86 Inline Assembly Support
25544 //===----------------------------------------------------------------------===//
25545
25546 // Helper to match a string separated by whitespace.
25547 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25548   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25549
25550   for (StringRef Piece : Pieces) {
25551     if (!S.startswith(Piece)) // Check if the piece matches.
25552       return false;
25553
25554     S = S.substr(Piece.size());
25555     StringRef::size_type Pos = S.find_first_not_of(" \t");
25556     if (Pos == 0) // We matched a prefix.
25557       return false;
25558
25559     S = S.substr(Pos);
25560   }
25561
25562   return S.empty();
25563 }
25564
25565 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25566
25567   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25568     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25569         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25570         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25571
25572       if (AsmPieces.size() == 3)
25573         return true;
25574       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25575         return true;
25576     }
25577   }
25578   return false;
25579 }
25580
25581 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25582   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25583
25584   std::string AsmStr = IA->getAsmString();
25585
25586   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25587   if (!Ty || Ty->getBitWidth() % 16 != 0)
25588     return false;
25589
25590   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25591   SmallVector<StringRef, 4> AsmPieces;
25592   SplitString(AsmStr, AsmPieces, ";\n");
25593
25594   switch (AsmPieces.size()) {
25595   default: return false;
25596   case 1:
25597     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25598     // we will turn this bswap into something that will be lowered to logical
25599     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25600     // lower so don't worry about this.
25601     // bswap $0
25602     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25603         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25604         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25605         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25606         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25607         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25608       // No need to check constraints, nothing other than the equivalent of
25609       // "=r,0" would be valid here.
25610       return IntrinsicLowering::LowerToByteSwap(CI);
25611     }
25612
25613     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25614     if (CI->getType()->isIntegerTy(16) &&
25615         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25616         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25617          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25618       AsmPieces.clear();
25619       StringRef ConstraintsStr = IA->getConstraintString();
25620       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25621       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25622       if (clobbersFlagRegisters(AsmPieces))
25623         return IntrinsicLowering::LowerToByteSwap(CI);
25624     }
25625     break;
25626   case 3:
25627     if (CI->getType()->isIntegerTy(32) &&
25628         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25629         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25630         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25631         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25632       AsmPieces.clear();
25633       StringRef ConstraintsStr = IA->getConstraintString();
25634       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25635       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25636       if (clobbersFlagRegisters(AsmPieces))
25637         return IntrinsicLowering::LowerToByteSwap(CI);
25638     }
25639
25640     if (CI->getType()->isIntegerTy(64)) {
25641       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25642       if (Constraints.size() >= 2 &&
25643           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25644           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25645         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25646         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25647             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25648             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25649           return IntrinsicLowering::LowerToByteSwap(CI);
25650       }
25651     }
25652     break;
25653   }
25654   return false;
25655 }
25656
25657 /// getConstraintType - Given a constraint letter, return the type of
25658 /// constraint it is for this target.
25659 X86TargetLowering::ConstraintType
25660 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25661   if (Constraint.size() == 1) {
25662     switch (Constraint[0]) {
25663     case 'R':
25664     case 'q':
25665     case 'Q':
25666     case 'f':
25667     case 't':
25668     case 'u':
25669     case 'y':
25670     case 'x':
25671     case 'Y':
25672     case 'l':
25673       return C_RegisterClass;
25674     case 'a':
25675     case 'b':
25676     case 'c':
25677     case 'd':
25678     case 'S':
25679     case 'D':
25680     case 'A':
25681       return C_Register;
25682     case 'I':
25683     case 'J':
25684     case 'K':
25685     case 'L':
25686     case 'M':
25687     case 'N':
25688     case 'G':
25689     case 'C':
25690     case 'e':
25691     case 'Z':
25692       return C_Other;
25693     default:
25694       break;
25695     }
25696   }
25697   return TargetLowering::getConstraintType(Constraint);
25698 }
25699
25700 /// Examine constraint type and operand type and determine a weight value.
25701 /// This object must already have been set up with the operand type
25702 /// and the current alternative constraint selected.
25703 TargetLowering::ConstraintWeight
25704   X86TargetLowering::getSingleConstraintMatchWeight(
25705     AsmOperandInfo &info, const char *constraint) const {
25706   ConstraintWeight weight = CW_Invalid;
25707   Value *CallOperandVal = info.CallOperandVal;
25708     // If we don't have a value, we can't do a match,
25709     // but allow it at the lowest weight.
25710   if (!CallOperandVal)
25711     return CW_Default;
25712   Type *type = CallOperandVal->getType();
25713   // Look at the constraint type.
25714   switch (*constraint) {
25715   default:
25716     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25717   case 'R':
25718   case 'q':
25719   case 'Q':
25720   case 'a':
25721   case 'b':
25722   case 'c':
25723   case 'd':
25724   case 'S':
25725   case 'D':
25726   case 'A':
25727     if (CallOperandVal->getType()->isIntegerTy())
25728       weight = CW_SpecificReg;
25729     break;
25730   case 'f':
25731   case 't':
25732   case 'u':
25733     if (type->isFloatingPointTy())
25734       weight = CW_SpecificReg;
25735     break;
25736   case 'y':
25737     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25738       weight = CW_SpecificReg;
25739     break;
25740   case 'x':
25741   case 'Y':
25742     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25743         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25744       weight = CW_Register;
25745     break;
25746   case 'I':
25747     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25748       if (C->getZExtValue() <= 31)
25749         weight = CW_Constant;
25750     }
25751     break;
25752   case 'J':
25753     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25754       if (C->getZExtValue() <= 63)
25755         weight = CW_Constant;
25756     }
25757     break;
25758   case 'K':
25759     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25760       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25761         weight = CW_Constant;
25762     }
25763     break;
25764   case 'L':
25765     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25766       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25767         weight = CW_Constant;
25768     }
25769     break;
25770   case 'M':
25771     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25772       if (C->getZExtValue() <= 3)
25773         weight = CW_Constant;
25774     }
25775     break;
25776   case 'N':
25777     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25778       if (C->getZExtValue() <= 0xff)
25779         weight = CW_Constant;
25780     }
25781     break;
25782   case 'G':
25783   case 'C':
25784     if (isa<ConstantFP>(CallOperandVal)) {
25785       weight = CW_Constant;
25786     }
25787     break;
25788   case 'e':
25789     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25790       if ((C->getSExtValue() >= -0x80000000LL) &&
25791           (C->getSExtValue() <= 0x7fffffffLL))
25792         weight = CW_Constant;
25793     }
25794     break;
25795   case 'Z':
25796     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25797       if (C->getZExtValue() <= 0xffffffff)
25798         weight = CW_Constant;
25799     }
25800     break;
25801   }
25802   return weight;
25803 }
25804
25805 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25806 /// with another that has more specific requirements based on the type of the
25807 /// corresponding operand.
25808 const char *X86TargetLowering::
25809 LowerXConstraint(EVT ConstraintVT) const {
25810   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25811   // 'f' like normal targets.
25812   if (ConstraintVT.isFloatingPoint()) {
25813     if (Subtarget->hasSSE2())
25814       return "Y";
25815     if (Subtarget->hasSSE1())
25816       return "x";
25817   }
25818
25819   return TargetLowering::LowerXConstraint(ConstraintVT);
25820 }
25821
25822 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25823 /// vector.  If it is invalid, don't add anything to Ops.
25824 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25825                                                      std::string &Constraint,
25826                                                      std::vector<SDValue>&Ops,
25827                                                      SelectionDAG &DAG) const {
25828   SDValue Result;
25829
25830   // Only support length 1 constraints for now.
25831   if (Constraint.length() > 1) return;
25832
25833   char ConstraintLetter = Constraint[0];
25834   switch (ConstraintLetter) {
25835   default: break;
25836   case 'I':
25837     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25838       if (C->getZExtValue() <= 31) {
25839         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25840                                        Op.getValueType());
25841         break;
25842       }
25843     }
25844     return;
25845   case 'J':
25846     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25847       if (C->getZExtValue() <= 63) {
25848         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25849                                        Op.getValueType());
25850         break;
25851       }
25852     }
25853     return;
25854   case 'K':
25855     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25856       if (isInt<8>(C->getSExtValue())) {
25857         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25858                                        Op.getValueType());
25859         break;
25860       }
25861     }
25862     return;
25863   case 'L':
25864     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25865       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25866           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25867         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25868                                        Op.getValueType());
25869         break;
25870       }
25871     }
25872     return;
25873   case 'M':
25874     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25875       if (C->getZExtValue() <= 3) {
25876         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25877                                        Op.getValueType());
25878         break;
25879       }
25880     }
25881     return;
25882   case 'N':
25883     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25884       if (C->getZExtValue() <= 255) {
25885         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25886                                        Op.getValueType());
25887         break;
25888       }
25889     }
25890     return;
25891   case 'O':
25892     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25893       if (C->getZExtValue() <= 127) {
25894         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25895                                        Op.getValueType());
25896         break;
25897       }
25898     }
25899     return;
25900   case 'e': {
25901     // 32-bit signed value
25902     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25903       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25904                                            C->getSExtValue())) {
25905         // Widen to 64 bits here to get it sign extended.
25906         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25907         break;
25908       }
25909     // FIXME gcc accepts some relocatable values here too, but only in certain
25910     // memory models; it's complicated.
25911     }
25912     return;
25913   }
25914   case 'Z': {
25915     // 32-bit unsigned value
25916     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25917       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25918                                            C->getZExtValue())) {
25919         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25920                                        Op.getValueType());
25921         break;
25922       }
25923     }
25924     // FIXME gcc accepts some relocatable values here too, but only in certain
25925     // memory models; it's complicated.
25926     return;
25927   }
25928   case 'i': {
25929     // Literal immediates are always ok.
25930     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25931       // Widen to 64 bits here to get it sign extended.
25932       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25933       break;
25934     }
25935
25936     // In any sort of PIC mode addresses need to be computed at runtime by
25937     // adding in a register or some sort of table lookup.  These can't
25938     // be used as immediates.
25939     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25940       return;
25941
25942     // If we are in non-pic codegen mode, we allow the address of a global (with
25943     // an optional displacement) to be used with 'i'.
25944     GlobalAddressSDNode *GA = nullptr;
25945     int64_t Offset = 0;
25946
25947     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25948     while (1) {
25949       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25950         Offset += GA->getOffset();
25951         break;
25952       } else if (Op.getOpcode() == ISD::ADD) {
25953         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25954           Offset += C->getZExtValue();
25955           Op = Op.getOperand(0);
25956           continue;
25957         }
25958       } else if (Op.getOpcode() == ISD::SUB) {
25959         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25960           Offset += -C->getZExtValue();
25961           Op = Op.getOperand(0);
25962           continue;
25963         }
25964       }
25965
25966       // Otherwise, this isn't something we can handle, reject it.
25967       return;
25968     }
25969
25970     const GlobalValue *GV = GA->getGlobal();
25971     // If we require an extra load to get this address, as in PIC mode, we
25972     // can't accept it.
25973     if (isGlobalStubReference(
25974             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25975       return;
25976
25977     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25978                                         GA->getValueType(0), Offset);
25979     break;
25980   }
25981   }
25982
25983   if (Result.getNode()) {
25984     Ops.push_back(Result);
25985     return;
25986   }
25987   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25988 }
25989
25990 std::pair<unsigned, const TargetRegisterClass *>
25991 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25992                                                 StringRef Constraint,
25993                                                 MVT VT) const {
25994   // First, see if this is a constraint that directly corresponds to an LLVM
25995   // register class.
25996   if (Constraint.size() == 1) {
25997     // GCC Constraint Letters
25998     switch (Constraint[0]) {
25999     default: break;
26000       // TODO: Slight differences here in allocation order and leaving
26001       // RIP in the class. Do they matter any more here than they do
26002       // in the normal allocation?
26003     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
26004       if (Subtarget->is64Bit()) {
26005         if (VT == MVT::i32 || VT == MVT::f32)
26006           return std::make_pair(0U, &X86::GR32RegClass);
26007         if (VT == MVT::i16)
26008           return std::make_pair(0U, &X86::GR16RegClass);
26009         if (VT == MVT::i8 || VT == MVT::i1)
26010           return std::make_pair(0U, &X86::GR8RegClass);
26011         if (VT == MVT::i64 || VT == MVT::f64)
26012           return std::make_pair(0U, &X86::GR64RegClass);
26013         break;
26014       }
26015       // 32-bit fallthrough
26016     case 'Q':   // Q_REGS
26017       if (VT == MVT::i32 || VT == MVT::f32)
26018         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
26019       if (VT == MVT::i16)
26020         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
26021       if (VT == MVT::i8 || VT == MVT::i1)
26022         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
26023       if (VT == MVT::i64)
26024         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26025       break;
26026     case 'r':   // GENERAL_REGS
26027     case 'l':   // INDEX_REGS
26028       if (VT == MVT::i8 || VT == MVT::i1)
26029         return std::make_pair(0U, &X86::GR8RegClass);
26030       if (VT == MVT::i16)
26031         return std::make_pair(0U, &X86::GR16RegClass);
26032       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26033         return std::make_pair(0U, &X86::GR32RegClass);
26034       return std::make_pair(0U, &X86::GR64RegClass);
26035     case 'R':   // LEGACY_REGS
26036       if (VT == MVT::i8 || VT == MVT::i1)
26037         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26038       if (VT == MVT::i16)
26039         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26040       if (VT == MVT::i32 || !Subtarget->is64Bit())
26041         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26042       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26043     case 'f':  // FP Stack registers.
26044       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26045       // value to the correct fpstack register class.
26046       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26047         return std::make_pair(0U, &X86::RFP32RegClass);
26048       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26049         return std::make_pair(0U, &X86::RFP64RegClass);
26050       return std::make_pair(0U, &X86::RFP80RegClass);
26051     case 'y':   // MMX_REGS if MMX allowed.
26052       if (!Subtarget->hasMMX()) break;
26053       return std::make_pair(0U, &X86::VR64RegClass);
26054     case 'Y':   // SSE_REGS if SSE2 allowed
26055       if (!Subtarget->hasSSE2()) break;
26056       // FALL THROUGH.
26057     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26058       if (!Subtarget->hasSSE1()) break;
26059
26060       switch (VT.SimpleTy) {
26061       default: break;
26062       // Scalar SSE types.
26063       case MVT::f32:
26064       case MVT::i32:
26065         return std::make_pair(0U, &X86::FR32RegClass);
26066       case MVT::f64:
26067       case MVT::i64:
26068         return std::make_pair(0U, &X86::FR64RegClass);
26069       // Vector types.
26070       case MVT::v16i8:
26071       case MVT::v8i16:
26072       case MVT::v4i32:
26073       case MVT::v2i64:
26074       case MVT::v4f32:
26075       case MVT::v2f64:
26076         return std::make_pair(0U, &X86::VR128RegClass);
26077       // AVX types.
26078       case MVT::v32i8:
26079       case MVT::v16i16:
26080       case MVT::v8i32:
26081       case MVT::v4i64:
26082       case MVT::v8f32:
26083       case MVT::v4f64:
26084         return std::make_pair(0U, &X86::VR256RegClass);
26085       case MVT::v8f64:
26086       case MVT::v16f32:
26087       case MVT::v16i32:
26088       case MVT::v8i64:
26089         return std::make_pair(0U, &X86::VR512RegClass);
26090       }
26091       break;
26092     }
26093   }
26094
26095   // Use the default implementation in TargetLowering to convert the register
26096   // constraint into a member of a register class.
26097   std::pair<unsigned, const TargetRegisterClass*> Res;
26098   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26099
26100   // Not found as a standard register?
26101   if (!Res.second) {
26102     // Map st(0) -> st(7) -> ST0
26103     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26104         tolower(Constraint[1]) == 's' &&
26105         tolower(Constraint[2]) == 't' &&
26106         Constraint[3] == '(' &&
26107         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26108         Constraint[5] == ')' &&
26109         Constraint[6] == '}') {
26110
26111       Res.first = X86::FP0+Constraint[4]-'0';
26112       Res.second = &X86::RFP80RegClass;
26113       return Res;
26114     }
26115
26116     // GCC allows "st(0)" to be called just plain "st".
26117     if (StringRef("{st}").equals_lower(Constraint)) {
26118       Res.first = X86::FP0;
26119       Res.second = &X86::RFP80RegClass;
26120       return Res;
26121     }
26122
26123     // flags -> EFLAGS
26124     if (StringRef("{flags}").equals_lower(Constraint)) {
26125       Res.first = X86::EFLAGS;
26126       Res.second = &X86::CCRRegClass;
26127       return Res;
26128     }
26129
26130     // 'A' means EAX + EDX.
26131     if (Constraint == "A") {
26132       Res.first = X86::EAX;
26133       Res.second = &X86::GR32_ADRegClass;
26134       return Res;
26135     }
26136     return Res;
26137   }
26138
26139   // Otherwise, check to see if this is a register class of the wrong value
26140   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26141   // turn into {ax},{dx}.
26142   // MVT::Other is used to specify clobber names.
26143   if (Res.second->hasType(VT) || VT == MVT::Other)
26144     return Res;   // Correct type already, nothing to do.
26145
26146   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26147   // return "eax". This should even work for things like getting 64bit integer
26148   // registers when given an f64 type.
26149   const TargetRegisterClass *Class = Res.second;
26150   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26151       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26152     unsigned Size = VT.getSizeInBits();
26153     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26154                                   : Size == 16 ? MVT::i16
26155                                   : Size == 32 ? MVT::i32
26156                                   : Size == 64 ? MVT::i64
26157                                   : MVT::Other;
26158     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26159     if (DestReg > 0) {
26160       Res.first = DestReg;
26161       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26162                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26163                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26164                  : &X86::GR64RegClass;
26165       assert(Res.second->contains(Res.first) && "Register in register class");
26166     } else {
26167       // No register found/type mismatch.
26168       Res.first = 0;
26169       Res.second = nullptr;
26170     }
26171   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26172              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26173              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26174              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26175              Class == &X86::VR512RegClass) {
26176     // Handle references to XMM physical registers that got mapped into the
26177     // wrong class.  This can happen with constraints like {xmm0} where the
26178     // target independent register mapper will just pick the first match it can
26179     // find, ignoring the required type.
26180
26181     if (VT == MVT::f32 || VT == MVT::i32)
26182       Res.second = &X86::FR32RegClass;
26183     else if (VT == MVT::f64 || VT == MVT::i64)
26184       Res.second = &X86::FR64RegClass;
26185     else if (X86::VR128RegClass.hasType(VT))
26186       Res.second = &X86::VR128RegClass;
26187     else if (X86::VR256RegClass.hasType(VT))
26188       Res.second = &X86::VR256RegClass;
26189     else if (X86::VR512RegClass.hasType(VT))
26190       Res.second = &X86::VR512RegClass;
26191     else {
26192       // Type mismatch and not a clobber: Return an error;
26193       Res.first = 0;
26194       Res.second = nullptr;
26195     }
26196   }
26197
26198   return Res;
26199 }
26200
26201 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26202                                             const AddrMode &AM, Type *Ty,
26203                                             unsigned AS) const {
26204   // Scaling factors are not free at all.
26205   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26206   // will take 2 allocations in the out of order engine instead of 1
26207   // for plain addressing mode, i.e. inst (reg1).
26208   // E.g.,
26209   // vaddps (%rsi,%drx), %ymm0, %ymm1
26210   // Requires two allocations (one for the load, one for the computation)
26211   // whereas:
26212   // vaddps (%rsi), %ymm0, %ymm1
26213   // Requires just 1 allocation, i.e., freeing allocations for other operations
26214   // and having less micro operations to execute.
26215   //
26216   // For some X86 architectures, this is even worse because for instance for
26217   // stores, the complex addressing mode forces the instruction to use the
26218   // "load" ports instead of the dedicated "store" port.
26219   // E.g., on Haswell:
26220   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26221   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26222   if (isLegalAddressingMode(DL, AM, Ty, AS))
26223     // Scale represents reg2 * scale, thus account for 1
26224     // as soon as we use a second register.
26225     return AM.Scale != 0;
26226   return -1;
26227 }
26228
26229 bool X86TargetLowering::isTargetFTOL() const {
26230   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26231 }