Fix spelling. NFCI.
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = TM.getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(*TD), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v2i64, Custom);
1036     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1037   }
1038
1039   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1040     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1041     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1045     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1046
1047     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1049     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1050
1051     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1055     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1056     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1057     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1058     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1059     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1061     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1062     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1063
1064     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1068     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1069     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1070     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1071     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1072     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1074     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1075     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1076
1077     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1078     // even though v8i16 is a legal type.
1079     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1081     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1082
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1084     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1085     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1086
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1088     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1089
1090     for (MVT VT : MVT::fp_vector_valuetypes())
1091       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1092
1093     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1094     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1095
1096     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1097     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1098
1099     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1100     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1101
1102     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1105     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1106
1107     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1109     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1110
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1113     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1116     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1119     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1122     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1123
1124     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1127     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1128
1129     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1130       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1133       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1135       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1136     }
1137
1138     if (Subtarget->hasInt256()) {
1139       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1142       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1143
1144       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1147       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1148
1149       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1150       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1152       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1153
1154       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1156       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1157       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1158
1159       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1161       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1164       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1167       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1170       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1171
1172       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1173       // when we have a 256bit-wide blend with immediate.
1174       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1175
1176       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1182       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1183
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1189       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1190     } else {
1191       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1194       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1195
1196       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1199       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1200
1201       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1204       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1205     }
1206
1207     // In the customized shift lowering, the legal cases in AVX2 will be
1208     // recognized.
1209     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1210     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1211
1212     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1213     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1214
1215     setOperationAction(ISD::SRA,               MVT::v4i64, Custom);
1216     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1217
1218     // Custom lower several nodes for 256-bit types.
1219     for (MVT VT : MVT::vector_valuetypes()) {
1220       if (VT.getScalarSizeInBits() >= 32) {
1221         setOperationAction(ISD::MLOAD,  VT, Legal);
1222         setOperationAction(ISD::MSTORE, VT, Legal);
1223       }
1224       // Extract subvector is special because the value type
1225       // (result) is 128-bit but the source is 256-bit wide.
1226       if (VT.is128BitVector()) {
1227         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1228       }
1229       // Do not attempt to custom lower other non-256-bit vectors
1230       if (!VT.is256BitVector())
1231         continue;
1232
1233       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1234       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1235       setOperationAction(ISD::VSELECT,            VT, Custom);
1236       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1237       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1238       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1239       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1240       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1241     }
1242
1243     if (Subtarget->hasInt256())
1244       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1245
1246
1247     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1248     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1249       MVT VT = (MVT::SimpleValueType)i;
1250
1251       // Do not attempt to promote non-256-bit vectors
1252       if (!VT.is256BitVector())
1253         continue;
1254
1255       setOperationAction(ISD::AND,    VT, Promote);
1256       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1257       setOperationAction(ISD::OR,     VT, Promote);
1258       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1259       setOperationAction(ISD::XOR,    VT, Promote);
1260       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1261       setOperationAction(ISD::LOAD,   VT, Promote);
1262       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1263       setOperationAction(ISD::SELECT, VT, Promote);
1264       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1265     }
1266   }
1267
1268   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1269     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1270     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1271     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1272     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1273
1274     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1275     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1276     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1277
1278     for (MVT VT : MVT::fp_vector_valuetypes())
1279       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1280
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1291     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1292     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1293
1294     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1295     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1296     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1297     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1298     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1299     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1300     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1301     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1302     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1305     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1306     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1307
1308     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1311     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1312     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1313     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1314
1315     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1318     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1319     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1320     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1321     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1322     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1323
1324     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1325     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1326     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1327     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1328     if (Subtarget->is64Bit()) {
1329       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1330       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1331       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1332       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1333     }
1334     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1336     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1337     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1341     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1342     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1346     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1347     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1348     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1349     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1350
1351     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1352     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1353     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1354     if (Subtarget->hasDQI()) {
1355       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1356       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1357     }
1358     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1359     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1360     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1361     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1362     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1363     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1364     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1368     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1369     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1370     if (Subtarget->hasDQI()) {
1371       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1372       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1373     }
1374     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1375     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1376     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1377     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1378     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1379     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1380     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1381     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1382     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1383     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1384
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1388     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1389     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1390
1391     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1392     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1393
1394     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1395
1396     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1397     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1398     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1399     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1400     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1401     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1405     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1406     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1407
1408     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1409     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1410     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1411     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1412     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1413     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1414     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1415     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1416
1417     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1418     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1419
1420     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1421     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1424
1425     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1426     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1427
1428     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1429     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1430
1431     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1432     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1433
1434     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1436     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1437     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1438     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1439     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1440
1441     if (Subtarget->hasCDI()) {
1442       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1443       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1444     }
1445     if (Subtarget->hasDQI()) {
1446       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1447       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1448       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1449     }
1450     // Custom lower several nodes.
1451     for (MVT VT : MVT::vector_valuetypes()) {
1452       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1453       if (EltSize == 1) {
1454         setOperationAction(ISD::AND, VT, Legal);
1455         setOperationAction(ISD::OR,  VT, Legal);
1456         setOperationAction(ISD::XOR,  VT, Legal);
1457       }
1458       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1459         setOperationAction(ISD::MGATHER,  VT, Custom);
1460         setOperationAction(ISD::MSCATTER, VT, Custom);
1461       }
1462       // Extract subvector is special because the value type
1463       // (result) is 256/128-bit but the source is 512-bit wide.
1464       if (VT.is128BitVector() || VT.is256BitVector()) {
1465         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1466       }
1467       if (VT.getVectorElementType() == MVT::i1)
1468         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1469
1470       // Do not attempt to custom lower other non-512-bit vectors
1471       if (!VT.is512BitVector())
1472         continue;
1473
1474       if (EltSize >= 32) {
1475         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1476         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1477         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1478         setOperationAction(ISD::VSELECT,             VT, Legal);
1479         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1480         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1481         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1482         setOperationAction(ISD::MLOAD,               VT, Legal);
1483         setOperationAction(ISD::MSTORE,              VT, Legal);
1484       }
1485     }
1486     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1487       MVT VT = (MVT::SimpleValueType)i;
1488
1489       // Do not attempt to promote non-512-bit vectors.
1490       if (!VT.is512BitVector())
1491         continue;
1492
1493       setOperationAction(ISD::SELECT, VT, Promote);
1494       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1495     }
1496   }// has  AVX-512
1497
1498   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1499     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1500     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1501
1502     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1503     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1504
1505     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1506     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1507     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1508     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1509     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1510     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1511     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1512     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1513     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1514     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1515     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1516     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1517     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1518     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1519     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1520     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1521     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1522     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1525     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1526     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1527     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1528     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1529     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1530     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1531     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1532     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1533     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1534
1535     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1536     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1539     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1540     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1541     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1542     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1543
1544     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1545       const MVT VT = (MVT::SimpleValueType)i;
1546
1547       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1548
1549       // Do not attempt to promote non-512-bit vectors.
1550       if (!VT.is512BitVector())
1551         continue;
1552
1553       if (EltSize < 32) {
1554         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1555         setOperationAction(ISD::VSELECT,             VT, Legal);
1556       }
1557     }
1558   }
1559
1560   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1561     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1562     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1563
1564     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1565     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1566     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1567     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1568     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1569     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1570     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1571     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1572     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1573     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1574
1575     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1576     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1577     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1578     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1579     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1580     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1581     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1582     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1583
1584     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1585     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1586     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1587     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1588     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1589     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1590     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1591     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1592   }
1593
1594   // We want to custom lower some of our intrinsics.
1595   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1596   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1597   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1598   if (!Subtarget->is64Bit())
1599     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1600
1601   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1602   // handle type legalization for these operations here.
1603   //
1604   // FIXME: We really should do custom legalization for addition and
1605   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1606   // than generic legalization for 64-bit multiplication-with-overflow, though.
1607   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1608     // Add/Sub/Mul with overflow operations are custom lowered.
1609     MVT VT = IntVTs[i];
1610     setOperationAction(ISD::SADDO, VT, Custom);
1611     setOperationAction(ISD::UADDO, VT, Custom);
1612     setOperationAction(ISD::SSUBO, VT, Custom);
1613     setOperationAction(ISD::USUBO, VT, Custom);
1614     setOperationAction(ISD::SMULO, VT, Custom);
1615     setOperationAction(ISD::UMULO, VT, Custom);
1616   }
1617
1618
1619   if (!Subtarget->is64Bit()) {
1620     // These libcalls are not available in 32-bit.
1621     setLibcallName(RTLIB::SHL_I128, nullptr);
1622     setLibcallName(RTLIB::SRL_I128, nullptr);
1623     setLibcallName(RTLIB::SRA_I128, nullptr);
1624   }
1625
1626   // Combine sin / cos into one node or libcall if possible.
1627   if (Subtarget->hasSinCos()) {
1628     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1629     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1630     if (Subtarget->isTargetDarwin()) {
1631       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1632       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1633       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1634       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1635     }
1636   }
1637
1638   if (Subtarget->isTargetWin64()) {
1639     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1640     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1641     setOperationAction(ISD::SREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UREM, MVT::i128, Custom);
1643     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1644     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1645   }
1646
1647   // We have target-specific dag combine patterns for the following nodes:
1648   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1649   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1650   setTargetDAGCombine(ISD::BITCAST);
1651   setTargetDAGCombine(ISD::VSELECT);
1652   setTargetDAGCombine(ISD::SELECT);
1653   setTargetDAGCombine(ISD::SHL);
1654   setTargetDAGCombine(ISD::SRA);
1655   setTargetDAGCombine(ISD::SRL);
1656   setTargetDAGCombine(ISD::OR);
1657   setTargetDAGCombine(ISD::AND);
1658   setTargetDAGCombine(ISD::ADD);
1659   setTargetDAGCombine(ISD::FADD);
1660   setTargetDAGCombine(ISD::FSUB);
1661   setTargetDAGCombine(ISD::FMA);
1662   setTargetDAGCombine(ISD::SUB);
1663   setTargetDAGCombine(ISD::LOAD);
1664   setTargetDAGCombine(ISD::MLOAD);
1665   setTargetDAGCombine(ISD::STORE);
1666   setTargetDAGCombine(ISD::MSTORE);
1667   setTargetDAGCombine(ISD::ZERO_EXTEND);
1668   setTargetDAGCombine(ISD::ANY_EXTEND);
1669   setTargetDAGCombine(ISD::SIGN_EXTEND);
1670   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1671   setTargetDAGCombine(ISD::SINT_TO_FP);
1672   setTargetDAGCombine(ISD::UINT_TO_FP);
1673   setTargetDAGCombine(ISD::SETCC);
1674   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1675   setTargetDAGCombine(ISD::BUILD_VECTOR);
1676   setTargetDAGCombine(ISD::MUL);
1677   setTargetDAGCombine(ISD::XOR);
1678
1679   computeRegisterProperties(Subtarget->getRegisterInfo());
1680
1681   // On Darwin, -Os means optimize for size without hurting performance,
1682   // do not reduce the limit.
1683   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1684   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1685   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1686   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1688   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1689   setPrefLoopAlignment(4); // 2^4 bytes.
1690
1691   // Predictable cmov don't hurt on atom because it's in-order.
1692   PredictableSelectIsExpensive = !Subtarget->isAtom();
1693   EnableExtLdPromotion = true;
1694   setPrefFunctionAlignment(4); // 2^4 bytes.
1695
1696   verifyIntrinsicTables();
1697 }
1698
1699 // This has so far only been implemented for 64-bit MachO.
1700 bool X86TargetLowering::useLoadStackGuardNode() const {
1701   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1702 }
1703
1704 TargetLoweringBase::LegalizeTypeAction
1705 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1706   if (ExperimentalVectorWideningLegalization &&
1707       VT.getVectorNumElements() != 1 &&
1708       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1709     return TypeWidenVector;
1710
1711   return TargetLoweringBase::getPreferredVectorAction(VT);
1712 }
1713
1714 EVT X86TargetLowering::getSetCCResultType(const DataLayout &DL, LLVMContext &,
1715                                           EVT VT) const {
1716   if (!VT.isVector())
1717     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1718
1719   const unsigned NumElts = VT.getVectorNumElements();
1720   const EVT EltVT = VT.getVectorElementType();
1721   if (VT.is512BitVector()) {
1722     if (Subtarget->hasAVX512())
1723       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1724           EltVT == MVT::f32 || EltVT == MVT::f64)
1725         switch(NumElts) {
1726         case  8: return MVT::v8i1;
1727         case 16: return MVT::v16i1;
1728       }
1729     if (Subtarget->hasBWI())
1730       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1731         switch(NumElts) {
1732         case 32: return MVT::v32i1;
1733         case 64: return MVT::v64i1;
1734       }
1735   }
1736
1737   if (VT.is256BitVector() || VT.is128BitVector()) {
1738     if (Subtarget->hasVLX())
1739       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1740           EltVT == MVT::f32 || EltVT == MVT::f64)
1741         switch(NumElts) {
1742         case 2: return MVT::v2i1;
1743         case 4: return MVT::v4i1;
1744         case 8: return MVT::v8i1;
1745       }
1746     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1747       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1748         switch(NumElts) {
1749         case  8: return MVT::v8i1;
1750         case 16: return MVT::v16i1;
1751         case 32: return MVT::v32i1;
1752       }
1753   }
1754
1755   return VT.changeVectorElementTypeToInteger();
1756 }
1757
1758 /// Helper for getByValTypeAlignment to determine
1759 /// the desired ByVal argument alignment.
1760 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1761   if (MaxAlign == 16)
1762     return;
1763   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1764     if (VTy->getBitWidth() == 128)
1765       MaxAlign = 16;
1766   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1767     unsigned EltAlign = 0;
1768     getMaxByValAlign(ATy->getElementType(), EltAlign);
1769     if (EltAlign > MaxAlign)
1770       MaxAlign = EltAlign;
1771   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1772     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1773       unsigned EltAlign = 0;
1774       getMaxByValAlign(STy->getElementType(i), EltAlign);
1775       if (EltAlign > MaxAlign)
1776         MaxAlign = EltAlign;
1777       if (MaxAlign == 16)
1778         break;
1779     }
1780   }
1781 }
1782
1783 /// Return the desired alignment for ByVal aggregate
1784 /// function arguments in the caller parameter area. For X86, aggregates
1785 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1786 /// are at 4-byte boundaries.
1787 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty,
1788                                                   const DataLayout &DL) const {
1789   if (Subtarget->is64Bit()) {
1790     // Max of 8 and alignment of type.
1791     unsigned TyAlign = DL.getABITypeAlignment(Ty);
1792     if (TyAlign > 8)
1793       return TyAlign;
1794     return 8;
1795   }
1796
1797   unsigned Align = 4;
1798   if (Subtarget->hasSSE1())
1799     getMaxByValAlign(Ty, Align);
1800   return Align;
1801 }
1802
1803 /// Returns the target specific optimal type for load
1804 /// and store operations as a result of memset, memcpy, and memmove
1805 /// lowering. If DstAlign is zero that means it's safe to destination
1806 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1807 /// means there isn't a need to check it against alignment requirement,
1808 /// probably because the source does not need to be loaded. If 'IsMemset' is
1809 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1810 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1811 /// source is constant so it does not need to be loaded.
1812 /// It returns EVT::Other if the type should be determined using generic
1813 /// target-independent logic.
1814 EVT
1815 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1816                                        unsigned DstAlign, unsigned SrcAlign,
1817                                        bool IsMemset, bool ZeroMemset,
1818                                        bool MemcpyStrSrc,
1819                                        MachineFunction &MF) const {
1820   const Function *F = MF.getFunction();
1821   if ((!IsMemset || ZeroMemset) &&
1822       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1823     if (Size >= 16 &&
1824         (Subtarget->isUnalignedMemAccessFast() ||
1825          ((DstAlign == 0 || DstAlign >= 16) &&
1826           (SrcAlign == 0 || SrcAlign >= 16)))) {
1827       if (Size >= 32) {
1828         if (Subtarget->hasInt256())
1829           return MVT::v8i32;
1830         if (Subtarget->hasFp256())
1831           return MVT::v8f32;
1832       }
1833       if (Subtarget->hasSSE2())
1834         return MVT::v4i32;
1835       if (Subtarget->hasSSE1())
1836         return MVT::v4f32;
1837     } else if (!MemcpyStrSrc && Size >= 8 &&
1838                !Subtarget->is64Bit() &&
1839                Subtarget->hasSSE2()) {
1840       // Do not use f64 to lower memcpy if source is string constant. It's
1841       // better to use i32 to avoid the loads.
1842       return MVT::f64;
1843     }
1844   }
1845   if (Subtarget->is64Bit() && Size >= 8)
1846     return MVT::i64;
1847   return MVT::i32;
1848 }
1849
1850 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1851   if (VT == MVT::f32)
1852     return X86ScalarSSEf32;
1853   else if (VT == MVT::f64)
1854     return X86ScalarSSEf64;
1855   return true;
1856 }
1857
1858 bool
1859 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1860                                                   unsigned,
1861                                                   unsigned,
1862                                                   bool *Fast) const {
1863   if (Fast)
1864     *Fast = Subtarget->isUnalignedMemAccessFast();
1865   return true;
1866 }
1867
1868 /// Return the entry encoding for a jump table in the
1869 /// current function.  The returned value is a member of the
1870 /// MachineJumpTableInfo::JTEntryKind enum.
1871 unsigned X86TargetLowering::getJumpTableEncoding() const {
1872   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1873   // symbol.
1874   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1875       Subtarget->isPICStyleGOT())
1876     return MachineJumpTableInfo::EK_Custom32;
1877
1878   // Otherwise, use the normal jump table encoding heuristics.
1879   return TargetLowering::getJumpTableEncoding();
1880 }
1881
1882 bool X86TargetLowering::useSoftFloat() const {
1883   return Subtarget->useSoftFloat();
1884 }
1885
1886 const MCExpr *
1887 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1888                                              const MachineBasicBlock *MBB,
1889                                              unsigned uid,MCContext &Ctx) const{
1890   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1891          Subtarget->isPICStyleGOT());
1892   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1893   // entries.
1894   return MCSymbolRefExpr::create(MBB->getSymbol(),
1895                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1896 }
1897
1898 /// Returns relocation base for the given PIC jumptable.
1899 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1900                                                     SelectionDAG &DAG) const {
1901   if (!Subtarget->is64Bit())
1902     // This doesn't have SDLoc associated with it, but is not really the
1903     // same as a Register.
1904     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
1905                        getPointerTy(DAG.getDataLayout()));
1906   return Table;
1907 }
1908
1909 /// This returns the relocation base for the given PIC jumptable,
1910 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1911 const MCExpr *X86TargetLowering::
1912 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1913                              MCContext &Ctx) const {
1914   // X86-64 uses RIP relative addressing based on the jump table label.
1915   if (Subtarget->isPICStyleRIPRel())
1916     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1917
1918   // Otherwise, the reference is relative to the PIC base.
1919   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1920 }
1921
1922 std::pair<const TargetRegisterClass *, uint8_t>
1923 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1924                                            MVT VT) const {
1925   const TargetRegisterClass *RRC = nullptr;
1926   uint8_t Cost = 1;
1927   switch (VT.SimpleTy) {
1928   default:
1929     return TargetLowering::findRepresentativeClass(TRI, VT);
1930   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1931     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1932     break;
1933   case MVT::x86mmx:
1934     RRC = &X86::VR64RegClass;
1935     break;
1936   case MVT::f32: case MVT::f64:
1937   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1938   case MVT::v4f32: case MVT::v2f64:
1939   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1940   case MVT::v4f64:
1941     RRC = &X86::VR128RegClass;
1942     break;
1943   }
1944   return std::make_pair(RRC, Cost);
1945 }
1946
1947 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1948                                                unsigned &Offset) const {
1949   if (!Subtarget->isTargetLinux())
1950     return false;
1951
1952   if (Subtarget->is64Bit()) {
1953     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1954     Offset = 0x28;
1955     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1956       AddressSpace = 256;
1957     else
1958       AddressSpace = 257;
1959   } else {
1960     // %gs:0x14 on i386
1961     Offset = 0x14;
1962     AddressSpace = 256;
1963   }
1964   return true;
1965 }
1966
1967 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1968                                             unsigned DestAS) const {
1969   assert(SrcAS != DestAS && "Expected different address spaces!");
1970
1971   return SrcAS < 256 && DestAS < 256;
1972 }
1973
1974 //===----------------------------------------------------------------------===//
1975 //               Return Value Calling Convention Implementation
1976 //===----------------------------------------------------------------------===//
1977
1978 #include "X86GenCallingConv.inc"
1979
1980 bool
1981 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1982                                   MachineFunction &MF, bool isVarArg,
1983                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1984                         LLVMContext &Context) const {
1985   SmallVector<CCValAssign, 16> RVLocs;
1986   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1987   return CCInfo.CheckReturn(Outs, RetCC_X86);
1988 }
1989
1990 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1991   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1992   return ScratchRegs;
1993 }
1994
1995 SDValue
1996 X86TargetLowering::LowerReturn(SDValue Chain,
1997                                CallingConv::ID CallConv, bool isVarArg,
1998                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1999                                const SmallVectorImpl<SDValue> &OutVals,
2000                                SDLoc dl, SelectionDAG &DAG) const {
2001   MachineFunction &MF = DAG.getMachineFunction();
2002   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2003
2004   SmallVector<CCValAssign, 16> RVLocs;
2005   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2006   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2007
2008   SDValue Flag;
2009   SmallVector<SDValue, 6> RetOps;
2010   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2011   // Operand #1 = Bytes To Pop
2012   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2013                    MVT::i16));
2014
2015   // Copy the result values into the output registers.
2016   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2017     CCValAssign &VA = RVLocs[i];
2018     assert(VA.isRegLoc() && "Can only return in registers!");
2019     SDValue ValToCopy = OutVals[i];
2020     EVT ValVT = ValToCopy.getValueType();
2021
2022     // Promote values to the appropriate types.
2023     if (VA.getLocInfo() == CCValAssign::SExt)
2024       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2025     else if (VA.getLocInfo() == CCValAssign::ZExt)
2026       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027     else if (VA.getLocInfo() == CCValAssign::AExt) {
2028       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2029         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2030       else
2031         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2032     }
2033     else if (VA.getLocInfo() == CCValAssign::BCvt)
2034       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2035
2036     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2037            "Unexpected FP-extend for return value.");
2038
2039     // If this is x86-64, and we disabled SSE, we can't return FP values,
2040     // or SSE or MMX vectors.
2041     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2042          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2043           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2044       report_fatal_error("SSE register return with SSE disabled");
2045     }
2046     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2047     // llvm-gcc has never done it right and no one has noticed, so this
2048     // should be OK for now.
2049     if (ValVT == MVT::f64 &&
2050         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2051       report_fatal_error("SSE2 register return with SSE2 disabled");
2052
2053     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2054     // the RET instruction and handled by the FP Stackifier.
2055     if (VA.getLocReg() == X86::FP0 ||
2056         VA.getLocReg() == X86::FP1) {
2057       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2058       // change the value to the FP stack register class.
2059       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2060         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2061       RetOps.push_back(ValToCopy);
2062       // Don't emit a copytoreg.
2063       continue;
2064     }
2065
2066     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2067     // which is returned in RAX / RDX.
2068     if (Subtarget->is64Bit()) {
2069       if (ValVT == MVT::x86mmx) {
2070         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2071           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2072           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2073                                   ValToCopy);
2074           // If we don't have SSE2 available, convert to v4f32 so the generated
2075           // register is legal.
2076           if (!Subtarget->hasSSE2())
2077             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2078         }
2079       }
2080     }
2081
2082     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2083     Flag = Chain.getValue(1);
2084     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2085   }
2086
2087   // All x86 ABIs require that for returning structs by value we copy
2088   // the sret argument into %rax/%eax (depending on ABI) for the return.
2089   // We saved the argument into a virtual register in the entry block,
2090   // so now we copy the value out and into %rax/%eax.
2091   //
2092   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2093   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2094   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2095   // either case FuncInfo->setSRetReturnReg() will have been called.
2096   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2097     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg,
2098                                      getPointerTy(MF.getDataLayout()));
2099
2100     unsigned RetValReg
2101         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2102           X86::RAX : X86::EAX;
2103     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2104     Flag = Chain.getValue(1);
2105
2106     // RAX/EAX now acts like a return value.
2107     RetOps.push_back(
2108         DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
2109   }
2110
2111   RetOps[0] = Chain;  // Update chain.
2112
2113   // Add the flag if we have it.
2114   if (Flag.getNode())
2115     RetOps.push_back(Flag);
2116
2117   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2118 }
2119
2120 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2121   if (N->getNumValues() != 1)
2122     return false;
2123   if (!N->hasNUsesOfValue(1, 0))
2124     return false;
2125
2126   SDValue TCChain = Chain;
2127   SDNode *Copy = *N->use_begin();
2128   if (Copy->getOpcode() == ISD::CopyToReg) {
2129     // If the copy has a glue operand, we conservatively assume it isn't safe to
2130     // perform a tail call.
2131     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2132       return false;
2133     TCChain = Copy->getOperand(0);
2134   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2135     return false;
2136
2137   bool HasRet = false;
2138   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2139        UI != UE; ++UI) {
2140     if (UI->getOpcode() != X86ISD::RET_FLAG)
2141       return false;
2142     // If we are returning more than one value, we can definitely
2143     // not make a tail call see PR19530
2144     if (UI->getNumOperands() > 4)
2145       return false;
2146     if (UI->getNumOperands() == 4 &&
2147         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2148       return false;
2149     HasRet = true;
2150   }
2151
2152   if (!HasRet)
2153     return false;
2154
2155   Chain = TCChain;
2156   return true;
2157 }
2158
2159 EVT
2160 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2161                                             ISD::NodeType ExtendKind) const {
2162   MVT ReturnMVT;
2163   // TODO: Is this also valid on 32-bit?
2164   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2165     ReturnMVT = MVT::i8;
2166   else
2167     ReturnMVT = MVT::i32;
2168
2169   EVT MinVT = getRegisterType(Context, ReturnMVT);
2170   return VT.bitsLT(MinVT) ? MinVT : VT;
2171 }
2172
2173 /// Lower the result values of a call into the
2174 /// appropriate copies out of appropriate physical registers.
2175 ///
2176 SDValue
2177 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2178                                    CallingConv::ID CallConv, bool isVarArg,
2179                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2180                                    SDLoc dl, SelectionDAG &DAG,
2181                                    SmallVectorImpl<SDValue> &InVals) const {
2182
2183   // Assign locations to each value returned by this call.
2184   SmallVector<CCValAssign, 16> RVLocs;
2185   bool Is64Bit = Subtarget->is64Bit();
2186   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2187                  *DAG.getContext());
2188   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2189
2190   // Copy all of the result registers out of their specified physreg.
2191   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2192     CCValAssign &VA = RVLocs[i];
2193     EVT CopyVT = VA.getLocVT();
2194
2195     // If this is x86-64, and we disabled SSE, we can't return FP values
2196     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2197         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2198       report_fatal_error("SSE register return with SSE disabled");
2199     }
2200
2201     // If we prefer to use the value in xmm registers, copy it out as f80 and
2202     // use a truncate to move it from fp stack reg to xmm reg.
2203     bool RoundAfterCopy = false;
2204     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2205         isScalarFPTypeInSSEReg(VA.getValVT())) {
2206       CopyVT = MVT::f80;
2207       RoundAfterCopy = (CopyVT != VA.getLocVT());
2208     }
2209
2210     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2211                                CopyVT, InFlag).getValue(1);
2212     SDValue Val = Chain.getValue(0);
2213
2214     if (RoundAfterCopy)
2215       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2216                         // This truncation won't change the value.
2217                         DAG.getIntPtrConstant(1, dl));
2218
2219     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2220       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2221
2222     InFlag = Chain.getValue(2);
2223     InVals.push_back(Val);
2224   }
2225
2226   return Chain;
2227 }
2228
2229 //===----------------------------------------------------------------------===//
2230 //                C & StdCall & Fast Calling Convention implementation
2231 //===----------------------------------------------------------------------===//
2232 //  StdCall calling convention seems to be standard for many Windows' API
2233 //  routines and around. It differs from C calling convention just a little:
2234 //  callee should clean up the stack, not caller. Symbols should be also
2235 //  decorated in some fancy way :) It doesn't support any vector arguments.
2236 //  For info on fast calling convention see Fast Calling Convention (tail call)
2237 //  implementation LowerX86_32FastCCCallTo.
2238
2239 /// CallIsStructReturn - Determines whether a call uses struct return
2240 /// semantics.
2241 enum StructReturnType {
2242   NotStructReturn,
2243   RegStructReturn,
2244   StackStructReturn
2245 };
2246 static StructReturnType
2247 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2248   if (Outs.empty())
2249     return NotStructReturn;
2250
2251   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2252   if (!Flags.isSRet())
2253     return NotStructReturn;
2254   if (Flags.isInReg())
2255     return RegStructReturn;
2256   return StackStructReturn;
2257 }
2258
2259 /// Determines whether a function uses struct return semantics.
2260 static StructReturnType
2261 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2262   if (Ins.empty())
2263     return NotStructReturn;
2264
2265   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2266   if (!Flags.isSRet())
2267     return NotStructReturn;
2268   if (Flags.isInReg())
2269     return RegStructReturn;
2270   return StackStructReturn;
2271 }
2272
2273 /// Make a copy of an aggregate at address specified by "Src" to address
2274 /// "Dst" with size and alignment information specified by the specific
2275 /// parameter attribute. The copy will be passed as a byval function parameter.
2276 static SDValue
2277 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2278                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2279                           SDLoc dl) {
2280   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2281
2282   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2283                        /*isVolatile*/false, /*AlwaysInline=*/true,
2284                        /*isTailCall*/false,
2285                        MachinePointerInfo(), MachinePointerInfo());
2286 }
2287
2288 /// Return true if the calling convention is one that
2289 /// supports tail call optimization.
2290 static bool IsTailCallConvention(CallingConv::ID CC) {
2291   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2292           CC == CallingConv::HiPE);
2293 }
2294
2295 /// \brief Return true if the calling convention is a C calling convention.
2296 static bool IsCCallConvention(CallingConv::ID CC) {
2297   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2298           CC == CallingConv::X86_64_SysV);
2299 }
2300
2301 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2302   auto Attr =
2303       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2304   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2305     return false;
2306
2307   CallSite CS(CI);
2308   CallingConv::ID CalleeCC = CS.getCallingConv();
2309   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2310     return false;
2311
2312   return true;
2313 }
2314
2315 /// Return true if the function is being made into
2316 /// a tailcall target by changing its ABI.
2317 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2318                                    bool GuaranteedTailCallOpt) {
2319   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2320 }
2321
2322 SDValue
2323 X86TargetLowering::LowerMemArgument(SDValue Chain,
2324                                     CallingConv::ID CallConv,
2325                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2326                                     SDLoc dl, SelectionDAG &DAG,
2327                                     const CCValAssign &VA,
2328                                     MachineFrameInfo *MFI,
2329                                     unsigned i) const {
2330   // Create the nodes corresponding to a load from this parameter slot.
2331   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2332   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2333       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2334   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2335   EVT ValVT;
2336
2337   // If value is passed by pointer we have address passed instead of the value
2338   // itself.
2339   bool ExtendedInMem = VA.isExtInLoc() &&
2340     VA.getValVT().getScalarType() == MVT::i1;
2341
2342   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2343     ValVT = VA.getLocVT();
2344   else
2345     ValVT = VA.getValVT();
2346
2347   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2348   // changed with more analysis.
2349   // In case of tail call optimization mark all arguments mutable. Since they
2350   // could be overwritten by lowering of arguments in case of a tail call.
2351   if (Flags.isByVal()) {
2352     unsigned Bytes = Flags.getByValSize();
2353     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2354     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2355     return DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2356   } else {
2357     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2358                                     VA.getLocMemOffset(), isImmutable);
2359     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2360     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2361                                MachinePointerInfo::getFixedStack(FI),
2362                                false, false, false, 0);
2363     return ExtendedInMem ?
2364       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2365   }
2366 }
2367
2368 // FIXME: Get this from tablegen.
2369 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2370                                                 const X86Subtarget *Subtarget) {
2371   assert(Subtarget->is64Bit());
2372
2373   if (Subtarget->isCallingConvWin64(CallConv)) {
2374     static const MCPhysReg GPR64ArgRegsWin64[] = {
2375       X86::RCX, X86::RDX, X86::R8,  X86::R9
2376     };
2377     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2378   }
2379
2380   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2381     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2382   };
2383   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2384 }
2385
2386 // FIXME: Get this from tablegen.
2387 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2388                                                 CallingConv::ID CallConv,
2389                                                 const X86Subtarget *Subtarget) {
2390   assert(Subtarget->is64Bit());
2391   if (Subtarget->isCallingConvWin64(CallConv)) {
2392     // The XMM registers which might contain var arg parameters are shadowed
2393     // in their paired GPR.  So we only need to save the GPR to their home
2394     // slots.
2395     // TODO: __vectorcall will change this.
2396     return None;
2397   }
2398
2399   const Function *Fn = MF.getFunction();
2400   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2401   bool isSoftFloat = Subtarget->useSoftFloat();
2402   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2403          "SSE register cannot be used when SSE is disabled!");
2404   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2405     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2406     // registers.
2407     return None;
2408
2409   static const MCPhysReg XMMArgRegs64Bit[] = {
2410     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2411     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2412   };
2413   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2414 }
2415
2416 SDValue
2417 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2418                                         CallingConv::ID CallConv,
2419                                         bool isVarArg,
2420                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2421                                         SDLoc dl,
2422                                         SelectionDAG &DAG,
2423                                         SmallVectorImpl<SDValue> &InVals)
2424                                           const {
2425   MachineFunction &MF = DAG.getMachineFunction();
2426   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2427   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2428
2429   const Function* Fn = MF.getFunction();
2430   if (Fn->hasExternalLinkage() &&
2431       Subtarget->isTargetCygMing() &&
2432       Fn->getName() == "main")
2433     FuncInfo->setForceFramePointer(true);
2434
2435   MachineFrameInfo *MFI = MF.getFrameInfo();
2436   bool Is64Bit = Subtarget->is64Bit();
2437   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2438
2439   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2440          "Var args not supported with calling convention fastcc, ghc or hipe");
2441
2442   // Assign locations to all of the incoming arguments.
2443   SmallVector<CCValAssign, 16> ArgLocs;
2444   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2445
2446   // Allocate shadow area for Win64
2447   if (IsWin64)
2448     CCInfo.AllocateStack(32, 8);
2449
2450   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2451
2452   unsigned LastVal = ~0U;
2453   SDValue ArgValue;
2454   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2455     CCValAssign &VA = ArgLocs[i];
2456     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2457     // places.
2458     assert(VA.getValNo() != LastVal &&
2459            "Don't support value assigned to multiple locs yet");
2460     (void)LastVal;
2461     LastVal = VA.getValNo();
2462
2463     if (VA.isRegLoc()) {
2464       EVT RegVT = VA.getLocVT();
2465       const TargetRegisterClass *RC;
2466       if (RegVT == MVT::i32)
2467         RC = &X86::GR32RegClass;
2468       else if (Is64Bit && RegVT == MVT::i64)
2469         RC = &X86::GR64RegClass;
2470       else if (RegVT == MVT::f32)
2471         RC = &X86::FR32RegClass;
2472       else if (RegVT == MVT::f64)
2473         RC = &X86::FR64RegClass;
2474       else if (RegVT.is512BitVector())
2475         RC = &X86::VR512RegClass;
2476       else if (RegVT.is256BitVector())
2477         RC = &X86::VR256RegClass;
2478       else if (RegVT.is128BitVector())
2479         RC = &X86::VR128RegClass;
2480       else if (RegVT == MVT::x86mmx)
2481         RC = &X86::VR64RegClass;
2482       else if (RegVT == MVT::i1)
2483         RC = &X86::VK1RegClass;
2484       else if (RegVT == MVT::v8i1)
2485         RC = &X86::VK8RegClass;
2486       else if (RegVT == MVT::v16i1)
2487         RC = &X86::VK16RegClass;
2488       else if (RegVT == MVT::v32i1)
2489         RC = &X86::VK32RegClass;
2490       else if (RegVT == MVT::v64i1)
2491         RC = &X86::VK64RegClass;
2492       else
2493         llvm_unreachable("Unknown argument type!");
2494
2495       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2496       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2497
2498       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2499       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2500       // right size.
2501       if (VA.getLocInfo() == CCValAssign::SExt)
2502         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2503                                DAG.getValueType(VA.getValVT()));
2504       else if (VA.getLocInfo() == CCValAssign::ZExt)
2505         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2506                                DAG.getValueType(VA.getValVT()));
2507       else if (VA.getLocInfo() == CCValAssign::BCvt)
2508         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2509
2510       if (VA.isExtInLoc()) {
2511         // Handle MMX values passed in XMM regs.
2512         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2513           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2514         else
2515           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2516       }
2517     } else {
2518       assert(VA.isMemLoc());
2519       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2520     }
2521
2522     // If value is passed via pointer - do a load.
2523     if (VA.getLocInfo() == CCValAssign::Indirect)
2524       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2525                              MachinePointerInfo(), false, false, false, 0);
2526
2527     InVals.push_back(ArgValue);
2528   }
2529
2530   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2531     // All x86 ABIs require that for returning structs by value we copy the
2532     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2533     // the argument into a virtual register so that we can access it from the
2534     // return points.
2535     if (Ins[i].Flags.isSRet()) {
2536       unsigned Reg = FuncInfo->getSRetReturnReg();
2537       if (!Reg) {
2538         MVT PtrTy = getPointerTy(DAG.getDataLayout());
2539         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2540         FuncInfo->setSRetReturnReg(Reg);
2541       }
2542       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2543       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2544       break;
2545     }
2546   }
2547
2548   unsigned StackSize = CCInfo.getNextStackOffset();
2549   // Align stack specially for tail calls.
2550   if (FuncIsMadeTailCallSafe(CallConv,
2551                              MF.getTarget().Options.GuaranteedTailCallOpt))
2552     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2553
2554   // If the function takes variable number of arguments, make a frame index for
2555   // the start of the first vararg value... for expansion of llvm.va_start. We
2556   // can skip this if there are no va_start calls.
2557   if (MFI->hasVAStart() &&
2558       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2559                    CallConv != CallingConv::X86_ThisCall))) {
2560     FuncInfo->setVarArgsFrameIndex(
2561         MFI->CreateFixedObject(1, StackSize, true));
2562   }
2563
2564   MachineModuleInfo &MMI = MF.getMMI();
2565   const Function *WinEHParent = nullptr;
2566   if (MMI.hasWinEHFuncInfo(Fn))
2567     WinEHParent = MMI.getWinEHParent(Fn);
2568   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2569   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2570
2571   // Figure out if XMM registers are in use.
2572   assert(!(Subtarget->useSoftFloat() &&
2573            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2574          "SSE register cannot be used when SSE is disabled!");
2575
2576   // 64-bit calling conventions support varargs and register parameters, so we
2577   // have to do extra work to spill them in the prologue.
2578   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2579     // Find the first unallocated argument registers.
2580     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2581     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2582     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2583     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2584     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2585            "SSE register cannot be used when SSE is disabled!");
2586
2587     // Gather all the live in physical registers.
2588     SmallVector<SDValue, 6> LiveGPRs;
2589     SmallVector<SDValue, 8> LiveXMMRegs;
2590     SDValue ALVal;
2591     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2592       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2593       LiveGPRs.push_back(
2594           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2595     }
2596     if (!ArgXMMs.empty()) {
2597       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2598       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2599       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2600         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2601         LiveXMMRegs.push_back(
2602             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2603       }
2604     }
2605
2606     if (IsWin64) {
2607       // Get to the caller-allocated home save location.  Add 8 to account
2608       // for the return address.
2609       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2610       FuncInfo->setRegSaveFrameIndex(
2611           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2612       // Fixup to set vararg frame on shadow area (4 x i64).
2613       if (NumIntRegs < 4)
2614         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2615     } else {
2616       // For X86-64, if there are vararg parameters that are passed via
2617       // registers, then we must store them to their spots on the stack so
2618       // they may be loaded by deferencing the result of va_next.
2619       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2620       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2621       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2622           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2623     }
2624
2625     // Store the integer parameter registers.
2626     SmallVector<SDValue, 8> MemOps;
2627     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2628                                       getPointerTy(DAG.getDataLayout()));
2629     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2630     for (SDValue Val : LiveGPRs) {
2631       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2632                                 RSFIN, DAG.getIntPtrConstant(Offset, dl));
2633       SDValue Store =
2634         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2635                      MachinePointerInfo::getFixedStack(
2636                        FuncInfo->getRegSaveFrameIndex(), Offset),
2637                      false, false, 0);
2638       MemOps.push_back(Store);
2639       Offset += 8;
2640     }
2641
2642     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2643       // Now store the XMM (fp + vector) parameter registers.
2644       SmallVector<SDValue, 12> SaveXMMOps;
2645       SaveXMMOps.push_back(Chain);
2646       SaveXMMOps.push_back(ALVal);
2647       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2648                              FuncInfo->getRegSaveFrameIndex(), dl));
2649       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2650                              FuncInfo->getVarArgsFPOffset(), dl));
2651       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2652                         LiveXMMRegs.end());
2653       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2654                                    MVT::Other, SaveXMMOps));
2655     }
2656
2657     if (!MemOps.empty())
2658       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2659   } else if (IsWin64 && IsWinEHOutlined) {
2660     // Get to the caller-allocated home save location.  Add 8 to account
2661     // for the return address.
2662     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2663     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2664         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2665
2666     MMI.getWinEHFuncInfo(Fn)
2667         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2668         FuncInfo->getRegSaveFrameIndex();
2669
2670     // Store the second integer parameter (rdx) into rsp+16 relative to the
2671     // stack pointer at the entry of the function.
2672     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2673                                       getPointerTy(DAG.getDataLayout()));
2674     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2675     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2676     Chain = DAG.getStore(
2677         Val.getValue(1), dl, Val, RSFIN,
2678         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2679         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2680   }
2681
2682   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2683     // Find the largest legal vector type.
2684     MVT VecVT = MVT::Other;
2685     // FIXME: Only some x86_32 calling conventions support AVX512.
2686     if (Subtarget->hasAVX512() &&
2687         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2688                      CallConv == CallingConv::Intel_OCL_BI)))
2689       VecVT = MVT::v16f32;
2690     else if (Subtarget->hasAVX())
2691       VecVT = MVT::v8f32;
2692     else if (Subtarget->hasSSE2())
2693       VecVT = MVT::v4f32;
2694
2695     // We forward some GPRs and some vector types.
2696     SmallVector<MVT, 2> RegParmTypes;
2697     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2698     RegParmTypes.push_back(IntVT);
2699     if (VecVT != MVT::Other)
2700       RegParmTypes.push_back(VecVT);
2701
2702     // Compute the set of forwarded registers. The rest are scratch.
2703     SmallVectorImpl<ForwardedRegister> &Forwards =
2704         FuncInfo->getForwardedMustTailRegParms();
2705     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2706
2707     // Conservatively forward AL on x86_64, since it might be used for varargs.
2708     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2709       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2710       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2711     }
2712
2713     // Copy all forwards from physical to virtual registers.
2714     for (ForwardedRegister &F : Forwards) {
2715       // FIXME: Can we use a less constrained schedule?
2716       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2717       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2718       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2719     }
2720   }
2721
2722   // Some CCs need callee pop.
2723   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2724                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2725     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2726   } else {
2727     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2728     // If this is an sret function, the return should pop the hidden pointer.
2729     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2730         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2731         argsAreStructReturn(Ins) == StackStructReturn)
2732       FuncInfo->setBytesToPopOnReturn(4);
2733   }
2734
2735   if (!Is64Bit) {
2736     // RegSaveFrameIndex is X86-64 only.
2737     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2738     if (CallConv == CallingConv::X86_FastCall ||
2739         CallConv == CallingConv::X86_ThisCall)
2740       // fastcc functions can't have varargs.
2741       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2742   }
2743
2744   FuncInfo->setArgumentStackSize(StackSize);
2745
2746   if (IsWinEHParent) {
2747     if (Is64Bit) {
2748       int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2749       SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2750       MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2751       SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2752       Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2753                            MachinePointerInfo::getFixedStack(UnwindHelpFI),
2754                            /*isVolatile=*/true,
2755                            /*isNonTemporal=*/false, /*Alignment=*/0);
2756     } else {
2757       // Functions using Win32 EH are considered to have opaque SP adjustments
2758       // to force local variables to be addressed from the frame or base
2759       // pointers.
2760       MFI->setHasOpaqueSPAdjustment(true);
2761     }
2762   }
2763
2764   return Chain;
2765 }
2766
2767 SDValue
2768 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2769                                     SDValue StackPtr, SDValue Arg,
2770                                     SDLoc dl, SelectionDAG &DAG,
2771                                     const CCValAssign &VA,
2772                                     ISD::ArgFlagsTy Flags) const {
2773   unsigned LocMemOffset = VA.getLocMemOffset();
2774   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2775   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
2776                        StackPtr, PtrOff);
2777   if (Flags.isByVal())
2778     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2779
2780   return DAG.getStore(Chain, dl, Arg, PtrOff,
2781                       MachinePointerInfo::getStack(LocMemOffset),
2782                       false, false, 0);
2783 }
2784
2785 /// Emit a load of return address if tail call
2786 /// optimization is performed and it is required.
2787 SDValue
2788 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2789                                            SDValue &OutRetAddr, SDValue Chain,
2790                                            bool IsTailCall, bool Is64Bit,
2791                                            int FPDiff, SDLoc dl) const {
2792   // Adjust the Return address stack slot.
2793   EVT VT = getPointerTy(DAG.getDataLayout());
2794   OutRetAddr = getReturnAddressFrameIndex(DAG);
2795
2796   // Load the "old" Return address.
2797   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2798                            false, false, false, 0);
2799   return SDValue(OutRetAddr.getNode(), 1);
2800 }
2801
2802 /// Emit a store of the return address if tail call
2803 /// optimization is performed and it is required (FPDiff!=0).
2804 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2805                                         SDValue Chain, SDValue RetAddrFrIdx,
2806                                         EVT PtrVT, unsigned SlotSize,
2807                                         int FPDiff, SDLoc dl) {
2808   // Store the return address to the appropriate stack slot.
2809   if (!FPDiff) return Chain;
2810   // Calculate the new stack slot for the return address.
2811   int NewReturnAddrFI =
2812     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2813                                          false);
2814   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2815   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2816                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2817                        false, false, 0);
2818   return Chain;
2819 }
2820
2821 SDValue
2822 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2823                              SmallVectorImpl<SDValue> &InVals) const {
2824   SelectionDAG &DAG                     = CLI.DAG;
2825   SDLoc &dl                             = CLI.DL;
2826   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2827   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2828   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2829   SDValue Chain                         = CLI.Chain;
2830   SDValue Callee                        = CLI.Callee;
2831   CallingConv::ID CallConv              = CLI.CallConv;
2832   bool &isTailCall                      = CLI.IsTailCall;
2833   bool isVarArg                         = CLI.IsVarArg;
2834
2835   MachineFunction &MF = DAG.getMachineFunction();
2836   bool Is64Bit        = Subtarget->is64Bit();
2837   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2838   StructReturnType SR = callIsStructReturn(Outs);
2839   bool IsSibcall      = false;
2840   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2841   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2842
2843   if (Attr.getValueAsString() == "true")
2844     isTailCall = false;
2845
2846   if (Subtarget->isPICStyleGOT() &&
2847       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2848     // If we are using a GOT, disable tail calls to external symbols with
2849     // default visibility. Tail calling such a symbol requires using a GOT
2850     // relocation, which forces early binding of the symbol. This breaks code
2851     // that require lazy function symbol resolution. Using musttail or
2852     // GuaranteedTailCallOpt will override this.
2853     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2854     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2855                G->getGlobal()->hasDefaultVisibility()))
2856       isTailCall = false;
2857   }
2858
2859   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2860   if (IsMustTail) {
2861     // Force this to be a tail call.  The verifier rules are enough to ensure
2862     // that we can lower this successfully without moving the return address
2863     // around.
2864     isTailCall = true;
2865   } else if (isTailCall) {
2866     // Check if it's really possible to do a tail call.
2867     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2868                     isVarArg, SR != NotStructReturn,
2869                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2870                     Outs, OutVals, Ins, DAG);
2871
2872     // Sibcalls are automatically detected tailcalls which do not require
2873     // ABI changes.
2874     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2875       IsSibcall = true;
2876
2877     if (isTailCall)
2878       ++NumTailCalls;
2879   }
2880
2881   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2882          "Var args not supported with calling convention fastcc, ghc or hipe");
2883
2884   // Analyze operands of the call, assigning locations to each operand.
2885   SmallVector<CCValAssign, 16> ArgLocs;
2886   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2887
2888   // Allocate shadow area for Win64
2889   if (IsWin64)
2890     CCInfo.AllocateStack(32, 8);
2891
2892   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2893
2894   // Get a count of how many bytes are to be pushed on the stack.
2895   unsigned NumBytes = CCInfo.getNextStackOffset();
2896   if (IsSibcall)
2897     // This is a sibcall. The memory operands are available in caller's
2898     // own caller's stack.
2899     NumBytes = 0;
2900   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2901            IsTailCallConvention(CallConv))
2902     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2903
2904   int FPDiff = 0;
2905   if (isTailCall && !IsSibcall && !IsMustTail) {
2906     // Lower arguments at fp - stackoffset + fpdiff.
2907     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2908
2909     FPDiff = NumBytesCallerPushed - NumBytes;
2910
2911     // Set the delta of movement of the returnaddr stackslot.
2912     // But only set if delta is greater than previous delta.
2913     if (FPDiff < X86Info->getTCReturnAddrDelta())
2914       X86Info->setTCReturnAddrDelta(FPDiff);
2915   }
2916
2917   unsigned NumBytesToPush = NumBytes;
2918   unsigned NumBytesToPop = NumBytes;
2919
2920   // If we have an inalloca argument, all stack space has already been allocated
2921   // for us and be right at the top of the stack.  We don't support multiple
2922   // arguments passed in memory when using inalloca.
2923   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2924     NumBytesToPush = 0;
2925     if (!ArgLocs.back().isMemLoc())
2926       report_fatal_error("cannot use inalloca attribute on a register "
2927                          "parameter");
2928     if (ArgLocs.back().getLocMemOffset() != 0)
2929       report_fatal_error("any parameter with the inalloca attribute must be "
2930                          "the only memory argument");
2931   }
2932
2933   if (!IsSibcall)
2934     Chain = DAG.getCALLSEQ_START(
2935         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2936
2937   SDValue RetAddrFrIdx;
2938   // Load return address for tail calls.
2939   if (isTailCall && FPDiff)
2940     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2941                                     Is64Bit, FPDiff, dl);
2942
2943   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2944   SmallVector<SDValue, 8> MemOpChains;
2945   SDValue StackPtr;
2946
2947   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2948   // of tail call optimization arguments are handle later.
2949   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2950   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2951     // Skip inalloca arguments, they have already been written.
2952     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2953     if (Flags.isInAlloca())
2954       continue;
2955
2956     CCValAssign &VA = ArgLocs[i];
2957     EVT RegVT = VA.getLocVT();
2958     SDValue Arg = OutVals[i];
2959     bool isByVal = Flags.isByVal();
2960
2961     // Promote the value if needed.
2962     switch (VA.getLocInfo()) {
2963     default: llvm_unreachable("Unknown loc info!");
2964     case CCValAssign::Full: break;
2965     case CCValAssign::SExt:
2966       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2967       break;
2968     case CCValAssign::ZExt:
2969       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2970       break;
2971     case CCValAssign::AExt:
2972       if (Arg.getValueType().isVector() &&
2973           Arg.getValueType().getScalarType() == MVT::i1)
2974         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2975       else if (RegVT.is128BitVector()) {
2976         // Special case: passing MMX values in XMM registers.
2977         Arg = DAG.getBitcast(MVT::i64, Arg);
2978         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2979         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2980       } else
2981         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2982       break;
2983     case CCValAssign::BCvt:
2984       Arg = DAG.getBitcast(RegVT, Arg);
2985       break;
2986     case CCValAssign::Indirect: {
2987       // Store the argument.
2988       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2989       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2990       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2991                            MachinePointerInfo::getFixedStack(FI),
2992                            false, false, 0);
2993       Arg = SpillSlot;
2994       break;
2995     }
2996     }
2997
2998     if (VA.isRegLoc()) {
2999       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3000       if (isVarArg && IsWin64) {
3001         // Win64 ABI requires argument XMM reg to be copied to the corresponding
3002         // shadow reg if callee is a varargs function.
3003         unsigned ShadowReg = 0;
3004         switch (VA.getLocReg()) {
3005         case X86::XMM0: ShadowReg = X86::RCX; break;
3006         case X86::XMM1: ShadowReg = X86::RDX; break;
3007         case X86::XMM2: ShadowReg = X86::R8; break;
3008         case X86::XMM3: ShadowReg = X86::R9; break;
3009         }
3010         if (ShadowReg)
3011           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
3012       }
3013     } else if (!IsSibcall && (!isTailCall || isByVal)) {
3014       assert(VA.isMemLoc());
3015       if (!StackPtr.getNode())
3016         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3017                                       getPointerTy(DAG.getDataLayout()));
3018       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3019                                              dl, DAG, VA, Flags));
3020     }
3021   }
3022
3023   if (!MemOpChains.empty())
3024     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3025
3026   if (Subtarget->isPICStyleGOT()) {
3027     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3028     // GOT pointer.
3029     if (!isTailCall) {
3030       RegsToPass.push_back(std::make_pair(
3031           unsigned(X86::EBX), DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(),
3032                                           getPointerTy(DAG.getDataLayout()))));
3033     } else {
3034       // If we are tail calling and generating PIC/GOT style code load the
3035       // address of the callee into ECX. The value in ecx is used as target of
3036       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3037       // for tail calls on PIC/GOT architectures. Normally we would just put the
3038       // address of GOT into ebx and then call target@PLT. But for tail calls
3039       // ebx would be restored (since ebx is callee saved) before jumping to the
3040       // target@PLT.
3041
3042       // Note: The actual moving to ECX is done further down.
3043       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3044       if (G && !G->getGlobal()->hasLocalLinkage() &&
3045           G->getGlobal()->hasDefaultVisibility())
3046         Callee = LowerGlobalAddress(Callee, DAG);
3047       else if (isa<ExternalSymbolSDNode>(Callee))
3048         Callee = LowerExternalSymbol(Callee, DAG);
3049     }
3050   }
3051
3052   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3053     // From AMD64 ABI document:
3054     // For calls that may call functions that use varargs or stdargs
3055     // (prototype-less calls or calls to functions containing ellipsis (...) in
3056     // the declaration) %al is used as hidden argument to specify the number
3057     // of SSE registers used. The contents of %al do not need to match exactly
3058     // the number of registers, but must be an ubound on the number of SSE
3059     // registers used and is in the range 0 - 8 inclusive.
3060
3061     // Count the number of XMM registers allocated.
3062     static const MCPhysReg XMMArgRegs[] = {
3063       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3064       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3065     };
3066     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3067     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3068            && "SSE registers cannot be used when SSE is disabled");
3069
3070     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3071                                         DAG.getConstant(NumXMMRegs, dl,
3072                                                         MVT::i8)));
3073   }
3074
3075   if (isVarArg && IsMustTail) {
3076     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3077     for (const auto &F : Forwards) {
3078       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3079       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3080     }
3081   }
3082
3083   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3084   // don't need this because the eligibility check rejects calls that require
3085   // shuffling arguments passed in memory.
3086   if (!IsSibcall && isTailCall) {
3087     // Force all the incoming stack arguments to be loaded from the stack
3088     // before any new outgoing arguments are stored to the stack, because the
3089     // outgoing stack slots may alias the incoming argument stack slots, and
3090     // the alias isn't otherwise explicit. This is slightly more conservative
3091     // than necessary, because it means that each store effectively depends
3092     // on every argument instead of just those arguments it would clobber.
3093     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3094
3095     SmallVector<SDValue, 8> MemOpChains2;
3096     SDValue FIN;
3097     int FI = 0;
3098     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3099       CCValAssign &VA = ArgLocs[i];
3100       if (VA.isRegLoc())
3101         continue;
3102       assert(VA.isMemLoc());
3103       SDValue Arg = OutVals[i];
3104       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3105       // Skip inalloca arguments.  They don't require any work.
3106       if (Flags.isInAlloca())
3107         continue;
3108       // Create frame index.
3109       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3110       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3111       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3112       FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3113
3114       if (Flags.isByVal()) {
3115         // Copy relative to framepointer.
3116         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3117         if (!StackPtr.getNode())
3118           StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3119                                         getPointerTy(DAG.getDataLayout()));
3120         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(DAG.getDataLayout()),
3121                              StackPtr, Source);
3122
3123         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3124                                                          ArgChain,
3125                                                          Flags, DAG, dl));
3126       } else {
3127         // Store relative to framepointer.
3128         MemOpChains2.push_back(
3129           DAG.getStore(ArgChain, dl, Arg, FIN,
3130                        MachinePointerInfo::getFixedStack(FI),
3131                        false, false, 0));
3132       }
3133     }
3134
3135     if (!MemOpChains2.empty())
3136       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3137
3138     // Store the return address to the appropriate stack slot.
3139     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3140                                      getPointerTy(DAG.getDataLayout()),
3141                                      RegInfo->getSlotSize(), FPDiff, dl);
3142   }
3143
3144   // Build a sequence of copy-to-reg nodes chained together with token chain
3145   // and flag operands which copy the outgoing args into registers.
3146   SDValue InFlag;
3147   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3148     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3149                              RegsToPass[i].second, InFlag);
3150     InFlag = Chain.getValue(1);
3151   }
3152
3153   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3154     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3155     // In the 64-bit large code model, we have to make all calls
3156     // through a register, since the call instruction's 32-bit
3157     // pc-relative offset may not be large enough to hold the whole
3158     // address.
3159   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3160     // If the callee is a GlobalAddress node (quite common, every direct call
3161     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3162     // it.
3163     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3164
3165     // We should use extra load for direct calls to dllimported functions in
3166     // non-JIT mode.
3167     const GlobalValue *GV = G->getGlobal();
3168     if (!GV->hasDLLImportStorageClass()) {
3169       unsigned char OpFlags = 0;
3170       bool ExtraLoad = false;
3171       unsigned WrapperKind = ISD::DELETED_NODE;
3172
3173       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3174       // external symbols most go through the PLT in PIC mode.  If the symbol
3175       // has hidden or protected visibility, or if it is static or local, then
3176       // we don't need to use the PLT - we can directly call it.
3177       if (Subtarget->isTargetELF() &&
3178           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3179           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3180         OpFlags = X86II::MO_PLT;
3181       } else if (Subtarget->isPICStyleStubAny() &&
3182                  !GV->isStrongDefinitionForLinker() &&
3183                  (!Subtarget->getTargetTriple().isMacOSX() ||
3184                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3185         // PC-relative references to external symbols should go through $stub,
3186         // unless we're building with the leopard linker or later, which
3187         // automatically synthesizes these stubs.
3188         OpFlags = X86II::MO_DARWIN_STUB;
3189       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3190                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3191         // If the function is marked as non-lazy, generate an indirect call
3192         // which loads from the GOT directly. This avoids runtime overhead
3193         // at the cost of eager binding (and one extra byte of encoding).
3194         OpFlags = X86II::MO_GOTPCREL;
3195         WrapperKind = X86ISD::WrapperRIP;
3196         ExtraLoad = true;
3197       }
3198
3199       Callee = DAG.getTargetGlobalAddress(
3200           GV, dl, getPointerTy(DAG.getDataLayout()), G->getOffset(), OpFlags);
3201
3202       // Add a wrapper if needed.
3203       if (WrapperKind != ISD::DELETED_NODE)
3204         Callee = DAG.getNode(X86ISD::WrapperRIP, dl,
3205                              getPointerTy(DAG.getDataLayout()), Callee);
3206       // Add extra indirection if needed.
3207       if (ExtraLoad)
3208         Callee = DAG.getLoad(
3209             getPointerTy(DAG.getDataLayout()), dl, DAG.getEntryNode(), Callee,
3210             MachinePointerInfo::getGOT(), false, false, false, 0);
3211     }
3212   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3213     unsigned char OpFlags = 0;
3214
3215     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3216     // external symbols should go through the PLT.
3217     if (Subtarget->isTargetELF() &&
3218         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3219       OpFlags = X86II::MO_PLT;
3220     } else if (Subtarget->isPICStyleStubAny() &&
3221                (!Subtarget->getTargetTriple().isMacOSX() ||
3222                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3223       // PC-relative references to external symbols should go through $stub,
3224       // unless we're building with the leopard linker or later, which
3225       // automatically synthesizes these stubs.
3226       OpFlags = X86II::MO_DARWIN_STUB;
3227     }
3228
3229     Callee = DAG.getTargetExternalSymbol(
3230         S->getSymbol(), getPointerTy(DAG.getDataLayout()), OpFlags);
3231   } else if (Subtarget->isTarget64BitILP32() &&
3232              Callee->getValueType(0) == MVT::i32) {
3233     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3234     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3235   }
3236
3237   // Returns a chain & a flag for retval copy to use.
3238   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3239   SmallVector<SDValue, 8> Ops;
3240
3241   if (!IsSibcall && isTailCall) {
3242     Chain = DAG.getCALLSEQ_END(Chain,
3243                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3244                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3245     InFlag = Chain.getValue(1);
3246   }
3247
3248   Ops.push_back(Chain);
3249   Ops.push_back(Callee);
3250
3251   if (isTailCall)
3252     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3253
3254   // Add argument registers to the end of the list so that they are known live
3255   // into the call.
3256   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3257     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3258                                   RegsToPass[i].second.getValueType()));
3259
3260   // Add a register mask operand representing the call-preserved registers.
3261   const uint32_t *Mask = RegInfo->getCallPreservedMask(MF, CallConv);
3262   assert(Mask && "Missing call preserved mask for calling convention");
3263
3264   // If this is an invoke in a 32-bit function using an MSVC personality, assume
3265   // the function clobbers all registers. If an exception is thrown, the runtime
3266   // will not restore CSRs.
3267   // FIXME: Model this more precisely so that we can register allocate across
3268   // the normal edge and spill and fill across the exceptional edge.
3269   if (!Is64Bit && CLI.CS && CLI.CS->isInvoke()) {
3270     const Function *CallerFn = MF.getFunction();
3271     EHPersonality Pers =
3272         CallerFn->hasPersonalityFn()
3273             ? classifyEHPersonality(CallerFn->getPersonalityFn())
3274             : EHPersonality::Unknown;
3275     if (isMSVCEHPersonality(Pers))
3276       Mask = RegInfo->getNoPreservedMask();
3277   }
3278
3279   Ops.push_back(DAG.getRegisterMask(Mask));
3280
3281   if (InFlag.getNode())
3282     Ops.push_back(InFlag);
3283
3284   if (isTailCall) {
3285     // We used to do:
3286     //// If this is the first return lowered for this function, add the regs
3287     //// to the liveout set for the function.
3288     // This isn't right, although it's probably harmless on x86; liveouts
3289     // should be computed from returns not tail calls.  Consider a void
3290     // function making a tail call to a function returning int.
3291     MF.getFrameInfo()->setHasTailCall();
3292     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3293   }
3294
3295   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3296   InFlag = Chain.getValue(1);
3297
3298   // Create the CALLSEQ_END node.
3299   unsigned NumBytesForCalleeToPop;
3300   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3301                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3302     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3303   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3304            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3305            SR == StackStructReturn)
3306     // If this is a call to a struct-return function, the callee
3307     // pops the hidden struct pointer, so we have to push it back.
3308     // This is common for Darwin/X86, Linux & Mingw32 targets.
3309     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3310     NumBytesForCalleeToPop = 4;
3311   else
3312     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3313
3314   // Returns a flag for retval copy to use.
3315   if (!IsSibcall) {
3316     Chain = DAG.getCALLSEQ_END(Chain,
3317                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3318                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3319                                                      true),
3320                                InFlag, dl);
3321     InFlag = Chain.getValue(1);
3322   }
3323
3324   // Handle result values, copying them out of physregs into vregs that we
3325   // return.
3326   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3327                          Ins, dl, DAG, InVals);
3328 }
3329
3330 //===----------------------------------------------------------------------===//
3331 //                Fast Calling Convention (tail call) implementation
3332 //===----------------------------------------------------------------------===//
3333
3334 //  Like std call, callee cleans arguments, convention except that ECX is
3335 //  reserved for storing the tail called function address. Only 2 registers are
3336 //  free for argument passing (inreg). Tail call optimization is performed
3337 //  provided:
3338 //                * tailcallopt is enabled
3339 //                * caller/callee are fastcc
3340 //  On X86_64 architecture with GOT-style position independent code only local
3341 //  (within module) calls are supported at the moment.
3342 //  To keep the stack aligned according to platform abi the function
3343 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3344 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3345 //  If a tail called function callee has more arguments than the caller the
3346 //  caller needs to make sure that there is room to move the RETADDR to. This is
3347 //  achieved by reserving an area the size of the argument delta right after the
3348 //  original RETADDR, but before the saved framepointer or the spilled registers
3349 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3350 //  stack layout:
3351 //    arg1
3352 //    arg2
3353 //    RETADDR
3354 //    [ new RETADDR
3355 //      move area ]
3356 //    (possible EBP)
3357 //    ESI
3358 //    EDI
3359 //    local1 ..
3360
3361 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3362 /// for a 16 byte align requirement.
3363 unsigned
3364 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3365                                                SelectionDAG& DAG) const {
3366   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3367   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3368   unsigned StackAlignment = TFI.getStackAlignment();
3369   uint64_t AlignMask = StackAlignment - 1;
3370   int64_t Offset = StackSize;
3371   unsigned SlotSize = RegInfo->getSlotSize();
3372   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3373     // Number smaller than 12 so just add the difference.
3374     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3375   } else {
3376     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3377     Offset = ((~AlignMask) & Offset) + StackAlignment +
3378       (StackAlignment-SlotSize);
3379   }
3380   return Offset;
3381 }
3382
3383 /// MatchingStackOffset - Return true if the given stack call argument is
3384 /// already available in the same position (relatively) of the caller's
3385 /// incoming argument stack.
3386 static
3387 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3388                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3389                          const X86InstrInfo *TII) {
3390   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3391   int FI = INT_MAX;
3392   if (Arg.getOpcode() == ISD::CopyFromReg) {
3393     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3394     if (!TargetRegisterInfo::isVirtualRegister(VR))
3395       return false;
3396     MachineInstr *Def = MRI->getVRegDef(VR);
3397     if (!Def)
3398       return false;
3399     if (!Flags.isByVal()) {
3400       if (!TII->isLoadFromStackSlot(Def, FI))
3401         return false;
3402     } else {
3403       unsigned Opcode = Def->getOpcode();
3404       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3405            Opcode == X86::LEA64_32r) &&
3406           Def->getOperand(1).isFI()) {
3407         FI = Def->getOperand(1).getIndex();
3408         Bytes = Flags.getByValSize();
3409       } else
3410         return false;
3411     }
3412   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3413     if (Flags.isByVal())
3414       // ByVal argument is passed in as a pointer but it's now being
3415       // dereferenced. e.g.
3416       // define @foo(%struct.X* %A) {
3417       //   tail call @bar(%struct.X* byval %A)
3418       // }
3419       return false;
3420     SDValue Ptr = Ld->getBasePtr();
3421     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3422     if (!FINode)
3423       return false;
3424     FI = FINode->getIndex();
3425   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3426     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3427     FI = FINode->getIndex();
3428     Bytes = Flags.getByValSize();
3429   } else
3430     return false;
3431
3432   assert(FI != INT_MAX);
3433   if (!MFI->isFixedObjectIndex(FI))
3434     return false;
3435   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3436 }
3437
3438 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3439 /// for tail call optimization. Targets which want to do tail call
3440 /// optimization should implement this function.
3441 bool
3442 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3443                                                      CallingConv::ID CalleeCC,
3444                                                      bool isVarArg,
3445                                                      bool isCalleeStructRet,
3446                                                      bool isCallerStructRet,
3447                                                      Type *RetTy,
3448                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3449                                     const SmallVectorImpl<SDValue> &OutVals,
3450                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3451                                                      SelectionDAG &DAG) const {
3452   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3453     return false;
3454
3455   // If -tailcallopt is specified, make fastcc functions tail-callable.
3456   const MachineFunction &MF = DAG.getMachineFunction();
3457   const Function *CallerF = MF.getFunction();
3458
3459   // If the function return type is x86_fp80 and the callee return type is not,
3460   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3461   // perform a tailcall optimization here.
3462   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3463     return false;
3464
3465   CallingConv::ID CallerCC = CallerF->getCallingConv();
3466   bool CCMatch = CallerCC == CalleeCC;
3467   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3468   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3469
3470   // Win64 functions have extra shadow space for argument homing. Don't do the
3471   // sibcall if the caller and callee have mismatched expectations for this
3472   // space.
3473   if (IsCalleeWin64 != IsCallerWin64)
3474     return false;
3475
3476   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3477     if (IsTailCallConvention(CalleeCC) && CCMatch)
3478       return true;
3479     return false;
3480   }
3481
3482   // Look for obvious safe cases to perform tail call optimization that do not
3483   // require ABI changes. This is what gcc calls sibcall.
3484
3485   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3486   // emit a special epilogue.
3487   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3488   if (RegInfo->needsStackRealignment(MF))
3489     return false;
3490
3491   // Also avoid sibcall optimization if either caller or callee uses struct
3492   // return semantics.
3493   if (isCalleeStructRet || isCallerStructRet)
3494     return false;
3495
3496   // An stdcall/thiscall caller is expected to clean up its arguments; the
3497   // callee isn't going to do that.
3498   // FIXME: this is more restrictive than needed. We could produce a tailcall
3499   // when the stack adjustment matches. For example, with a thiscall that takes
3500   // only one argument.
3501   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3502                    CallerCC == CallingConv::X86_ThisCall))
3503     return false;
3504
3505   // Do not sibcall optimize vararg calls unless all arguments are passed via
3506   // registers.
3507   if (isVarArg && !Outs.empty()) {
3508
3509     // Optimizing for varargs on Win64 is unlikely to be safe without
3510     // additional testing.
3511     if (IsCalleeWin64 || IsCallerWin64)
3512       return false;
3513
3514     SmallVector<CCValAssign, 16> ArgLocs;
3515     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3516                    *DAG.getContext());
3517
3518     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3519     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3520       if (!ArgLocs[i].isRegLoc())
3521         return false;
3522   }
3523
3524   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3525   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3526   // this into a sibcall.
3527   bool Unused = false;
3528   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3529     if (!Ins[i].Used) {
3530       Unused = true;
3531       break;
3532     }
3533   }
3534   if (Unused) {
3535     SmallVector<CCValAssign, 16> RVLocs;
3536     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3537                    *DAG.getContext());
3538     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3539     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3540       CCValAssign &VA = RVLocs[i];
3541       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3542         return false;
3543     }
3544   }
3545
3546   // If the calling conventions do not match, then we'd better make sure the
3547   // results are returned in the same way as what the caller expects.
3548   if (!CCMatch) {
3549     SmallVector<CCValAssign, 16> RVLocs1;
3550     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3551                     *DAG.getContext());
3552     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3553
3554     SmallVector<CCValAssign, 16> RVLocs2;
3555     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3556                     *DAG.getContext());
3557     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3558
3559     if (RVLocs1.size() != RVLocs2.size())
3560       return false;
3561     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3562       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3563         return false;
3564       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3565         return false;
3566       if (RVLocs1[i].isRegLoc()) {
3567         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3568           return false;
3569       } else {
3570         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3571           return false;
3572       }
3573     }
3574   }
3575
3576   // If the callee takes no arguments then go on to check the results of the
3577   // call.
3578   if (!Outs.empty()) {
3579     // Check if stack adjustment is needed. For now, do not do this if any
3580     // argument is passed on the stack.
3581     SmallVector<CCValAssign, 16> ArgLocs;
3582     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3583                    *DAG.getContext());
3584
3585     // Allocate shadow area for Win64
3586     if (IsCalleeWin64)
3587       CCInfo.AllocateStack(32, 8);
3588
3589     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3590     if (CCInfo.getNextStackOffset()) {
3591       MachineFunction &MF = DAG.getMachineFunction();
3592       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3593         return false;
3594
3595       // Check if the arguments are already laid out in the right way as
3596       // the caller's fixed stack objects.
3597       MachineFrameInfo *MFI = MF.getFrameInfo();
3598       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3599       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3600       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3601         CCValAssign &VA = ArgLocs[i];
3602         SDValue Arg = OutVals[i];
3603         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3604         if (VA.getLocInfo() == CCValAssign::Indirect)
3605           return false;
3606         if (!VA.isRegLoc()) {
3607           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3608                                    MFI, MRI, TII))
3609             return false;
3610         }
3611       }
3612     }
3613
3614     // If the tailcall address may be in a register, then make sure it's
3615     // possible to register allocate for it. In 32-bit, the call address can
3616     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3617     // callee-saved registers are restored. These happen to be the same
3618     // registers used to pass 'inreg' arguments so watch out for those.
3619     if (!Subtarget->is64Bit() &&
3620         ((!isa<GlobalAddressSDNode>(Callee) &&
3621           !isa<ExternalSymbolSDNode>(Callee)) ||
3622          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3623       unsigned NumInRegs = 0;
3624       // In PIC we need an extra register to formulate the address computation
3625       // for the callee.
3626       unsigned MaxInRegs =
3627         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3628
3629       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3630         CCValAssign &VA = ArgLocs[i];
3631         if (!VA.isRegLoc())
3632           continue;
3633         unsigned Reg = VA.getLocReg();
3634         switch (Reg) {
3635         default: break;
3636         case X86::EAX: case X86::EDX: case X86::ECX:
3637           if (++NumInRegs == MaxInRegs)
3638             return false;
3639           break;
3640         }
3641       }
3642     }
3643   }
3644
3645   return true;
3646 }
3647
3648 FastISel *
3649 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3650                                   const TargetLibraryInfo *libInfo) const {
3651   return X86::createFastISel(funcInfo, libInfo);
3652 }
3653
3654 //===----------------------------------------------------------------------===//
3655 //                           Other Lowering Hooks
3656 //===----------------------------------------------------------------------===//
3657
3658 static bool MayFoldLoad(SDValue Op) {
3659   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3660 }
3661
3662 static bool MayFoldIntoStore(SDValue Op) {
3663   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3664 }
3665
3666 static bool isTargetShuffle(unsigned Opcode) {
3667   switch(Opcode) {
3668   default: return false;
3669   case X86ISD::BLENDI:
3670   case X86ISD::PSHUFB:
3671   case X86ISD::PSHUFD:
3672   case X86ISD::PSHUFHW:
3673   case X86ISD::PSHUFLW:
3674   case X86ISD::SHUFP:
3675   case X86ISD::PALIGNR:
3676   case X86ISD::MOVLHPS:
3677   case X86ISD::MOVLHPD:
3678   case X86ISD::MOVHLPS:
3679   case X86ISD::MOVLPS:
3680   case X86ISD::MOVLPD:
3681   case X86ISD::MOVSHDUP:
3682   case X86ISD::MOVSLDUP:
3683   case X86ISD::MOVDDUP:
3684   case X86ISD::MOVSS:
3685   case X86ISD::MOVSD:
3686   case X86ISD::UNPCKL:
3687   case X86ISD::UNPCKH:
3688   case X86ISD::VPERMILPI:
3689   case X86ISD::VPERM2X128:
3690   case X86ISD::VPERMI:
3691     return true;
3692   }
3693 }
3694
3695 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3696                                     SDValue V1, unsigned TargetMask,
3697                                     SelectionDAG &DAG) {
3698   switch(Opc) {
3699   default: llvm_unreachable("Unknown x86 shuffle node");
3700   case X86ISD::PSHUFD:
3701   case X86ISD::PSHUFHW:
3702   case X86ISD::PSHUFLW:
3703   case X86ISD::VPERMILPI:
3704   case X86ISD::VPERMI:
3705     return DAG.getNode(Opc, dl, VT, V1,
3706                        DAG.getConstant(TargetMask, dl, MVT::i8));
3707   }
3708 }
3709
3710 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3711                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3712   switch(Opc) {
3713   default: llvm_unreachable("Unknown x86 shuffle node");
3714   case X86ISD::MOVLHPS:
3715   case X86ISD::MOVLHPD:
3716   case X86ISD::MOVHLPS:
3717   case X86ISD::MOVLPS:
3718   case X86ISD::MOVLPD:
3719   case X86ISD::MOVSS:
3720   case X86ISD::MOVSD:
3721   case X86ISD::UNPCKL:
3722   case X86ISD::UNPCKH:
3723     return DAG.getNode(Opc, dl, VT, V1, V2);
3724   }
3725 }
3726
3727 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3728   MachineFunction &MF = DAG.getMachineFunction();
3729   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3730   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3731   int ReturnAddrIndex = FuncInfo->getRAIndex();
3732
3733   if (ReturnAddrIndex == 0) {
3734     // Set up a frame object for the return address.
3735     unsigned SlotSize = RegInfo->getSlotSize();
3736     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3737                                                            -(int64_t)SlotSize,
3738                                                            false);
3739     FuncInfo->setRAIndex(ReturnAddrIndex);
3740   }
3741
3742   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy(DAG.getDataLayout()));
3743 }
3744
3745 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3746                                        bool hasSymbolicDisplacement) {
3747   // Offset should fit into 32 bit immediate field.
3748   if (!isInt<32>(Offset))
3749     return false;
3750
3751   // If we don't have a symbolic displacement - we don't have any extra
3752   // restrictions.
3753   if (!hasSymbolicDisplacement)
3754     return true;
3755
3756   // FIXME: Some tweaks might be needed for medium code model.
3757   if (M != CodeModel::Small && M != CodeModel::Kernel)
3758     return false;
3759
3760   // For small code model we assume that latest object is 16MB before end of 31
3761   // bits boundary. We may also accept pretty large negative constants knowing
3762   // that all objects are in the positive half of address space.
3763   if (M == CodeModel::Small && Offset < 16*1024*1024)
3764     return true;
3765
3766   // For kernel code model we know that all object resist in the negative half
3767   // of 32bits address space. We may not accept negative offsets, since they may
3768   // be just off and we may accept pretty large positive ones.
3769   if (M == CodeModel::Kernel && Offset >= 0)
3770     return true;
3771
3772   return false;
3773 }
3774
3775 /// isCalleePop - Determines whether the callee is required to pop its
3776 /// own arguments. Callee pop is necessary to support tail calls.
3777 bool X86::isCalleePop(CallingConv::ID CallingConv,
3778                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3779   switch (CallingConv) {
3780   default:
3781     return false;
3782   case CallingConv::X86_StdCall:
3783   case CallingConv::X86_FastCall:
3784   case CallingConv::X86_ThisCall:
3785     return !is64Bit;
3786   case CallingConv::Fast:
3787   case CallingConv::GHC:
3788   case CallingConv::HiPE:
3789     if (IsVarArg)
3790       return false;
3791     return TailCallOpt;
3792   }
3793 }
3794
3795 /// \brief Return true if the condition is an unsigned comparison operation.
3796 static bool isX86CCUnsigned(unsigned X86CC) {
3797   switch (X86CC) {
3798   default: llvm_unreachable("Invalid integer condition!");
3799   case X86::COND_E:     return true;
3800   case X86::COND_G:     return false;
3801   case X86::COND_GE:    return false;
3802   case X86::COND_L:     return false;
3803   case X86::COND_LE:    return false;
3804   case X86::COND_NE:    return true;
3805   case X86::COND_B:     return true;
3806   case X86::COND_A:     return true;
3807   case X86::COND_BE:    return true;
3808   case X86::COND_AE:    return true;
3809   }
3810   llvm_unreachable("covered switch fell through?!");
3811 }
3812
3813 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3814 /// specific condition code, returning the condition code and the LHS/RHS of the
3815 /// comparison to make.
3816 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3817                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3818   if (!isFP) {
3819     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3820       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3821         // X > -1   -> X == 0, jump !sign.
3822         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3823         return X86::COND_NS;
3824       }
3825       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3826         // X < 0   -> X == 0, jump on sign.
3827         return X86::COND_S;
3828       }
3829       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3830         // X < 1   -> X <= 0
3831         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3832         return X86::COND_LE;
3833       }
3834     }
3835
3836     switch (SetCCOpcode) {
3837     default: llvm_unreachable("Invalid integer condition!");
3838     case ISD::SETEQ:  return X86::COND_E;
3839     case ISD::SETGT:  return X86::COND_G;
3840     case ISD::SETGE:  return X86::COND_GE;
3841     case ISD::SETLT:  return X86::COND_L;
3842     case ISD::SETLE:  return X86::COND_LE;
3843     case ISD::SETNE:  return X86::COND_NE;
3844     case ISD::SETULT: return X86::COND_B;
3845     case ISD::SETUGT: return X86::COND_A;
3846     case ISD::SETULE: return X86::COND_BE;
3847     case ISD::SETUGE: return X86::COND_AE;
3848     }
3849   }
3850
3851   // First determine if it is required or is profitable to flip the operands.
3852
3853   // If LHS is a foldable load, but RHS is not, flip the condition.
3854   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3855       !ISD::isNON_EXTLoad(RHS.getNode())) {
3856     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3857     std::swap(LHS, RHS);
3858   }
3859
3860   switch (SetCCOpcode) {
3861   default: break;
3862   case ISD::SETOLT:
3863   case ISD::SETOLE:
3864   case ISD::SETUGT:
3865   case ISD::SETUGE:
3866     std::swap(LHS, RHS);
3867     break;
3868   }
3869
3870   // On a floating point condition, the flags are set as follows:
3871   // ZF  PF  CF   op
3872   //  0 | 0 | 0 | X > Y
3873   //  0 | 0 | 1 | X < Y
3874   //  1 | 0 | 0 | X == Y
3875   //  1 | 1 | 1 | unordered
3876   switch (SetCCOpcode) {
3877   default: llvm_unreachable("Condcode should be pre-legalized away");
3878   case ISD::SETUEQ:
3879   case ISD::SETEQ:   return X86::COND_E;
3880   case ISD::SETOLT:              // flipped
3881   case ISD::SETOGT:
3882   case ISD::SETGT:   return X86::COND_A;
3883   case ISD::SETOLE:              // flipped
3884   case ISD::SETOGE:
3885   case ISD::SETGE:   return X86::COND_AE;
3886   case ISD::SETUGT:              // flipped
3887   case ISD::SETULT:
3888   case ISD::SETLT:   return X86::COND_B;
3889   case ISD::SETUGE:              // flipped
3890   case ISD::SETULE:
3891   case ISD::SETLE:   return X86::COND_BE;
3892   case ISD::SETONE:
3893   case ISD::SETNE:   return X86::COND_NE;
3894   case ISD::SETUO:   return X86::COND_P;
3895   case ISD::SETO:    return X86::COND_NP;
3896   case ISD::SETOEQ:
3897   case ISD::SETUNE:  return X86::COND_INVALID;
3898   }
3899 }
3900
3901 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3902 /// code. Current x86 isa includes the following FP cmov instructions:
3903 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3904 static bool hasFPCMov(unsigned X86CC) {
3905   switch (X86CC) {
3906   default:
3907     return false;
3908   case X86::COND_B:
3909   case X86::COND_BE:
3910   case X86::COND_E:
3911   case X86::COND_P:
3912   case X86::COND_A:
3913   case X86::COND_AE:
3914   case X86::COND_NE:
3915   case X86::COND_NP:
3916     return true;
3917   }
3918 }
3919
3920 /// isFPImmLegal - Returns true if the target can instruction select the
3921 /// specified FP immediate natively. If false, the legalizer will
3922 /// materialize the FP immediate as a load from a constant pool.
3923 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3924   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3925     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3926       return true;
3927   }
3928   return false;
3929 }
3930
3931 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3932                                               ISD::LoadExtType ExtTy,
3933                                               EVT NewVT) const {
3934   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3935   // relocation target a movq or addq instruction: don't let the load shrink.
3936   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3937   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3938     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3939       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3940   return true;
3941 }
3942
3943 /// \brief Returns true if it is beneficial to convert a load of a constant
3944 /// to just the constant itself.
3945 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3946                                                           Type *Ty) const {
3947   assert(Ty->isIntegerTy());
3948
3949   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3950   if (BitSize == 0 || BitSize > 64)
3951     return false;
3952   return true;
3953 }
3954
3955 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3956                                                 unsigned Index) const {
3957   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3958     return false;
3959
3960   return (Index == 0 || Index == ResVT.getVectorNumElements());
3961 }
3962
3963 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3964   // Speculate cttz only if we can directly use TZCNT.
3965   return Subtarget->hasBMI();
3966 }
3967
3968 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3969   // Speculate ctlz only if we can directly use LZCNT.
3970   return Subtarget->hasLZCNT();
3971 }
3972
3973 /// isUndefInRange - Return true if every element in Mask, beginning
3974 /// from position Pos and ending in Pos+Size is undef.
3975 static bool isUndefInRange(ArrayRef<int> Mask, unsigned Pos, unsigned Size) {
3976   for (unsigned i = Pos, e = Pos + Size; i != e; ++i)
3977     if (0 <= Mask[i])
3978       return false;
3979   return true;
3980 }
3981
3982 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3983 /// the specified range (L, H].
3984 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3985   return (Val < 0) || (Val >= Low && Val < Hi);
3986 }
3987
3988 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3989 /// specified value.
3990 static bool isUndefOrEqual(int Val, int CmpVal) {
3991   return (Val < 0 || Val == CmpVal);
3992 }
3993
3994 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3995 /// from position Pos and ending in Pos+Size, falls within the specified
3996 /// sequential range (Low, Low+Size]. or is undef.
3997 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3998                                        unsigned Pos, unsigned Size, int Low) {
3999   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
4000     if (!isUndefOrEqual(Mask[i], Low))
4001       return false;
4002   return true;
4003 }
4004
4005 /// isVEXTRACTIndex - Return true if the specified
4006 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
4007 /// suitable for instruction that extract 128 or 256 bit vectors
4008 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
4009   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4010   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4011     return false;
4012
4013   // The index should be aligned on a vecWidth-bit boundary.
4014   uint64_t Index =
4015     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4016
4017   MVT VT = N->getSimpleValueType(0);
4018   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4019   bool Result = (Index * ElSize) % vecWidth == 0;
4020
4021   return Result;
4022 }
4023
4024 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
4025 /// operand specifies a subvector insert that is suitable for input to
4026 /// insertion of 128 or 256-bit subvectors
4027 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
4028   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
4029   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4030     return false;
4031   // The index should be aligned on a vecWidth-bit boundary.
4032   uint64_t Index =
4033     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4034
4035   MVT VT = N->getSimpleValueType(0);
4036   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
4037   bool Result = (Index * ElSize) % vecWidth == 0;
4038
4039   return Result;
4040 }
4041
4042 bool X86::isVINSERT128Index(SDNode *N) {
4043   return isVINSERTIndex(N, 128);
4044 }
4045
4046 bool X86::isVINSERT256Index(SDNode *N) {
4047   return isVINSERTIndex(N, 256);
4048 }
4049
4050 bool X86::isVEXTRACT128Index(SDNode *N) {
4051   return isVEXTRACTIndex(N, 128);
4052 }
4053
4054 bool X86::isVEXTRACT256Index(SDNode *N) {
4055   return isVEXTRACTIndex(N, 256);
4056 }
4057
4058 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4059   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4060   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4061     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4062
4063   uint64_t Index =
4064     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4065
4066   MVT VecVT = N->getOperand(0).getSimpleValueType();
4067   MVT ElVT = VecVT.getVectorElementType();
4068
4069   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4070   return Index / NumElemsPerChunk;
4071 }
4072
4073 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4074   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4075   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4076     llvm_unreachable("Illegal insert subvector for VINSERT");
4077
4078   uint64_t Index =
4079     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4080
4081   MVT VecVT = N->getSimpleValueType(0);
4082   MVT ElVT = VecVT.getVectorElementType();
4083
4084   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4085   return Index / NumElemsPerChunk;
4086 }
4087
4088 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4089 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4090 /// and VINSERTI128 instructions.
4091 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4092   return getExtractVEXTRACTImmediate(N, 128);
4093 }
4094
4095 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4096 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4097 /// and VINSERTI64x4 instructions.
4098 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4099   return getExtractVEXTRACTImmediate(N, 256);
4100 }
4101
4102 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4103 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4104 /// and VINSERTI128 instructions.
4105 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4106   return getInsertVINSERTImmediate(N, 128);
4107 }
4108
4109 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4110 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4111 /// and VINSERTI64x4 instructions.
4112 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4113   return getInsertVINSERTImmediate(N, 256);
4114 }
4115
4116 /// isZero - Returns true if Elt is a constant integer zero
4117 static bool isZero(SDValue V) {
4118   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4119   return C && C->isNullValue();
4120 }
4121
4122 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4123 /// constant +0.0.
4124 bool X86::isZeroNode(SDValue Elt) {
4125   if (isZero(Elt))
4126     return true;
4127   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4128     return CFP->getValueAPF().isPosZero();
4129   return false;
4130 }
4131
4132 /// getZeroVector - Returns a vector of specified type with all zero elements.
4133 ///
4134 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4135                              SelectionDAG &DAG, SDLoc dl) {
4136   assert(VT.isVector() && "Expected a vector type");
4137
4138   // Always build SSE zero vectors as <4 x i32> bitcasted
4139   // to their dest type. This ensures they get CSE'd.
4140   SDValue Vec;
4141   if (VT.is128BitVector()) {  // SSE
4142     if (Subtarget->hasSSE2()) {  // SSE2
4143       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4144       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4145     } else { // SSE1
4146       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4147       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4148     }
4149   } else if (VT.is256BitVector()) { // AVX
4150     if (Subtarget->hasInt256()) { // AVX2
4151       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4152       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4153       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4154     } else {
4155       // 256-bit logic and arithmetic instructions in AVX are all
4156       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4157       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4158       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4159       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4160     }
4161   } else if (VT.is512BitVector()) { // AVX-512
4162       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4163       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4164                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4165       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4166   } else if (VT.getScalarType() == MVT::i1) {
4167
4168     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4169             && "Unexpected vector type");
4170     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4171             && "Unexpected vector type");
4172     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4173     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4174     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4175   } else
4176     llvm_unreachable("Unexpected vector type");
4177
4178   return DAG.getBitcast(VT, Vec);
4179 }
4180
4181 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4182                                 SelectionDAG &DAG, SDLoc dl,
4183                                 unsigned vectorWidth) {
4184   assert((vectorWidth == 128 || vectorWidth == 256) &&
4185          "Unsupported vector width");
4186   EVT VT = Vec.getValueType();
4187   EVT ElVT = VT.getVectorElementType();
4188   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4189   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4190                                   VT.getVectorNumElements()/Factor);
4191
4192   // Extract from UNDEF is UNDEF.
4193   if (Vec.getOpcode() == ISD::UNDEF)
4194     return DAG.getUNDEF(ResultVT);
4195
4196   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4197   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4198
4199   // This is the index of the first element of the vectorWidth-bit chunk
4200   // we want.
4201   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4202                                * ElemsPerChunk);
4203
4204   // If the input is a buildvector just emit a smaller one.
4205   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4206     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4207                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4208                                     ElemsPerChunk));
4209
4210   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4211   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4212 }
4213
4214 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4215 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4216 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4217 /// instructions or a simple subregister reference. Idx is an index in the
4218 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4219 /// lowering EXTRACT_VECTOR_ELT operations easier.
4220 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4221                                    SelectionDAG &DAG, SDLoc dl) {
4222   assert((Vec.getValueType().is256BitVector() ||
4223           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4224   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4225 }
4226
4227 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4228 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4229                                    SelectionDAG &DAG, SDLoc dl) {
4230   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4231   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4232 }
4233
4234 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4235                                unsigned IdxVal, SelectionDAG &DAG,
4236                                SDLoc dl, unsigned vectorWidth) {
4237   assert((vectorWidth == 128 || vectorWidth == 256) &&
4238          "Unsupported vector width");
4239   // Inserting UNDEF is Result
4240   if (Vec.getOpcode() == ISD::UNDEF)
4241     return Result;
4242   EVT VT = Vec.getValueType();
4243   EVT ElVT = VT.getVectorElementType();
4244   EVT ResultVT = Result.getValueType();
4245
4246   // Insert the relevant vectorWidth bits.
4247   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4248
4249   // This is the index of the first element of the vectorWidth-bit chunk
4250   // we want.
4251   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4252                                * ElemsPerChunk);
4253
4254   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4255   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4256 }
4257
4258 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4259 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4260 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4261 /// simple superregister reference.  Idx is an index in the 128 bits
4262 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4263 /// lowering INSERT_VECTOR_ELT operations easier.
4264 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4265                                   SelectionDAG &DAG, SDLoc dl) {
4266   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4267
4268   // For insertion into the zero index (low half) of a 256-bit vector, it is
4269   // more efficient to generate a blend with immediate instead of an insert*128.
4270   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4271   // extend the subvector to the size of the result vector. Make sure that
4272   // we are not recursing on that node by checking for undef here.
4273   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4274       Result.getOpcode() != ISD::UNDEF) {
4275     EVT ResultVT = Result.getValueType();
4276     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4277     SDValue Undef = DAG.getUNDEF(ResultVT);
4278     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4279                                  Vec, ZeroIndex);
4280
4281     // The blend instruction, and therefore its mask, depend on the data type.
4282     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4283     if (ScalarType.isFloatingPoint()) {
4284       // Choose either vblendps (float) or vblendpd (double).
4285       unsigned ScalarSize = ScalarType.getSizeInBits();
4286       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4287       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4288       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4289       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4290     }
4291
4292     const X86Subtarget &Subtarget =
4293     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4294
4295     // AVX2 is needed for 256-bit integer blend support.
4296     // Integers must be cast to 32-bit because there is only vpblendd;
4297     // vpblendw can't be used for this because it has a handicapped mask.
4298
4299     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4300     // is still more efficient than using the wrong domain vinsertf128 that
4301     // will be created by InsertSubVector().
4302     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4303
4304     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4305     Vec256 = DAG.getBitcast(CastVT, Vec256);
4306     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4307     return DAG.getBitcast(ResultVT, Vec256);
4308   }
4309
4310   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4311 }
4312
4313 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4314                                   SelectionDAG &DAG, SDLoc dl) {
4315   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4316   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4317 }
4318
4319 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4320 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4321 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4322 /// large BUILD_VECTORS.
4323 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4324                                    unsigned NumElems, SelectionDAG &DAG,
4325                                    SDLoc dl) {
4326   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4327   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4328 }
4329
4330 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4331                                    unsigned NumElems, SelectionDAG &DAG,
4332                                    SDLoc dl) {
4333   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4334   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4335 }
4336
4337 /// getOnesVector - Returns a vector of specified type with all bits set.
4338 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4339 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4340 /// Then bitcast to their original type, ensuring they get CSE'd.
4341 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4342                              SDLoc dl) {
4343   assert(VT.isVector() && "Expected a vector type");
4344
4345   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4346   SDValue Vec;
4347   if (VT.is256BitVector()) {
4348     if (HasInt256) { // AVX2
4349       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4350       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4351     } else { // AVX
4352       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4353       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4354     }
4355   } else if (VT.is128BitVector()) {
4356     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4357   } else
4358     llvm_unreachable("Unexpected vector type");
4359
4360   return DAG.getBitcast(VT, Vec);
4361 }
4362
4363 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4364 /// operation of specified width.
4365 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4366                        SDValue V2) {
4367   unsigned NumElems = VT.getVectorNumElements();
4368   SmallVector<int, 8> Mask;
4369   Mask.push_back(NumElems);
4370   for (unsigned i = 1; i != NumElems; ++i)
4371     Mask.push_back(i);
4372   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4373 }
4374
4375 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4376 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4377                           SDValue V2) {
4378   unsigned NumElems = VT.getVectorNumElements();
4379   SmallVector<int, 8> Mask;
4380   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4381     Mask.push_back(i);
4382     Mask.push_back(i + NumElems);
4383   }
4384   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4385 }
4386
4387 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4388 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4389                           SDValue V2) {
4390   unsigned NumElems = VT.getVectorNumElements();
4391   SmallVector<int, 8> Mask;
4392   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4393     Mask.push_back(i + Half);
4394     Mask.push_back(i + NumElems + Half);
4395   }
4396   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4397 }
4398
4399 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4400 /// vector of zero or undef vector.  This produces a shuffle where the low
4401 /// element of V2 is swizzled into the zero/undef vector, landing at element
4402 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4403 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4404                                            bool IsZero,
4405                                            const X86Subtarget *Subtarget,
4406                                            SelectionDAG &DAG) {
4407   MVT VT = V2.getSimpleValueType();
4408   SDValue V1 = IsZero
4409     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4410   unsigned NumElems = VT.getVectorNumElements();
4411   SmallVector<int, 16> MaskVec;
4412   for (unsigned i = 0; i != NumElems; ++i)
4413     // If this is the insertion idx, put the low elt of V2 here.
4414     MaskVec.push_back(i == Idx ? NumElems : i);
4415   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4416 }
4417
4418 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4419 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4420 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4421 /// shuffles which use a single input multiple times, and in those cases it will
4422 /// adjust the mask to only have indices within that single input.
4423 /// FIXME: Add support for Decode*Mask functions that return SM_SentinelZero.
4424 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4425                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4426   unsigned NumElems = VT.getVectorNumElements();
4427   SDValue ImmN;
4428
4429   IsUnary = false;
4430   bool IsFakeUnary = false;
4431   switch(N->getOpcode()) {
4432   case X86ISD::BLENDI:
4433     ImmN = N->getOperand(N->getNumOperands()-1);
4434     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4435     break;
4436   case X86ISD::SHUFP:
4437     ImmN = N->getOperand(N->getNumOperands()-1);
4438     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4439     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4440     break;
4441   case X86ISD::UNPCKH:
4442     DecodeUNPCKHMask(VT, Mask);
4443     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4444     break;
4445   case X86ISD::UNPCKL:
4446     DecodeUNPCKLMask(VT, Mask);
4447     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4448     break;
4449   case X86ISD::MOVHLPS:
4450     DecodeMOVHLPSMask(NumElems, Mask);
4451     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4452     break;
4453   case X86ISD::MOVLHPS:
4454     DecodeMOVLHPSMask(NumElems, Mask);
4455     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4456     break;
4457   case X86ISD::PALIGNR:
4458     ImmN = N->getOperand(N->getNumOperands()-1);
4459     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4460     break;
4461   case X86ISD::PSHUFD:
4462   case X86ISD::VPERMILPI:
4463     ImmN = N->getOperand(N->getNumOperands()-1);
4464     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4465     IsUnary = true;
4466     break;
4467   case X86ISD::PSHUFHW:
4468     ImmN = N->getOperand(N->getNumOperands()-1);
4469     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4470     IsUnary = true;
4471     break;
4472   case X86ISD::PSHUFLW:
4473     ImmN = N->getOperand(N->getNumOperands()-1);
4474     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4475     IsUnary = true;
4476     break;
4477   case X86ISD::PSHUFB: {
4478     IsUnary = true;
4479     SDValue MaskNode = N->getOperand(1);
4480     while (MaskNode->getOpcode() == ISD::BITCAST)
4481       MaskNode = MaskNode->getOperand(0);
4482
4483     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4484       // If we have a build-vector, then things are easy.
4485       EVT VT = MaskNode.getValueType();
4486       assert(VT.isVector() &&
4487              "Can't produce a non-vector with a build_vector!");
4488       if (!VT.isInteger())
4489         return false;
4490
4491       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4492
4493       SmallVector<uint64_t, 32> RawMask;
4494       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4495         SDValue Op = MaskNode->getOperand(i);
4496         if (Op->getOpcode() == ISD::UNDEF) {
4497           RawMask.push_back((uint64_t)SM_SentinelUndef);
4498           continue;
4499         }
4500         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4501         if (!CN)
4502           return false;
4503         APInt MaskElement = CN->getAPIntValue();
4504
4505         // We now have to decode the element which could be any integer size and
4506         // extract each byte of it.
4507         for (int j = 0; j < NumBytesPerElement; ++j) {
4508           // Note that this is x86 and so always little endian: the low byte is
4509           // the first byte of the mask.
4510           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4511           MaskElement = MaskElement.lshr(8);
4512         }
4513       }
4514       DecodePSHUFBMask(RawMask, Mask);
4515       break;
4516     }
4517
4518     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4519     if (!MaskLoad)
4520       return false;
4521
4522     SDValue Ptr = MaskLoad->getBasePtr();
4523     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4524         Ptr->getOpcode() == X86ISD::WrapperRIP)
4525       Ptr = Ptr->getOperand(0);
4526
4527     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4528     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4529       return false;
4530
4531     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4532       DecodePSHUFBMask(C, Mask);
4533       if (Mask.empty())
4534         return false;
4535       break;
4536     }
4537
4538     return false;
4539   }
4540   case X86ISD::VPERMI:
4541     ImmN = N->getOperand(N->getNumOperands()-1);
4542     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4543     IsUnary = true;
4544     break;
4545   case X86ISD::MOVSS:
4546   case X86ISD::MOVSD:
4547     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4548     break;
4549   case X86ISD::VPERM2X128:
4550     ImmN = N->getOperand(N->getNumOperands()-1);
4551     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4552     if (Mask.empty()) return false;
4553     // Mask only contains negative index if an element is zero.
4554     if (std::any_of(Mask.begin(), Mask.end(),
4555                     [](int M){ return M == SM_SentinelZero; }))
4556       return false;
4557     break;
4558   case X86ISD::MOVSLDUP:
4559     DecodeMOVSLDUPMask(VT, Mask);
4560     IsUnary = true;
4561     break;
4562   case X86ISD::MOVSHDUP:
4563     DecodeMOVSHDUPMask(VT, Mask);
4564     IsUnary = true;
4565     break;
4566   case X86ISD::MOVDDUP:
4567     DecodeMOVDDUPMask(VT, Mask);
4568     IsUnary = true;
4569     break;
4570   case X86ISD::MOVLHPD:
4571   case X86ISD::MOVLPD:
4572   case X86ISD::MOVLPS:
4573     // Not yet implemented
4574     return false;
4575   default: llvm_unreachable("unknown target shuffle node");
4576   }
4577
4578   // If we have a fake unary shuffle, the shuffle mask is spread across two
4579   // inputs that are actually the same node. Re-map the mask to always point
4580   // into the first input.
4581   if (IsFakeUnary)
4582     for (int &M : Mask)
4583       if (M >= (int)Mask.size())
4584         M -= Mask.size();
4585
4586   return true;
4587 }
4588
4589 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4590 /// element of the result of the vector shuffle.
4591 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4592                                    unsigned Depth) {
4593   if (Depth == 6)
4594     return SDValue();  // Limit search depth.
4595
4596   SDValue V = SDValue(N, 0);
4597   EVT VT = V.getValueType();
4598   unsigned Opcode = V.getOpcode();
4599
4600   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4601   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4602     int Elt = SV->getMaskElt(Index);
4603
4604     if (Elt < 0)
4605       return DAG.getUNDEF(VT.getVectorElementType());
4606
4607     unsigned NumElems = VT.getVectorNumElements();
4608     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4609                                          : SV->getOperand(1);
4610     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4611   }
4612
4613   // Recurse into target specific vector shuffles to find scalars.
4614   if (isTargetShuffle(Opcode)) {
4615     MVT ShufVT = V.getSimpleValueType();
4616     unsigned NumElems = ShufVT.getVectorNumElements();
4617     SmallVector<int, 16> ShuffleMask;
4618     bool IsUnary;
4619
4620     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4621       return SDValue();
4622
4623     int Elt = ShuffleMask[Index];
4624     if (Elt < 0)
4625       return DAG.getUNDEF(ShufVT.getVectorElementType());
4626
4627     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4628                                          : N->getOperand(1);
4629     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4630                                Depth+1);
4631   }
4632
4633   // Actual nodes that may contain scalar elements
4634   if (Opcode == ISD::BITCAST) {
4635     V = V.getOperand(0);
4636     EVT SrcVT = V.getValueType();
4637     unsigned NumElems = VT.getVectorNumElements();
4638
4639     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4640       return SDValue();
4641   }
4642
4643   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4644     return (Index == 0) ? V.getOperand(0)
4645                         : DAG.getUNDEF(VT.getVectorElementType());
4646
4647   if (V.getOpcode() == ISD::BUILD_VECTOR)
4648     return V.getOperand(Index);
4649
4650   return SDValue();
4651 }
4652
4653 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4654 ///
4655 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4656                                        unsigned NumNonZero, unsigned NumZero,
4657                                        SelectionDAG &DAG,
4658                                        const X86Subtarget* Subtarget,
4659                                        const TargetLowering &TLI) {
4660   if (NumNonZero > 8)
4661     return SDValue();
4662
4663   SDLoc dl(Op);
4664   SDValue V;
4665   bool First = true;
4666
4667   // SSE4.1 - use PINSRB to insert each byte directly.
4668   if (Subtarget->hasSSE41()) {
4669     for (unsigned i = 0; i < 16; ++i) {
4670       bool isNonZero = (NonZeros & (1 << i)) != 0;
4671       if (isNonZero) {
4672         if (First) {
4673           if (NumZero)
4674             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4675           else
4676             V = DAG.getUNDEF(MVT::v16i8);
4677           First = false;
4678         }
4679         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4680                         MVT::v16i8, V, Op.getOperand(i),
4681                         DAG.getIntPtrConstant(i, dl));
4682       }
4683     }
4684
4685     return V;
4686   }
4687
4688   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4689   for (unsigned i = 0; i < 16; ++i) {
4690     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4691     if (ThisIsNonZero && First) {
4692       if (NumZero)
4693         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4694       else
4695         V = DAG.getUNDEF(MVT::v8i16);
4696       First = false;
4697     }
4698
4699     if ((i & 1) != 0) {
4700       SDValue ThisElt, LastElt;
4701       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4702       if (LastIsNonZero) {
4703         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4704                               MVT::i16, Op.getOperand(i-1));
4705       }
4706       if (ThisIsNonZero) {
4707         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4708         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4709                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4710         if (LastIsNonZero)
4711           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4712       } else
4713         ThisElt = LastElt;
4714
4715       if (ThisElt.getNode())
4716         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4717                         DAG.getIntPtrConstant(i/2, dl));
4718     }
4719   }
4720
4721   return DAG.getBitcast(MVT::v16i8, V);
4722 }
4723
4724 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4725 ///
4726 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4727                                      unsigned NumNonZero, unsigned NumZero,
4728                                      SelectionDAG &DAG,
4729                                      const X86Subtarget* Subtarget,
4730                                      const TargetLowering &TLI) {
4731   if (NumNonZero > 4)
4732     return SDValue();
4733
4734   SDLoc dl(Op);
4735   SDValue V;
4736   bool First = true;
4737   for (unsigned i = 0; i < 8; ++i) {
4738     bool isNonZero = (NonZeros & (1 << i)) != 0;
4739     if (isNonZero) {
4740       if (First) {
4741         if (NumZero)
4742           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4743         else
4744           V = DAG.getUNDEF(MVT::v8i16);
4745         First = false;
4746       }
4747       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4748                       MVT::v8i16, V, Op.getOperand(i),
4749                       DAG.getIntPtrConstant(i, dl));
4750     }
4751   }
4752
4753   return V;
4754 }
4755
4756 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4757 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4758                                      const X86Subtarget *Subtarget,
4759                                      const TargetLowering &TLI) {
4760   // Find all zeroable elements.
4761   std::bitset<4> Zeroable;
4762   for (int i=0; i < 4; ++i) {
4763     SDValue Elt = Op->getOperand(i);
4764     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4765   }
4766   assert(Zeroable.size() - Zeroable.count() > 1 &&
4767          "We expect at least two non-zero elements!");
4768
4769   // We only know how to deal with build_vector nodes where elements are either
4770   // zeroable or extract_vector_elt with constant index.
4771   SDValue FirstNonZero;
4772   unsigned FirstNonZeroIdx;
4773   for (unsigned i=0; i < 4; ++i) {
4774     if (Zeroable[i])
4775       continue;
4776     SDValue Elt = Op->getOperand(i);
4777     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4778         !isa<ConstantSDNode>(Elt.getOperand(1)))
4779       return SDValue();
4780     // Make sure that this node is extracting from a 128-bit vector.
4781     MVT VT = Elt.getOperand(0).getSimpleValueType();
4782     if (!VT.is128BitVector())
4783       return SDValue();
4784     if (!FirstNonZero.getNode()) {
4785       FirstNonZero = Elt;
4786       FirstNonZeroIdx = i;
4787     }
4788   }
4789
4790   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4791   SDValue V1 = FirstNonZero.getOperand(0);
4792   MVT VT = V1.getSimpleValueType();
4793
4794   // See if this build_vector can be lowered as a blend with zero.
4795   SDValue Elt;
4796   unsigned EltMaskIdx, EltIdx;
4797   int Mask[4];
4798   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4799     if (Zeroable[EltIdx]) {
4800       // The zero vector will be on the right hand side.
4801       Mask[EltIdx] = EltIdx+4;
4802       continue;
4803     }
4804
4805     Elt = Op->getOperand(EltIdx);
4806     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4807     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4808     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4809       break;
4810     Mask[EltIdx] = EltIdx;
4811   }
4812
4813   if (EltIdx == 4) {
4814     // Let the shuffle legalizer deal with blend operations.
4815     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4816     if (V1.getSimpleValueType() != VT)
4817       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4818     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4819   }
4820
4821   // See if we can lower this build_vector to a INSERTPS.
4822   if (!Subtarget->hasSSE41())
4823     return SDValue();
4824
4825   SDValue V2 = Elt.getOperand(0);
4826   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4827     V1 = SDValue();
4828
4829   bool CanFold = true;
4830   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4831     if (Zeroable[i])
4832       continue;
4833
4834     SDValue Current = Op->getOperand(i);
4835     SDValue SrcVector = Current->getOperand(0);
4836     if (!V1.getNode())
4837       V1 = SrcVector;
4838     CanFold = SrcVector == V1 &&
4839       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4840   }
4841
4842   if (!CanFold)
4843     return SDValue();
4844
4845   assert(V1.getNode() && "Expected at least two non-zero elements!");
4846   if (V1.getSimpleValueType() != MVT::v4f32)
4847     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4848   if (V2.getSimpleValueType() != MVT::v4f32)
4849     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4850
4851   // Ok, we can emit an INSERTPS instruction.
4852   unsigned ZMask = Zeroable.to_ulong();
4853
4854   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4855   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4856   SDLoc DL(Op);
4857   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4858                                DAG.getIntPtrConstant(InsertPSMask, DL));
4859   return DAG.getBitcast(VT, Result);
4860 }
4861
4862 /// Return a vector logical shift node.
4863 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4864                          unsigned NumBits, SelectionDAG &DAG,
4865                          const TargetLowering &TLI, SDLoc dl) {
4866   assert(VT.is128BitVector() && "Unknown type for VShift");
4867   MVT ShVT = MVT::v2i64;
4868   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4869   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4870   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(DAG.getDataLayout(), VT);
4871   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4872   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4873   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4874 }
4875
4876 static SDValue
4877 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4878
4879   // Check if the scalar load can be widened into a vector load. And if
4880   // the address is "base + cst" see if the cst can be "absorbed" into
4881   // the shuffle mask.
4882   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4883     SDValue Ptr = LD->getBasePtr();
4884     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4885       return SDValue();
4886     EVT PVT = LD->getValueType(0);
4887     if (PVT != MVT::i32 && PVT != MVT::f32)
4888       return SDValue();
4889
4890     int FI = -1;
4891     int64_t Offset = 0;
4892     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4893       FI = FINode->getIndex();
4894       Offset = 0;
4895     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4896                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4897       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4898       Offset = Ptr.getConstantOperandVal(1);
4899       Ptr = Ptr.getOperand(0);
4900     } else {
4901       return SDValue();
4902     }
4903
4904     // FIXME: 256-bit vector instructions don't require a strict alignment,
4905     // improve this code to support it better.
4906     unsigned RequiredAlign = VT.getSizeInBits()/8;
4907     SDValue Chain = LD->getChain();
4908     // Make sure the stack object alignment is at least 16 or 32.
4909     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4910     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4911       if (MFI->isFixedObjectIndex(FI)) {
4912         // Can't change the alignment. FIXME: It's possible to compute
4913         // the exact stack offset and reference FI + adjust offset instead.
4914         // If someone *really* cares about this. That's the way to implement it.
4915         return SDValue();
4916       } else {
4917         MFI->setObjectAlignment(FI, RequiredAlign);
4918       }
4919     }
4920
4921     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4922     // Ptr + (Offset & ~15).
4923     if (Offset < 0)
4924       return SDValue();
4925     if ((Offset % RequiredAlign) & 3)
4926       return SDValue();
4927     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4928     if (StartOffset) {
4929       SDLoc DL(Ptr);
4930       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4931                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4932     }
4933
4934     int EltNo = (Offset - StartOffset) >> 2;
4935     unsigned NumElems = VT.getVectorNumElements();
4936
4937     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4938     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4939                              LD->getPointerInfo().getWithOffset(StartOffset),
4940                              false, false, false, 0);
4941
4942     SmallVector<int, 8> Mask(NumElems, EltNo);
4943
4944     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4945   }
4946
4947   return SDValue();
4948 }
4949
4950 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4951 /// elements can be replaced by a single large load which has the same value as
4952 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4953 ///
4954 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4955 ///
4956 /// FIXME: we'd also like to handle the case where the last elements are zero
4957 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4958 /// There's even a handy isZeroNode for that purpose.
4959 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4960                                         SDLoc &DL, SelectionDAG &DAG,
4961                                         bool isAfterLegalize) {
4962   unsigned NumElems = Elts.size();
4963
4964   LoadSDNode *LDBase = nullptr;
4965   unsigned LastLoadedElt = -1U;
4966
4967   // For each element in the initializer, see if we've found a load or an undef.
4968   // If we don't find an initial load element, or later load elements are
4969   // non-consecutive, bail out.
4970   for (unsigned i = 0; i < NumElems; ++i) {
4971     SDValue Elt = Elts[i];
4972     // Look through a bitcast.
4973     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4974       Elt = Elt.getOperand(0);
4975     if (!Elt.getNode() ||
4976         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4977       return SDValue();
4978     if (!LDBase) {
4979       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4980         return SDValue();
4981       LDBase = cast<LoadSDNode>(Elt.getNode());
4982       LastLoadedElt = i;
4983       continue;
4984     }
4985     if (Elt.getOpcode() == ISD::UNDEF)
4986       continue;
4987
4988     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4989     EVT LdVT = Elt.getValueType();
4990     // Each loaded element must be the correct fractional portion of the
4991     // requested vector load.
4992     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4993       return SDValue();
4994     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4995       return SDValue();
4996     LastLoadedElt = i;
4997   }
4998
4999   // If we have found an entire vector of loads and undefs, then return a large
5000   // load of the entire vector width starting at the base pointer.  If we found
5001   // consecutive loads for the low half, generate a vzext_load node.
5002   if (LastLoadedElt == NumElems - 1) {
5003     assert(LDBase && "Did not find base load for merging consecutive loads");
5004     EVT EltVT = LDBase->getValueType(0);
5005     // Ensure that the input vector size for the merged loads matches the
5006     // cumulative size of the input elements.
5007     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
5008       return SDValue();
5009
5010     if (isAfterLegalize &&
5011         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
5012       return SDValue();
5013
5014     SDValue NewLd = SDValue();
5015
5016     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
5017                         LDBase->getPointerInfo(), LDBase->isVolatile(),
5018                         LDBase->isNonTemporal(), LDBase->isInvariant(),
5019                         LDBase->getAlignment());
5020
5021     if (LDBase->hasAnyUseOfValue(1)) {
5022       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5023                                      SDValue(LDBase, 1),
5024                                      SDValue(NewLd.getNode(), 1));
5025       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5026       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5027                              SDValue(NewLd.getNode(), 1));
5028     }
5029
5030     return NewLd;
5031   }
5032
5033   //TODO: The code below fires only for for loading the low v2i32 / v2f32
5034   //of a v4i32 / v4f32. It's probably worth generalizing.
5035   EVT EltVT = VT.getVectorElementType();
5036   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
5037       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
5038     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
5039     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
5040     SDValue ResNode =
5041         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
5042                                 LDBase->getPointerInfo(),
5043                                 LDBase->getAlignment(),
5044                                 false/*isVolatile*/, true/*ReadMem*/,
5045                                 false/*WriteMem*/);
5046
5047     // Make sure the newly-created LOAD is in the same position as LDBase in
5048     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5049     // update uses of LDBase's output chain to use the TokenFactor.
5050     if (LDBase->hasAnyUseOfValue(1)) {
5051       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5052                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5053       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5054       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5055                              SDValue(ResNode.getNode(), 1));
5056     }
5057
5058     return DAG.getBitcast(VT, ResNode);
5059   }
5060   return SDValue();
5061 }
5062
5063 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5064 /// to generate a splat value for the following cases:
5065 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5066 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5067 /// a scalar load, or a constant.
5068 /// The VBROADCAST node is returned when a pattern is found,
5069 /// or SDValue() otherwise.
5070 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5071                                     SelectionDAG &DAG) {
5072   // VBROADCAST requires AVX.
5073   // TODO: Splats could be generated for non-AVX CPUs using SSE
5074   // instructions, but there's less potential gain for only 128-bit vectors.
5075   if (!Subtarget->hasAVX())
5076     return SDValue();
5077
5078   MVT VT = Op.getSimpleValueType();
5079   SDLoc dl(Op);
5080
5081   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5082          "Unsupported vector type for broadcast.");
5083
5084   SDValue Ld;
5085   bool ConstSplatVal;
5086
5087   switch (Op.getOpcode()) {
5088     default:
5089       // Unknown pattern found.
5090       return SDValue();
5091
5092     case ISD::BUILD_VECTOR: {
5093       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5094       BitVector UndefElements;
5095       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5096
5097       // We need a splat of a single value to use broadcast, and it doesn't
5098       // make any sense if the value is only in one element of the vector.
5099       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5100         return SDValue();
5101
5102       Ld = Splat;
5103       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5104                        Ld.getOpcode() == ISD::ConstantFP);
5105
5106       // Make sure that all of the users of a non-constant load are from the
5107       // BUILD_VECTOR node.
5108       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5109         return SDValue();
5110       break;
5111     }
5112
5113     case ISD::VECTOR_SHUFFLE: {
5114       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5115
5116       // Shuffles must have a splat mask where the first element is
5117       // broadcasted.
5118       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5119         return SDValue();
5120
5121       SDValue Sc = Op.getOperand(0);
5122       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5123           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5124
5125         if (!Subtarget->hasInt256())
5126           return SDValue();
5127
5128         // Use the register form of the broadcast instruction available on AVX2.
5129         if (VT.getSizeInBits() >= 256)
5130           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5131         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5132       }
5133
5134       Ld = Sc.getOperand(0);
5135       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5136                        Ld.getOpcode() == ISD::ConstantFP);
5137
5138       // The scalar_to_vector node and the suspected
5139       // load node must have exactly one user.
5140       // Constants may have multiple users.
5141
5142       // AVX-512 has register version of the broadcast
5143       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5144         Ld.getValueType().getSizeInBits() >= 32;
5145       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5146           !hasRegVer))
5147         return SDValue();
5148       break;
5149     }
5150   }
5151
5152   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5153   bool IsGE256 = (VT.getSizeInBits() >= 256);
5154
5155   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5156   // instruction to save 8 or more bytes of constant pool data.
5157   // TODO: If multiple splats are generated to load the same constant,
5158   // it may be detrimental to overall size. There needs to be a way to detect
5159   // that condition to know if this is truly a size win.
5160   const Function *F = DAG.getMachineFunction().getFunction();
5161   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5162
5163   // Handle broadcasting a single constant scalar from the constant pool
5164   // into a vector.
5165   // On Sandybridge (no AVX2), it is still better to load a constant vector
5166   // from the constant pool and not to broadcast it from a scalar.
5167   // But override that restriction when optimizing for size.
5168   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5169   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5170     EVT CVT = Ld.getValueType();
5171     assert(!CVT.isVector() && "Must not broadcast a vector type");
5172
5173     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5174     // For size optimization, also splat v2f64 and v2i64, and for size opt
5175     // with AVX2, also splat i8 and i16.
5176     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5177     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5178         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5179       const Constant *C = nullptr;
5180       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5181         C = CI->getConstantIntValue();
5182       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5183         C = CF->getConstantFPValue();
5184
5185       assert(C && "Invalid constant type");
5186
5187       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5188       SDValue CP =
5189           DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
5190       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5191       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5192                        MachinePointerInfo::getConstantPool(),
5193                        false, false, false, Alignment);
5194
5195       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5196     }
5197   }
5198
5199   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5200
5201   // Handle AVX2 in-register broadcasts.
5202   if (!IsLoad && Subtarget->hasInt256() &&
5203       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5204     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5205
5206   // The scalar source must be a normal load.
5207   if (!IsLoad)
5208     return SDValue();
5209
5210   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5211       (Subtarget->hasVLX() && ScalarSize == 64))
5212     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5213
5214   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5215   // double since there is no vbroadcastsd xmm
5216   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5217     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5218       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5219   }
5220
5221   // Unsupported broadcast.
5222   return SDValue();
5223 }
5224
5225 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5226 /// underlying vector and index.
5227 ///
5228 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5229 /// index.
5230 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5231                                          SDValue ExtIdx) {
5232   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5233   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5234     return Idx;
5235
5236   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5237   // lowered this:
5238   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5239   // to:
5240   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5241   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5242   //                           undef)
5243   //                       Constant<0>)
5244   // In this case the vector is the extract_subvector expression and the index
5245   // is 2, as specified by the shuffle.
5246   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5247   SDValue ShuffleVec = SVOp->getOperand(0);
5248   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5249   assert(ShuffleVecVT.getVectorElementType() ==
5250          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5251
5252   int ShuffleIdx = SVOp->getMaskElt(Idx);
5253   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5254     ExtractedFromVec = ShuffleVec;
5255     return ShuffleIdx;
5256   }
5257   return Idx;
5258 }
5259
5260 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5261   MVT VT = Op.getSimpleValueType();
5262
5263   // Skip if insert_vec_elt is not supported.
5264   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5265   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5266     return SDValue();
5267
5268   SDLoc DL(Op);
5269   unsigned NumElems = Op.getNumOperands();
5270
5271   SDValue VecIn1;
5272   SDValue VecIn2;
5273   SmallVector<unsigned, 4> InsertIndices;
5274   SmallVector<int, 8> Mask(NumElems, -1);
5275
5276   for (unsigned i = 0; i != NumElems; ++i) {
5277     unsigned Opc = Op.getOperand(i).getOpcode();
5278
5279     if (Opc == ISD::UNDEF)
5280       continue;
5281
5282     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5283       // Quit if more than 1 elements need inserting.
5284       if (InsertIndices.size() > 1)
5285         return SDValue();
5286
5287       InsertIndices.push_back(i);
5288       continue;
5289     }
5290
5291     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5292     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5293     // Quit if non-constant index.
5294     if (!isa<ConstantSDNode>(ExtIdx))
5295       return SDValue();
5296     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5297
5298     // Quit if extracted from vector of different type.
5299     if (ExtractedFromVec.getValueType() != VT)
5300       return SDValue();
5301
5302     if (!VecIn1.getNode())
5303       VecIn1 = ExtractedFromVec;
5304     else if (VecIn1 != ExtractedFromVec) {
5305       if (!VecIn2.getNode())
5306         VecIn2 = ExtractedFromVec;
5307       else if (VecIn2 != ExtractedFromVec)
5308         // Quit if more than 2 vectors to shuffle
5309         return SDValue();
5310     }
5311
5312     if (ExtractedFromVec == VecIn1)
5313       Mask[i] = Idx;
5314     else if (ExtractedFromVec == VecIn2)
5315       Mask[i] = Idx + NumElems;
5316   }
5317
5318   if (!VecIn1.getNode())
5319     return SDValue();
5320
5321   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5322   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5323   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5324     unsigned Idx = InsertIndices[i];
5325     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5326                      DAG.getIntPtrConstant(Idx, DL));
5327   }
5328
5329   return NV;
5330 }
5331
5332 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5333   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5334          Op.getScalarValueSizeInBits() == 1 &&
5335          "Can not convert non-constant vector");
5336   uint64_t Immediate = 0;
5337   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5338     SDValue In = Op.getOperand(idx);
5339     if (In.getOpcode() != ISD::UNDEF)
5340       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5341   }
5342   SDLoc dl(Op);
5343   MVT VT =
5344    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5345   return DAG.getConstant(Immediate, dl, VT);
5346 }
5347 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5348 SDValue
5349 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5350
5351   MVT VT = Op.getSimpleValueType();
5352   assert((VT.getVectorElementType() == MVT::i1) &&
5353          "Unexpected type in LowerBUILD_VECTORvXi1!");
5354
5355   SDLoc dl(Op);
5356   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5357     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5358     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5359     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5360   }
5361
5362   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5363     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5364     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5365     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5366   }
5367
5368   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5369     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5370     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5371       return DAG.getBitcast(VT, Imm);
5372     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5373     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5374                         DAG.getIntPtrConstant(0, dl));
5375   }
5376
5377   // Vector has one or more non-const elements
5378   uint64_t Immediate = 0;
5379   SmallVector<unsigned, 16> NonConstIdx;
5380   bool IsSplat = true;
5381   bool HasConstElts = false;
5382   int SplatIdx = -1;
5383   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5384     SDValue In = Op.getOperand(idx);
5385     if (In.getOpcode() == ISD::UNDEF)
5386       continue;
5387     if (!isa<ConstantSDNode>(In))
5388       NonConstIdx.push_back(idx);
5389     else {
5390       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5391       HasConstElts = true;
5392     }
5393     if (SplatIdx == -1)
5394       SplatIdx = idx;
5395     else if (In != Op.getOperand(SplatIdx))
5396       IsSplat = false;
5397   }
5398
5399   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5400   if (IsSplat)
5401     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5402                        DAG.getConstant(1, dl, VT),
5403                        DAG.getConstant(0, dl, VT));
5404
5405   // insert elements one by one
5406   SDValue DstVec;
5407   SDValue Imm;
5408   if (Immediate) {
5409     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5410     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5411   }
5412   else if (HasConstElts)
5413     Imm = DAG.getConstant(0, dl, VT);
5414   else
5415     Imm = DAG.getUNDEF(VT);
5416   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5417     DstVec = DAG.getBitcast(VT, Imm);
5418   else {
5419     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5420     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5421                          DAG.getIntPtrConstant(0, dl));
5422   }
5423
5424   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5425     unsigned InsertIdx = NonConstIdx[i];
5426     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5427                          Op.getOperand(InsertIdx),
5428                          DAG.getIntPtrConstant(InsertIdx, dl));
5429   }
5430   return DstVec;
5431 }
5432
5433 /// \brief Return true if \p N implements a horizontal binop and return the
5434 /// operands for the horizontal binop into V0 and V1.
5435 ///
5436 /// This is a helper function of LowerToHorizontalOp().
5437 /// This function checks that the build_vector \p N in input implements a
5438 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5439 /// operation to match.
5440 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5441 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5442 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5443 /// arithmetic sub.
5444 ///
5445 /// This function only analyzes elements of \p N whose indices are
5446 /// in range [BaseIdx, LastIdx).
5447 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5448                               SelectionDAG &DAG,
5449                               unsigned BaseIdx, unsigned LastIdx,
5450                               SDValue &V0, SDValue &V1) {
5451   EVT VT = N->getValueType(0);
5452
5453   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5454   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5455          "Invalid Vector in input!");
5456
5457   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5458   bool CanFold = true;
5459   unsigned ExpectedVExtractIdx = BaseIdx;
5460   unsigned NumElts = LastIdx - BaseIdx;
5461   V0 = DAG.getUNDEF(VT);
5462   V1 = DAG.getUNDEF(VT);
5463
5464   // Check if N implements a horizontal binop.
5465   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5466     SDValue Op = N->getOperand(i + BaseIdx);
5467
5468     // Skip UNDEFs.
5469     if (Op->getOpcode() == ISD::UNDEF) {
5470       // Update the expected vector extract index.
5471       if (i * 2 == NumElts)
5472         ExpectedVExtractIdx = BaseIdx;
5473       ExpectedVExtractIdx += 2;
5474       continue;
5475     }
5476
5477     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5478
5479     if (!CanFold)
5480       break;
5481
5482     SDValue Op0 = Op.getOperand(0);
5483     SDValue Op1 = Op.getOperand(1);
5484
5485     // Try to match the following pattern:
5486     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5487     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5488         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5489         Op0.getOperand(0) == Op1.getOperand(0) &&
5490         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5491         isa<ConstantSDNode>(Op1.getOperand(1)));
5492     if (!CanFold)
5493       break;
5494
5495     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5496     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5497
5498     if (i * 2 < NumElts) {
5499       if (V0.getOpcode() == ISD::UNDEF) {
5500         V0 = Op0.getOperand(0);
5501         if (V0.getValueType() != VT)
5502           return false;
5503       }
5504     } else {
5505       if (V1.getOpcode() == ISD::UNDEF) {
5506         V1 = Op0.getOperand(0);
5507         if (V1.getValueType() != VT)
5508           return false;
5509       }
5510       if (i * 2 == NumElts)
5511         ExpectedVExtractIdx = BaseIdx;
5512     }
5513
5514     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5515     if (I0 == ExpectedVExtractIdx)
5516       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5517     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5518       // Try to match the following dag sequence:
5519       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5520       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5521     } else
5522       CanFold = false;
5523
5524     ExpectedVExtractIdx += 2;
5525   }
5526
5527   return CanFold;
5528 }
5529
5530 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5531 /// a concat_vector.
5532 ///
5533 /// This is a helper function of LowerToHorizontalOp().
5534 /// This function expects two 256-bit vectors called V0 and V1.
5535 /// At first, each vector is split into two separate 128-bit vectors.
5536 /// Then, the resulting 128-bit vectors are used to implement two
5537 /// horizontal binary operations.
5538 ///
5539 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5540 ///
5541 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5542 /// the two new horizontal binop.
5543 /// When Mode is set, the first horizontal binop dag node would take as input
5544 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5545 /// horizontal binop dag node would take as input the lower 128-bit of V1
5546 /// and the upper 128-bit of V1.
5547 ///   Example:
5548 ///     HADD V0_LO, V0_HI
5549 ///     HADD V1_LO, V1_HI
5550 ///
5551 /// Otherwise, the first horizontal binop dag node takes as input the lower
5552 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5553 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5554 ///   Example:
5555 ///     HADD V0_LO, V1_LO
5556 ///     HADD V0_HI, V1_HI
5557 ///
5558 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5559 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5560 /// the upper 128-bits of the result.
5561 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5562                                      SDLoc DL, SelectionDAG &DAG,
5563                                      unsigned X86Opcode, bool Mode,
5564                                      bool isUndefLO, bool isUndefHI) {
5565   EVT VT = V0.getValueType();
5566   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5567          "Invalid nodes in input!");
5568
5569   unsigned NumElts = VT.getVectorNumElements();
5570   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5571   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5572   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5573   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5574   EVT NewVT = V0_LO.getValueType();
5575
5576   SDValue LO = DAG.getUNDEF(NewVT);
5577   SDValue HI = DAG.getUNDEF(NewVT);
5578
5579   if (Mode) {
5580     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5581     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5582       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5583     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5584       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5585   } else {
5586     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5587     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5588                        V1_LO->getOpcode() != ISD::UNDEF))
5589       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5590
5591     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5592                        V1_HI->getOpcode() != ISD::UNDEF))
5593       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5594   }
5595
5596   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5597 }
5598
5599 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5600 /// node.
5601 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5602                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5603   EVT VT = BV->getValueType(0);
5604   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5605       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5606     return SDValue();
5607
5608   SDLoc DL(BV);
5609   unsigned NumElts = VT.getVectorNumElements();
5610   SDValue InVec0 = DAG.getUNDEF(VT);
5611   SDValue InVec1 = DAG.getUNDEF(VT);
5612
5613   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5614           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5615
5616   // Odd-numbered elements in the input build vector are obtained from
5617   // adding two integer/float elements.
5618   // Even-numbered elements in the input build vector are obtained from
5619   // subtracting two integer/float elements.
5620   unsigned ExpectedOpcode = ISD::FSUB;
5621   unsigned NextExpectedOpcode = ISD::FADD;
5622   bool AddFound = false;
5623   bool SubFound = false;
5624
5625   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5626     SDValue Op = BV->getOperand(i);
5627
5628     // Skip 'undef' values.
5629     unsigned Opcode = Op.getOpcode();
5630     if (Opcode == ISD::UNDEF) {
5631       std::swap(ExpectedOpcode, NextExpectedOpcode);
5632       continue;
5633     }
5634
5635     // Early exit if we found an unexpected opcode.
5636     if (Opcode != ExpectedOpcode)
5637       return SDValue();
5638
5639     SDValue Op0 = Op.getOperand(0);
5640     SDValue Op1 = Op.getOperand(1);
5641
5642     // Try to match the following pattern:
5643     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5644     // Early exit if we cannot match that sequence.
5645     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5646         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5647         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5648         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5649         Op0.getOperand(1) != Op1.getOperand(1))
5650       return SDValue();
5651
5652     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5653     if (I0 != i)
5654       return SDValue();
5655
5656     // We found a valid add/sub node. Update the information accordingly.
5657     if (i & 1)
5658       AddFound = true;
5659     else
5660       SubFound = true;
5661
5662     // Update InVec0 and InVec1.
5663     if (InVec0.getOpcode() == ISD::UNDEF) {
5664       InVec0 = Op0.getOperand(0);
5665       if (InVec0.getValueType() != VT)
5666         return SDValue();
5667     }
5668     if (InVec1.getOpcode() == ISD::UNDEF) {
5669       InVec1 = Op1.getOperand(0);
5670       if (InVec1.getValueType() != VT)
5671         return SDValue();
5672     }
5673
5674     // Make sure that operands in input to each add/sub node always
5675     // come from a same pair of vectors.
5676     if (InVec0 != Op0.getOperand(0)) {
5677       if (ExpectedOpcode == ISD::FSUB)
5678         return SDValue();
5679
5680       // FADD is commutable. Try to commute the operands
5681       // and then test again.
5682       std::swap(Op0, Op1);
5683       if (InVec0 != Op0.getOperand(0))
5684         return SDValue();
5685     }
5686
5687     if (InVec1 != Op1.getOperand(0))
5688       return SDValue();
5689
5690     // Update the pair of expected opcodes.
5691     std::swap(ExpectedOpcode, NextExpectedOpcode);
5692   }
5693
5694   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5695   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5696       InVec1.getOpcode() != ISD::UNDEF)
5697     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5698
5699   return SDValue();
5700 }
5701
5702 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5703 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5704                                    const X86Subtarget *Subtarget,
5705                                    SelectionDAG &DAG) {
5706   EVT VT = BV->getValueType(0);
5707   unsigned NumElts = VT.getVectorNumElements();
5708   unsigned NumUndefsLO = 0;
5709   unsigned NumUndefsHI = 0;
5710   unsigned Half = NumElts/2;
5711
5712   // Count the number of UNDEF operands in the build_vector in input.
5713   for (unsigned i = 0, e = Half; i != e; ++i)
5714     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5715       NumUndefsLO++;
5716
5717   for (unsigned i = Half, e = NumElts; i != e; ++i)
5718     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5719       NumUndefsHI++;
5720
5721   // Early exit if this is either a build_vector of all UNDEFs or all the
5722   // operands but one are UNDEF.
5723   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5724     return SDValue();
5725
5726   SDLoc DL(BV);
5727   SDValue InVec0, InVec1;
5728   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5729     // Try to match an SSE3 float HADD/HSUB.
5730     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5731       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5732
5733     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5734       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5735   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5736     // Try to match an SSSE3 integer HADD/HSUB.
5737     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5738       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5739
5740     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5741       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5742   }
5743
5744   if (!Subtarget->hasAVX())
5745     return SDValue();
5746
5747   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5748     // Try to match an AVX horizontal add/sub of packed single/double
5749     // precision floating point values from 256-bit vectors.
5750     SDValue InVec2, InVec3;
5751     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5752         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5753         ((InVec0.getOpcode() == ISD::UNDEF ||
5754           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5755         ((InVec1.getOpcode() == ISD::UNDEF ||
5756           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5757       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5758
5759     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5760         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5761         ((InVec0.getOpcode() == ISD::UNDEF ||
5762           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5763         ((InVec1.getOpcode() == ISD::UNDEF ||
5764           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5765       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5766   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5767     // Try to match an AVX2 horizontal add/sub of signed integers.
5768     SDValue InVec2, InVec3;
5769     unsigned X86Opcode;
5770     bool CanFold = true;
5771
5772     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5773         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5774         ((InVec0.getOpcode() == ISD::UNDEF ||
5775           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5776         ((InVec1.getOpcode() == ISD::UNDEF ||
5777           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5778       X86Opcode = X86ISD::HADD;
5779     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5780         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5781         ((InVec0.getOpcode() == ISD::UNDEF ||
5782           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5783         ((InVec1.getOpcode() == ISD::UNDEF ||
5784           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5785       X86Opcode = X86ISD::HSUB;
5786     else
5787       CanFold = false;
5788
5789     if (CanFold) {
5790       // Fold this build_vector into a single horizontal add/sub.
5791       // Do this only if the target has AVX2.
5792       if (Subtarget->hasAVX2())
5793         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5794
5795       // Do not try to expand this build_vector into a pair of horizontal
5796       // add/sub if we can emit a pair of scalar add/sub.
5797       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5798         return SDValue();
5799
5800       // Convert this build_vector into a pair of horizontal binop followed by
5801       // a concat vector.
5802       bool isUndefLO = NumUndefsLO == Half;
5803       bool isUndefHI = NumUndefsHI == Half;
5804       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5805                                    isUndefLO, isUndefHI);
5806     }
5807   }
5808
5809   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5810        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5811     unsigned X86Opcode;
5812     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5813       X86Opcode = X86ISD::HADD;
5814     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5815       X86Opcode = X86ISD::HSUB;
5816     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5817       X86Opcode = X86ISD::FHADD;
5818     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5819       X86Opcode = X86ISD::FHSUB;
5820     else
5821       return SDValue();
5822
5823     // Don't try to expand this build_vector into a pair of horizontal add/sub
5824     // if we can simply emit a pair of scalar add/sub.
5825     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5826       return SDValue();
5827
5828     // Convert this build_vector into two horizontal add/sub followed by
5829     // a concat vector.
5830     bool isUndefLO = NumUndefsLO == Half;
5831     bool isUndefHI = NumUndefsHI == Half;
5832     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5833                                  isUndefLO, isUndefHI);
5834   }
5835
5836   return SDValue();
5837 }
5838
5839 SDValue
5840 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5841   SDLoc dl(Op);
5842
5843   MVT VT = Op.getSimpleValueType();
5844   MVT ExtVT = VT.getVectorElementType();
5845   unsigned NumElems = Op.getNumOperands();
5846
5847   // Generate vectors for predicate vectors.
5848   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5849     return LowerBUILD_VECTORvXi1(Op, DAG);
5850
5851   // Vectors containing all zeros can be matched by pxor and xorps later
5852   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5853     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5854     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5855     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5856       return Op;
5857
5858     return getZeroVector(VT, Subtarget, DAG, dl);
5859   }
5860
5861   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5862   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5863   // vpcmpeqd on 256-bit vectors.
5864   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5865     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5866       return Op;
5867
5868     if (!VT.is512BitVector())
5869       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5870   }
5871
5872   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5873   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5874     return AddSub;
5875   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5876     return HorizontalOp;
5877   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5878     return Broadcast;
5879
5880   unsigned EVTBits = ExtVT.getSizeInBits();
5881
5882   unsigned NumZero  = 0;
5883   unsigned NumNonZero = 0;
5884   unsigned NonZeros = 0;
5885   bool IsAllConstants = true;
5886   SmallSet<SDValue, 8> Values;
5887   for (unsigned i = 0; i < NumElems; ++i) {
5888     SDValue Elt = Op.getOperand(i);
5889     if (Elt.getOpcode() == ISD::UNDEF)
5890       continue;
5891     Values.insert(Elt);
5892     if (Elt.getOpcode() != ISD::Constant &&
5893         Elt.getOpcode() != ISD::ConstantFP)
5894       IsAllConstants = false;
5895     if (X86::isZeroNode(Elt))
5896       NumZero++;
5897     else {
5898       NonZeros |= (1 << i);
5899       NumNonZero++;
5900     }
5901   }
5902
5903   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5904   if (NumNonZero == 0)
5905     return DAG.getUNDEF(VT);
5906
5907   // Special case for single non-zero, non-undef, element.
5908   if (NumNonZero == 1) {
5909     unsigned Idx = countTrailingZeros(NonZeros);
5910     SDValue Item = Op.getOperand(Idx);
5911
5912     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5913     // the value are obviously zero, truncate the value to i32 and do the
5914     // insertion that way.  Only do this if the value is non-constant or if the
5915     // value is a constant being inserted into element 0.  It is cheaper to do
5916     // a constant pool load than it is to do a movd + shuffle.
5917     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5918         (!IsAllConstants || Idx == 0)) {
5919       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5920         // Handle SSE only.
5921         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5922         EVT VecVT = MVT::v4i32;
5923
5924         // Truncate the value (which may itself be a constant) to i32, and
5925         // convert it to a vector with movd (S2V+shuffle to zero extend).
5926         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5927         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5928         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5929                                       Item, Idx * 2, true, Subtarget, DAG));
5930       }
5931     }
5932
5933     // If we have a constant or non-constant insertion into the low element of
5934     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5935     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5936     // depending on what the source datatype is.
5937     if (Idx == 0) {
5938       if (NumZero == 0)
5939         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5940
5941       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5942           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5943         if (VT.is512BitVector()) {
5944           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5945           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5946                              Item, DAG.getIntPtrConstant(0, dl));
5947         }
5948         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5949                "Expected an SSE value type!");
5950         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5951         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5952         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5953       }
5954
5955       // We can't directly insert an i8 or i16 into a vector, so zero extend
5956       // it to i32 first.
5957       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5958         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5959         if (VT.is256BitVector()) {
5960           if (Subtarget->hasAVX()) {
5961             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5962             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5963           } else {
5964             // Without AVX, we need to extend to a 128-bit vector and then
5965             // insert into the 256-bit vector.
5966             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5967             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5968             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5969           }
5970         } else {
5971           assert(VT.is128BitVector() && "Expected an SSE value type!");
5972           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5973           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5974         }
5975         return DAG.getBitcast(VT, Item);
5976       }
5977     }
5978
5979     // Is it a vector logical left shift?
5980     if (NumElems == 2 && Idx == 1 &&
5981         X86::isZeroNode(Op.getOperand(0)) &&
5982         !X86::isZeroNode(Op.getOperand(1))) {
5983       unsigned NumBits = VT.getSizeInBits();
5984       return getVShift(true, VT,
5985                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5986                                    VT, Op.getOperand(1)),
5987                        NumBits/2, DAG, *this, dl);
5988     }
5989
5990     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5991       return SDValue();
5992
5993     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5994     // is a non-constant being inserted into an element other than the low one,
5995     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5996     // movd/movss) to move this into the low element, then shuffle it into
5997     // place.
5998     if (EVTBits == 32) {
5999       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
6000       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
6001     }
6002   }
6003
6004   // Splat is obviously ok. Let legalizer expand it to a shuffle.
6005   if (Values.size() == 1) {
6006     if (EVTBits == 32) {
6007       // Instead of a shuffle like this:
6008       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
6009       // Check if it's possible to issue this instead.
6010       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
6011       unsigned Idx = countTrailingZeros(NonZeros);
6012       SDValue Item = Op.getOperand(Idx);
6013       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
6014         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
6015     }
6016     return SDValue();
6017   }
6018
6019   // A vector full of immediates; various special cases are already
6020   // handled, so this is best done with a single constant-pool load.
6021   if (IsAllConstants)
6022     return SDValue();
6023
6024   // For AVX-length vectors, see if we can use a vector load to get all of the
6025   // elements, otherwise build the individual 128-bit pieces and use
6026   // shuffles to put them in place.
6027   if (VT.is256BitVector() || VT.is512BitVector()) {
6028     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
6029
6030     // Check for a build vector of consecutive loads.
6031     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6032       return LD;
6033
6034     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
6035
6036     // Build both the lower and upper subvector.
6037     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6038                                 makeArrayRef(&V[0], NumElems/2));
6039     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
6040                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
6041
6042     // Recreate the wider vector with the lower and upper part.
6043     if (VT.is256BitVector())
6044       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6045     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
6046   }
6047
6048   // Let legalizer expand 2-wide build_vectors.
6049   if (EVTBits == 64) {
6050     if (NumNonZero == 1) {
6051       // One half is zero or undef.
6052       unsigned Idx = countTrailingZeros(NonZeros);
6053       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6054                                  Op.getOperand(Idx));
6055       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6056     }
6057     return SDValue();
6058   }
6059
6060   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6061   if (EVTBits == 8 && NumElems == 16)
6062     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6063                                         Subtarget, *this))
6064       return V;
6065
6066   if (EVTBits == 16 && NumElems == 8)
6067     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6068                                       Subtarget, *this))
6069       return V;
6070
6071   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6072   if (EVTBits == 32 && NumElems == 4)
6073     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6074       return V;
6075
6076   // If element VT is == 32 bits, turn it into a number of shuffles.
6077   SmallVector<SDValue, 8> V(NumElems);
6078   if (NumElems == 4 && NumZero > 0) {
6079     for (unsigned i = 0; i < 4; ++i) {
6080       bool isZero = !(NonZeros & (1 << i));
6081       if (isZero)
6082         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6083       else
6084         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6085     }
6086
6087     for (unsigned i = 0; i < 2; ++i) {
6088       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6089         default: break;
6090         case 0:
6091           V[i] = V[i*2];  // Must be a zero vector.
6092           break;
6093         case 1:
6094           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6095           break;
6096         case 2:
6097           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6098           break;
6099         case 3:
6100           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6101           break;
6102       }
6103     }
6104
6105     bool Reverse1 = (NonZeros & 0x3) == 2;
6106     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6107     int MaskVec[] = {
6108       Reverse1 ? 1 : 0,
6109       Reverse1 ? 0 : 1,
6110       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6111       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6112     };
6113     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6114   }
6115
6116   if (Values.size() > 1 && VT.is128BitVector()) {
6117     // Check for a build vector of consecutive loads.
6118     for (unsigned i = 0; i < NumElems; ++i)
6119       V[i] = Op.getOperand(i);
6120
6121     // Check for elements which are consecutive loads.
6122     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6123       return LD;
6124
6125     // Check for a build vector from mostly shuffle plus few inserting.
6126     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6127       return Sh;
6128
6129     // For SSE 4.1, use insertps to put the high elements into the low element.
6130     if (Subtarget->hasSSE41()) {
6131       SDValue Result;
6132       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6133         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6134       else
6135         Result = DAG.getUNDEF(VT);
6136
6137       for (unsigned i = 1; i < NumElems; ++i) {
6138         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6139         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6140                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6141       }
6142       return Result;
6143     }
6144
6145     // Otherwise, expand into a number of unpckl*, start by extending each of
6146     // our (non-undef) elements to the full vector width with the element in the
6147     // bottom slot of the vector (which generates no code for SSE).
6148     for (unsigned i = 0; i < NumElems; ++i) {
6149       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6150         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6151       else
6152         V[i] = DAG.getUNDEF(VT);
6153     }
6154
6155     // Next, we iteratively mix elements, e.g. for v4f32:
6156     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6157     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6158     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6159     unsigned EltStride = NumElems >> 1;
6160     while (EltStride != 0) {
6161       for (unsigned i = 0; i < EltStride; ++i) {
6162         // If V[i+EltStride] is undef and this is the first round of mixing,
6163         // then it is safe to just drop this shuffle: V[i] is already in the
6164         // right place, the one element (since it's the first round) being
6165         // inserted as undef can be dropped.  This isn't safe for successive
6166         // rounds because they will permute elements within both vectors.
6167         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6168             EltStride == NumElems/2)
6169           continue;
6170
6171         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6172       }
6173       EltStride >>= 1;
6174     }
6175     return V[0];
6176   }
6177   return SDValue();
6178 }
6179
6180 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6181 // to create 256-bit vectors from two other 128-bit ones.
6182 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6183   SDLoc dl(Op);
6184   MVT ResVT = Op.getSimpleValueType();
6185
6186   assert((ResVT.is256BitVector() ||
6187           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6188
6189   SDValue V1 = Op.getOperand(0);
6190   SDValue V2 = Op.getOperand(1);
6191   unsigned NumElems = ResVT.getVectorNumElements();
6192   if (ResVT.is256BitVector())
6193     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6194
6195   if (Op.getNumOperands() == 4) {
6196     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6197                                 ResVT.getVectorNumElements()/2);
6198     SDValue V3 = Op.getOperand(2);
6199     SDValue V4 = Op.getOperand(3);
6200     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6201       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6202   }
6203   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6204 }
6205
6206 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6207                                        const X86Subtarget *Subtarget,
6208                                        SelectionDAG & DAG) {
6209   SDLoc dl(Op);
6210   MVT ResVT = Op.getSimpleValueType();
6211   unsigned NumOfOperands = Op.getNumOperands();
6212
6213   assert(isPowerOf2_32(NumOfOperands) &&
6214          "Unexpected number of operands in CONCAT_VECTORS");
6215
6216   if (NumOfOperands > 2) {
6217     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6218                                   ResVT.getVectorNumElements()/2);
6219     SmallVector<SDValue, 2> Ops;
6220     for (unsigned i = 0; i < NumOfOperands/2; i++)
6221       Ops.push_back(Op.getOperand(i));
6222     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6223     Ops.clear();
6224     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6225       Ops.push_back(Op.getOperand(i));
6226     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6227     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6228   }
6229
6230   SDValue V1 = Op.getOperand(0);
6231   SDValue V2 = Op.getOperand(1);
6232   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6233   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6234
6235   if (IsZeroV1 && IsZeroV2)
6236     return getZeroVector(ResVT, Subtarget, DAG, dl);
6237
6238   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6239   SDValue Undef = DAG.getUNDEF(ResVT);
6240   unsigned NumElems = ResVT.getVectorNumElements();
6241   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6242
6243   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6244   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6245   if (IsZeroV1)
6246     return V2;
6247
6248   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6249   // Zero the upper bits of V1
6250   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6251   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6252   if (IsZeroV2)
6253     return V1;
6254   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6255 }
6256
6257 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6258                                    const X86Subtarget *Subtarget,
6259                                    SelectionDAG &DAG) {
6260   MVT VT = Op.getSimpleValueType();
6261   if (VT.getVectorElementType() == MVT::i1)
6262     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6263
6264   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6265          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6266           Op.getNumOperands() == 4)));
6267
6268   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6269   // from two other 128-bit ones.
6270
6271   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6272   return LowerAVXCONCAT_VECTORS(Op, DAG);
6273 }
6274
6275
6276 //===----------------------------------------------------------------------===//
6277 // Vector shuffle lowering
6278 //
6279 // This is an experimental code path for lowering vector shuffles on x86. It is
6280 // designed to handle arbitrary vector shuffles and blends, gracefully
6281 // degrading performance as necessary. It works hard to recognize idiomatic
6282 // shuffles and lower them to optimal instruction patterns without leaving
6283 // a framework that allows reasonably efficient handling of all vector shuffle
6284 // patterns.
6285 //===----------------------------------------------------------------------===//
6286
6287 /// \brief Tiny helper function to identify a no-op mask.
6288 ///
6289 /// This is a somewhat boring predicate function. It checks whether the mask
6290 /// array input, which is assumed to be a single-input shuffle mask of the kind
6291 /// used by the X86 shuffle instructions (not a fully general
6292 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6293 /// in-place shuffle are 'no-op's.
6294 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6295   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6296     if (Mask[i] != -1 && Mask[i] != i)
6297       return false;
6298   return true;
6299 }
6300
6301 /// \brief Helper function to classify a mask as a single-input mask.
6302 ///
6303 /// This isn't a generic single-input test because in the vector shuffle
6304 /// lowering we canonicalize single inputs to be the first input operand. This
6305 /// means we can more quickly test for a single input by only checking whether
6306 /// an input from the second operand exists. We also assume that the size of
6307 /// mask corresponds to the size of the input vectors which isn't true in the
6308 /// fully general case.
6309 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6310   for (int M : Mask)
6311     if (M >= (int)Mask.size())
6312       return false;
6313   return true;
6314 }
6315
6316 /// \brief Test whether there are elements crossing 128-bit lanes in this
6317 /// shuffle mask.
6318 ///
6319 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6320 /// and we routinely test for these.
6321 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6322   int LaneSize = 128 / VT.getScalarSizeInBits();
6323   int Size = Mask.size();
6324   for (int i = 0; i < Size; ++i)
6325     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6326       return true;
6327   return false;
6328 }
6329
6330 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6331 ///
6332 /// This checks a shuffle mask to see if it is performing the same
6333 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6334 /// that it is also not lane-crossing. It may however involve a blend from the
6335 /// same lane of a second vector.
6336 ///
6337 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6338 /// non-trivial to compute in the face of undef lanes. The representation is
6339 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6340 /// entries from both V1 and V2 inputs to the wider mask.
6341 static bool
6342 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6343                                 SmallVectorImpl<int> &RepeatedMask) {
6344   int LaneSize = 128 / VT.getScalarSizeInBits();
6345   RepeatedMask.resize(LaneSize, -1);
6346   int Size = Mask.size();
6347   for (int i = 0; i < Size; ++i) {
6348     if (Mask[i] < 0)
6349       continue;
6350     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6351       // This entry crosses lanes, so there is no way to model this shuffle.
6352       return false;
6353
6354     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6355     if (RepeatedMask[i % LaneSize] == -1)
6356       // This is the first non-undef entry in this slot of a 128-bit lane.
6357       RepeatedMask[i % LaneSize] =
6358           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6359     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6360       // Found a mismatch with the repeated mask.
6361       return false;
6362   }
6363   return true;
6364 }
6365
6366 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6367 /// arguments.
6368 ///
6369 /// This is a fast way to test a shuffle mask against a fixed pattern:
6370 ///
6371 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6372 ///
6373 /// It returns true if the mask is exactly as wide as the argument list, and
6374 /// each element of the mask is either -1 (signifying undef) or the value given
6375 /// in the argument.
6376 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6377                                 ArrayRef<int> ExpectedMask) {
6378   if (Mask.size() != ExpectedMask.size())
6379     return false;
6380
6381   int Size = Mask.size();
6382
6383   // If the values are build vectors, we can look through them to find
6384   // equivalent inputs that make the shuffles equivalent.
6385   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6386   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6387
6388   for (int i = 0; i < Size; ++i)
6389     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6390       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6391       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6392       if (!MaskBV || !ExpectedBV ||
6393           MaskBV->getOperand(Mask[i] % Size) !=
6394               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6395         return false;
6396     }
6397
6398   return true;
6399 }
6400
6401 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6402 ///
6403 /// This helper function produces an 8-bit shuffle immediate corresponding to
6404 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6405 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6406 /// example.
6407 ///
6408 /// NB: We rely heavily on "undef" masks preserving the input lane.
6409 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6410                                           SelectionDAG &DAG) {
6411   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6412   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6413   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6414   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6415   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6416
6417   unsigned Imm = 0;
6418   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6419   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6420   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6421   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6422   return DAG.getConstant(Imm, DL, MVT::i8);
6423 }
6424
6425 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6426 ///
6427 /// This is used as a fallback approach when first class blend instructions are
6428 /// unavailable. Currently it is only suitable for integer vectors, but could
6429 /// be generalized for floating point vectors if desirable.
6430 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6431                                             SDValue V2, ArrayRef<int> Mask,
6432                                             SelectionDAG &DAG) {
6433   assert(VT.isInteger() && "Only supports integer vector types!");
6434   MVT EltVT = VT.getScalarType();
6435   int NumEltBits = EltVT.getSizeInBits();
6436   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6437   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6438                                     EltVT);
6439   SmallVector<SDValue, 16> MaskOps;
6440   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6441     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6442       return SDValue(); // Shuffled input!
6443     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6444   }
6445
6446   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6447   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6448   // We have to cast V2 around.
6449   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6450   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6451                                       DAG.getBitcast(MaskVT, V1Mask),
6452                                       DAG.getBitcast(MaskVT, V2)));
6453   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6454 }
6455
6456 /// \brief Try to emit a blend instruction for a shuffle.
6457 ///
6458 /// This doesn't do any checks for the availability of instructions for blending
6459 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6460 /// be matched in the backend with the type given. What it does check for is
6461 /// that the shuffle mask is in fact a blend.
6462 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6463                                          SDValue V2, ArrayRef<int> Mask,
6464                                          const X86Subtarget *Subtarget,
6465                                          SelectionDAG &DAG) {
6466   unsigned BlendMask = 0;
6467   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6468     if (Mask[i] >= Size) {
6469       if (Mask[i] != i + Size)
6470         return SDValue(); // Shuffled V2 input!
6471       BlendMask |= 1u << i;
6472       continue;
6473     }
6474     if (Mask[i] >= 0 && Mask[i] != i)
6475       return SDValue(); // Shuffled V1 input!
6476   }
6477   switch (VT.SimpleTy) {
6478   case MVT::v2f64:
6479   case MVT::v4f32:
6480   case MVT::v4f64:
6481   case MVT::v8f32:
6482     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6483                        DAG.getConstant(BlendMask, DL, MVT::i8));
6484
6485   case MVT::v4i64:
6486   case MVT::v8i32:
6487     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6488     // FALLTHROUGH
6489   case MVT::v2i64:
6490   case MVT::v4i32:
6491     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6492     // that instruction.
6493     if (Subtarget->hasAVX2()) {
6494       // Scale the blend by the number of 32-bit dwords per element.
6495       int Scale =  VT.getScalarSizeInBits() / 32;
6496       BlendMask = 0;
6497       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6498         if (Mask[i] >= Size)
6499           for (int j = 0; j < Scale; ++j)
6500             BlendMask |= 1u << (i * Scale + j);
6501
6502       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6503       V1 = DAG.getBitcast(BlendVT, V1);
6504       V2 = DAG.getBitcast(BlendVT, V2);
6505       return DAG.getBitcast(
6506           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6507                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6508     }
6509     // FALLTHROUGH
6510   case MVT::v8i16: {
6511     // For integer shuffles we need to expand the mask and cast the inputs to
6512     // v8i16s prior to blending.
6513     int Scale = 8 / VT.getVectorNumElements();
6514     BlendMask = 0;
6515     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6516       if (Mask[i] >= Size)
6517         for (int j = 0; j < Scale; ++j)
6518           BlendMask |= 1u << (i * Scale + j);
6519
6520     V1 = DAG.getBitcast(MVT::v8i16, V1);
6521     V2 = DAG.getBitcast(MVT::v8i16, V2);
6522     return DAG.getBitcast(VT,
6523                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6524                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6525   }
6526
6527   case MVT::v16i16: {
6528     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6529     SmallVector<int, 8> RepeatedMask;
6530     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6531       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6532       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6533       BlendMask = 0;
6534       for (int i = 0; i < 8; ++i)
6535         if (RepeatedMask[i] >= 16)
6536           BlendMask |= 1u << i;
6537       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6538                          DAG.getConstant(BlendMask, DL, MVT::i8));
6539     }
6540   }
6541     // FALLTHROUGH
6542   case MVT::v16i8:
6543   case MVT::v32i8: {
6544     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6545            "256-bit byte-blends require AVX2 support!");
6546
6547     // Scale the blend by the number of bytes per element.
6548     int Scale = VT.getScalarSizeInBits() / 8;
6549
6550     // This form of blend is always done on bytes. Compute the byte vector
6551     // type.
6552     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6553
6554     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6555     // mix of LLVM's code generator and the x86 backend. We tell the code
6556     // generator that boolean values in the elements of an x86 vector register
6557     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6558     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6559     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6560     // of the element (the remaining are ignored) and 0 in that high bit would
6561     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6562     // the LLVM model for boolean values in vector elements gets the relevant
6563     // bit set, it is set backwards and over constrained relative to x86's
6564     // actual model.
6565     SmallVector<SDValue, 32> VSELECTMask;
6566     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6567       for (int j = 0; j < Scale; ++j)
6568         VSELECTMask.push_back(
6569             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6570                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6571                                           MVT::i8));
6572
6573     V1 = DAG.getBitcast(BlendVT, V1);
6574     V2 = DAG.getBitcast(BlendVT, V2);
6575     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6576                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6577                                                       BlendVT, VSELECTMask),
6578                                           V1, V2));
6579   }
6580
6581   default:
6582     llvm_unreachable("Not a supported integer vector type!");
6583   }
6584 }
6585
6586 /// \brief Try to lower as a blend of elements from two inputs followed by
6587 /// a single-input permutation.
6588 ///
6589 /// This matches the pattern where we can blend elements from two inputs and
6590 /// then reduce the shuffle to a single-input permutation.
6591 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6592                                                    SDValue V2,
6593                                                    ArrayRef<int> Mask,
6594                                                    SelectionDAG &DAG) {
6595   // We build up the blend mask while checking whether a blend is a viable way
6596   // to reduce the shuffle.
6597   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6598   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6599
6600   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6601     if (Mask[i] < 0)
6602       continue;
6603
6604     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6605
6606     if (BlendMask[Mask[i] % Size] == -1)
6607       BlendMask[Mask[i] % Size] = Mask[i];
6608     else if (BlendMask[Mask[i] % Size] != Mask[i])
6609       return SDValue(); // Can't blend in the needed input!
6610
6611     PermuteMask[i] = Mask[i] % Size;
6612   }
6613
6614   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6615   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6616 }
6617
6618 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6619 /// blends and permutes.
6620 ///
6621 /// This matches the extremely common pattern for handling combined
6622 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6623 /// operations. It will try to pick the best arrangement of shuffles and
6624 /// blends.
6625 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6626                                                           SDValue V1,
6627                                                           SDValue V2,
6628                                                           ArrayRef<int> Mask,
6629                                                           SelectionDAG &DAG) {
6630   // Shuffle the input elements into the desired positions in V1 and V2 and
6631   // blend them together.
6632   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6633   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6634   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6635   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6636     if (Mask[i] >= 0 && Mask[i] < Size) {
6637       V1Mask[i] = Mask[i];
6638       BlendMask[i] = i;
6639     } else if (Mask[i] >= Size) {
6640       V2Mask[i] = Mask[i] - Size;
6641       BlendMask[i] = i + Size;
6642     }
6643
6644   // Try to lower with the simpler initial blend strategy unless one of the
6645   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6646   // shuffle may be able to fold with a load or other benefit. However, when
6647   // we'll have to do 2x as many shuffles in order to achieve this, blending
6648   // first is a better strategy.
6649   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6650     if (SDValue BlendPerm =
6651             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6652       return BlendPerm;
6653
6654   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6655   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6656   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6657 }
6658
6659 /// \brief Try to lower a vector shuffle as a byte rotation.
6660 ///
6661 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6662 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6663 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6664 /// try to generically lower a vector shuffle through such an pattern. It
6665 /// does not check for the profitability of lowering either as PALIGNR or
6666 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6667 /// This matches shuffle vectors that look like:
6668 ///
6669 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6670 ///
6671 /// Essentially it concatenates V1 and V2, shifts right by some number of
6672 /// elements, and takes the low elements as the result. Note that while this is
6673 /// specified as a *right shift* because x86 is little-endian, it is a *left
6674 /// rotate* of the vector lanes.
6675 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6676                                               SDValue V2,
6677                                               ArrayRef<int> Mask,
6678                                               const X86Subtarget *Subtarget,
6679                                               SelectionDAG &DAG) {
6680   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6681
6682   int NumElts = Mask.size();
6683   int NumLanes = VT.getSizeInBits() / 128;
6684   int NumLaneElts = NumElts / NumLanes;
6685
6686   // We need to detect various ways of spelling a rotation:
6687   //   [11, 12, 13, 14, 15,  0,  1,  2]
6688   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6689   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6690   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6691   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6692   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6693   int Rotation = 0;
6694   SDValue Lo, Hi;
6695   for (int l = 0; l < NumElts; l += NumLaneElts) {
6696     for (int i = 0; i < NumLaneElts; ++i) {
6697       if (Mask[l + i] == -1)
6698         continue;
6699       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6700
6701       // Get the mod-Size index and lane correct it.
6702       int LaneIdx = (Mask[l + i] % NumElts) - l;
6703       // Make sure it was in this lane.
6704       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6705         return SDValue();
6706
6707       // Determine where a rotated vector would have started.
6708       int StartIdx = i - LaneIdx;
6709       if (StartIdx == 0)
6710         // The identity rotation isn't interesting, stop.
6711         return SDValue();
6712
6713       // If we found the tail of a vector the rotation must be the missing
6714       // front. If we found the head of a vector, it must be how much of the
6715       // head.
6716       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6717
6718       if (Rotation == 0)
6719         Rotation = CandidateRotation;
6720       else if (Rotation != CandidateRotation)
6721         // The rotations don't match, so we can't match this mask.
6722         return SDValue();
6723
6724       // Compute which value this mask is pointing at.
6725       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6726
6727       // Compute which of the two target values this index should be assigned
6728       // to. This reflects whether the high elements are remaining or the low
6729       // elements are remaining.
6730       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6731
6732       // Either set up this value if we've not encountered it before, or check
6733       // that it remains consistent.
6734       if (!TargetV)
6735         TargetV = MaskV;
6736       else if (TargetV != MaskV)
6737         // This may be a rotation, but it pulls from the inputs in some
6738         // unsupported interleaving.
6739         return SDValue();
6740     }
6741   }
6742
6743   // Check that we successfully analyzed the mask, and normalize the results.
6744   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6745   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6746   if (!Lo)
6747     Lo = Hi;
6748   else if (!Hi)
6749     Hi = Lo;
6750
6751   // The actual rotate instruction rotates bytes, so we need to scale the
6752   // rotation based on how many bytes are in the vector lane.
6753   int Scale = 16 / NumLaneElts;
6754
6755   // SSSE3 targets can use the palignr instruction.
6756   if (Subtarget->hasSSSE3()) {
6757     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6758     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6759     Lo = DAG.getBitcast(AlignVT, Lo);
6760     Hi = DAG.getBitcast(AlignVT, Hi);
6761
6762     return DAG.getBitcast(
6763         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6764                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6765   }
6766
6767   assert(VT.getSizeInBits() == 128 &&
6768          "Rotate-based lowering only supports 128-bit lowering!");
6769   assert(Mask.size() <= 16 &&
6770          "Can shuffle at most 16 bytes in a 128-bit vector!");
6771
6772   // Default SSE2 implementation
6773   int LoByteShift = 16 - Rotation * Scale;
6774   int HiByteShift = Rotation * Scale;
6775
6776   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6777   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6778   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6779
6780   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6781                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6782   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6783                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6784   return DAG.getBitcast(VT,
6785                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6786 }
6787
6788 /// \brief Compute whether each element of a shuffle is zeroable.
6789 ///
6790 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6791 /// Either it is an undef element in the shuffle mask, the element of the input
6792 /// referenced is undef, or the element of the input referenced is known to be
6793 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6794 /// as many lanes with this technique as possible to simplify the remaining
6795 /// shuffle.
6796 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6797                                                      SDValue V1, SDValue V2) {
6798   SmallBitVector Zeroable(Mask.size(), false);
6799
6800   while (V1.getOpcode() == ISD::BITCAST)
6801     V1 = V1->getOperand(0);
6802   while (V2.getOpcode() == ISD::BITCAST)
6803     V2 = V2->getOperand(0);
6804
6805   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6806   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6807
6808   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6809     int M = Mask[i];
6810     // Handle the easy cases.
6811     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6812       Zeroable[i] = true;
6813       continue;
6814     }
6815
6816     // If this is an index into a build_vector node (which has the same number
6817     // of elements), dig out the input value and use it.
6818     SDValue V = M < Size ? V1 : V2;
6819     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6820       continue;
6821
6822     SDValue Input = V.getOperand(M % Size);
6823     // The UNDEF opcode check really should be dead code here, but not quite
6824     // worth asserting on (it isn't invalid, just unexpected).
6825     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6826       Zeroable[i] = true;
6827   }
6828
6829   return Zeroable;
6830 }
6831
6832 /// \brief Try to emit a bitmask instruction for a shuffle.
6833 ///
6834 /// This handles cases where we can model a blend exactly as a bitmask due to
6835 /// one of the inputs being zeroable.
6836 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6837                                            SDValue V2, ArrayRef<int> Mask,
6838                                            SelectionDAG &DAG) {
6839   MVT EltVT = VT.getScalarType();
6840   int NumEltBits = EltVT.getSizeInBits();
6841   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6842   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6843   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6844                                     IntEltVT);
6845   if (EltVT.isFloatingPoint()) {
6846     Zero = DAG.getBitcast(EltVT, Zero);
6847     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6848   }
6849   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6850   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6851   SDValue V;
6852   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6853     if (Zeroable[i])
6854       continue;
6855     if (Mask[i] % Size != i)
6856       return SDValue(); // Not a blend.
6857     if (!V)
6858       V = Mask[i] < Size ? V1 : V2;
6859     else if (V != (Mask[i] < Size ? V1 : V2))
6860       return SDValue(); // Can only let one input through the mask.
6861
6862     VMaskOps[i] = AllOnes;
6863   }
6864   if (!V)
6865     return SDValue(); // No non-zeroable elements!
6866
6867   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6868   V = DAG.getNode(VT.isFloatingPoint()
6869                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6870                   DL, VT, V, VMask);
6871   return V;
6872 }
6873
6874 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6875 ///
6876 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6877 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6878 /// matches elements from one of the input vectors shuffled to the left or
6879 /// right with zeroable elements 'shifted in'. It handles both the strictly
6880 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6881 /// quad word lane.
6882 ///
6883 /// PSHL : (little-endian) left bit shift.
6884 /// [ zz, 0, zz,  2 ]
6885 /// [ -1, 4, zz, -1 ]
6886 /// PSRL : (little-endian) right bit shift.
6887 /// [  1, zz,  3, zz]
6888 /// [ -1, -1,  7, zz]
6889 /// PSLLDQ : (little-endian) left byte shift
6890 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6891 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6892 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6893 /// PSRLDQ : (little-endian) right byte shift
6894 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6895 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6896 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6897 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6898                                          SDValue V2, ArrayRef<int> Mask,
6899                                          SelectionDAG &DAG) {
6900   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6901
6902   int Size = Mask.size();
6903   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6904
6905   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6906     for (int i = 0; i < Size; i += Scale)
6907       for (int j = 0; j < Shift; ++j)
6908         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6909           return false;
6910
6911     return true;
6912   };
6913
6914   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6915     for (int i = 0; i != Size; i += Scale) {
6916       unsigned Pos = Left ? i + Shift : i;
6917       unsigned Low = Left ? i : i + Shift;
6918       unsigned Len = Scale - Shift;
6919       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6920                                       Low + (V == V1 ? 0 : Size)))
6921         return SDValue();
6922     }
6923
6924     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6925     bool ByteShift = ShiftEltBits > 64;
6926     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6927                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6928     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6929
6930     // Normalize the scale for byte shifts to still produce an i64 element
6931     // type.
6932     Scale = ByteShift ? Scale / 2 : Scale;
6933
6934     // We need to round trip through the appropriate type for the shift.
6935     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6936     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6937     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6938            "Illegal integer vector type");
6939     V = DAG.getBitcast(ShiftVT, V);
6940
6941     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6942                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6943     return DAG.getBitcast(VT, V);
6944   };
6945
6946   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6947   // keep doubling the size of the integer elements up to that. We can
6948   // then shift the elements of the integer vector by whole multiples of
6949   // their width within the elements of the larger integer vector. Test each
6950   // multiple to see if we can find a match with the moved element indices
6951   // and that the shifted in elements are all zeroable.
6952   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6953     for (int Shift = 1; Shift != Scale; ++Shift)
6954       for (bool Left : {true, false})
6955         if (CheckZeros(Shift, Scale, Left))
6956           for (SDValue V : {V1, V2})
6957             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6958               return Match;
6959
6960   // no match
6961   return SDValue();
6962 }
6963
6964 /// \brief Try to lower a vector shuffle using SSE4a EXTRQ/INSERTQ.
6965 static SDValue lowerVectorShuffleWithSSE4A(SDLoc DL, MVT VT, SDValue V1,
6966                                            SDValue V2, ArrayRef<int> Mask,
6967                                            SelectionDAG &DAG) {
6968   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6969   assert(!Zeroable.all() && "Fully zeroable shuffle mask");
6970
6971   int Size = Mask.size();
6972   int HalfSize = Size / 2;
6973   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6974
6975   // Upper half must be undefined.
6976   if (!isUndefInRange(Mask, HalfSize, HalfSize))
6977     return SDValue();
6978
6979   // EXTRQ: Extract Len elements from lower half of source, starting at Idx.
6980   // Remainder of lower half result is zero and upper half is all undef.
6981   auto LowerAsEXTRQ = [&]() {
6982     // Determine the extraction length from the part of the
6983     // lower half that isn't zeroable.
6984     int Len = HalfSize;
6985     for (; Len >= 0; --Len)
6986       if (!Zeroable[Len - 1])
6987         break;
6988     assert(Len > 0 && "Zeroable shuffle mask");
6989
6990     // Attempt to match first Len sequential elements from the lower half.
6991     SDValue Src;
6992     int Idx = -1;
6993     for (int i = 0; i != Len; ++i) {
6994       int M = Mask[i];
6995       if (M < 0)
6996         continue;
6997       SDValue &V = (M < Size ? V1 : V2);
6998       M = M % Size;
6999
7000       // All mask elements must be in the lower half.
7001       if (M > HalfSize)
7002         return SDValue();
7003
7004       if (Idx < 0 || (Src == V && Idx == (M - i))) {
7005         Src = V;
7006         Idx = M - i;
7007         continue;
7008       }
7009       return SDValue();
7010     }
7011
7012     if (Idx < 0)
7013       return SDValue();
7014
7015     assert((Idx + Len) <= HalfSize && "Illegal extraction mask");
7016     int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7017     int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7018     return DAG.getNode(X86ISD::EXTRQI, DL, VT, Src,
7019                        DAG.getConstant(BitLen, DL, MVT::i8),
7020                        DAG.getConstant(BitIdx, DL, MVT::i8));
7021   };
7022
7023   if (SDValue ExtrQ = LowerAsEXTRQ())
7024     return ExtrQ;
7025
7026   // INSERTQ: Extract lowest Len elements from lower half of second source and
7027   // insert over first source, starting at Idx.
7028   // { A[0], .., A[Idx-1], B[0], .., B[Len-1], A[Idx+Len], .., UNDEF, ... }
7029   auto LowerAsInsertQ = [&]() {
7030     for (int Idx = 0; Idx != HalfSize; ++Idx) {
7031       SDValue Base;
7032
7033       // Attempt to match first source from mask before insertion point.
7034       if (isUndefInRange(Mask, 0, Idx)) {
7035         /* EMPTY */
7036       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, 0)) {
7037         Base = V1;
7038       } else if (isSequentialOrUndefInRange(Mask, 0, Idx, Size)) {
7039         Base = V2;
7040       } else {
7041         continue;
7042       }
7043
7044       // Extend the extraction length looking to match both the insertion of
7045       // the second source and the remaining elements of the first.
7046       for (int Hi = Idx + 1; Hi <= HalfSize; ++Hi) {
7047         SDValue Insert;
7048         int Len = Hi - Idx;
7049
7050         // Match insertion.
7051         if (isSequentialOrUndefInRange(Mask, Idx, Len, 0)) {
7052           Insert = V1;
7053         } else if (isSequentialOrUndefInRange(Mask, Idx, Len, Size)) {
7054           Insert = V2;
7055         } else {
7056           continue;
7057         }
7058
7059         // Match the remaining elements of the lower half.
7060         if (isUndefInRange(Mask, Hi, HalfSize - Hi)) {
7061           /* EMPTY */
7062         } else if ((!Base || (Base == V1)) &&
7063                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi, Hi)) {
7064           Base = V1;
7065         } else if ((!Base || (Base == V2)) &&
7066                    isSequentialOrUndefInRange(Mask, Hi, HalfSize - Hi,
7067                                               Size + Hi)) {
7068           Base = V2;
7069         } else {
7070           continue;
7071         }
7072
7073         // We may not have a base (first source) - this can safely be undefined.
7074         if (!Base)
7075           Base = DAG.getUNDEF(VT);
7076
7077         int BitLen = (Len * VT.getScalarSizeInBits()) & 0x3f;
7078         int BitIdx = (Idx * VT.getScalarSizeInBits()) & 0x3f;
7079         return DAG.getNode(X86ISD::INSERTQI, DL, VT, Base, Insert,
7080                            DAG.getConstant(BitLen, DL, MVT::i8),
7081                            DAG.getConstant(BitIdx, DL, MVT::i8));
7082       }
7083     }
7084
7085     return SDValue();
7086   };
7087
7088   if (SDValue InsertQ = LowerAsInsertQ())
7089     return InsertQ;
7090
7091   return SDValue();
7092 }
7093
7094 /// \brief Lower a vector shuffle as a zero or any extension.
7095 ///
7096 /// Given a specific number of elements, element bit width, and extension
7097 /// stride, produce either a zero or any extension based on the available
7098 /// features of the subtarget.
7099 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7100     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
7101     ArrayRef<int> Mask, const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7102   assert(Scale > 1 && "Need a scale to extend.");
7103   int NumElements = VT.getVectorNumElements();
7104   int EltBits = VT.getScalarSizeInBits();
7105   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
7106          "Only 8, 16, and 32 bit elements can be extended.");
7107   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
7108
7109   // Found a valid zext mask! Try various lowering strategies based on the
7110   // input type and available ISA extensions.
7111   if (Subtarget->hasSSE41()) {
7112     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
7113                                  NumElements / Scale);
7114     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
7115   }
7116
7117   // For any extends we can cheat for larger element sizes and use shuffle
7118   // instructions that can fold with a load and/or copy.
7119   if (AnyExt && EltBits == 32) {
7120     int PSHUFDMask[4] = {0, -1, 1, -1};
7121     return DAG.getBitcast(
7122         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7123                         DAG.getBitcast(MVT::v4i32, InputV),
7124                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
7125   }
7126   if (AnyExt && EltBits == 16 && Scale > 2) {
7127     int PSHUFDMask[4] = {0, -1, 0, -1};
7128     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
7129                          DAG.getBitcast(MVT::v4i32, InputV),
7130                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
7131     int PSHUFHWMask[4] = {1, -1, -1, -1};
7132     return DAG.getBitcast(
7133         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
7134                         DAG.getBitcast(MVT::v8i16, InputV),
7135                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
7136   }
7137
7138   // The SSE4A EXTRQ instruction can efficiently extend the first 2 lanes
7139   // to 64-bits.
7140   if ((Scale * EltBits) == 64 && EltBits < 32 && Subtarget->hasSSE4A()) {
7141     assert(NumElements == (int)Mask.size() && "Unexpected shuffle mask size!");
7142     assert(VT.getSizeInBits() == 128 && "Unexpected vector width!");
7143
7144     SDValue Lo = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7145                              DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7146                                          DAG.getConstant(EltBits, DL, MVT::i8),
7147                                          DAG.getConstant(0, DL, MVT::i8)));
7148     if (isUndefInRange(Mask, NumElements/2, NumElements/2))
7149       return DAG.getNode(ISD::BITCAST, DL, VT, Lo);
7150
7151     SDValue Hi =
7152         DAG.getNode(ISD::BITCAST, DL, MVT::v2i64,
7153                     DAG.getNode(X86ISD::EXTRQI, DL, VT, InputV,
7154                                 DAG.getConstant(EltBits, DL, MVT::i8),
7155                                 DAG.getConstant(EltBits, DL, MVT::i8)));
7156     return DAG.getNode(ISD::BITCAST, DL, VT,
7157                        DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, Lo, Hi));
7158   }
7159
7160   // If this would require more than 2 unpack instructions to expand, use
7161   // pshufb when available. We can only use more than 2 unpack instructions
7162   // when zero extending i8 elements which also makes it easier to use pshufb.
7163   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
7164     assert(NumElements == 16 && "Unexpected byte vector width!");
7165     SDValue PSHUFBMask[16];
7166     for (int i = 0; i < 16; ++i)
7167       PSHUFBMask[i] =
7168           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
7169     InputV = DAG.getBitcast(MVT::v16i8, InputV);
7170     return DAG.getBitcast(VT,
7171                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
7172                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
7173                                                   MVT::v16i8, PSHUFBMask)));
7174   }
7175
7176   // Otherwise emit a sequence of unpacks.
7177   do {
7178     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
7179     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
7180                          : getZeroVector(InputVT, Subtarget, DAG, DL);
7181     InputV = DAG.getBitcast(InputVT, InputV);
7182     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
7183     Scale /= 2;
7184     EltBits *= 2;
7185     NumElements /= 2;
7186   } while (Scale > 1);
7187   return DAG.getBitcast(VT, InputV);
7188 }
7189
7190 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
7191 ///
7192 /// This routine will try to do everything in its power to cleverly lower
7193 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
7194 /// check for the profitability of this lowering,  it tries to aggressively
7195 /// match this pattern. It will use all of the micro-architectural details it
7196 /// can to emit an efficient lowering. It handles both blends with all-zero
7197 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
7198 /// masking out later).
7199 ///
7200 /// The reason we have dedicated lowering for zext-style shuffles is that they
7201 /// are both incredibly common and often quite performance sensitive.
7202 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7203     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7204     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7205   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7206
7207   int Bits = VT.getSizeInBits();
7208   int NumElements = VT.getVectorNumElements();
7209   assert(VT.getScalarSizeInBits() <= 32 &&
7210          "Exceeds 32-bit integer zero extension limit");
7211   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7212
7213   // Define a helper function to check a particular ext-scale and lower to it if
7214   // valid.
7215   auto Lower = [&](int Scale) -> SDValue {
7216     SDValue InputV;
7217     bool AnyExt = true;
7218     for (int i = 0; i < NumElements; ++i) {
7219       if (Mask[i] == -1)
7220         continue; // Valid anywhere but doesn't tell us anything.
7221       if (i % Scale != 0) {
7222         // Each of the extended elements need to be zeroable.
7223         if (!Zeroable[i])
7224           return SDValue();
7225
7226         // We no longer are in the anyext case.
7227         AnyExt = false;
7228         continue;
7229       }
7230
7231       // Each of the base elements needs to be consecutive indices into the
7232       // same input vector.
7233       SDValue V = Mask[i] < NumElements ? V1 : V2;
7234       if (!InputV)
7235         InputV = V;
7236       else if (InputV != V)
7237         return SDValue(); // Flip-flopping inputs.
7238
7239       if (Mask[i] % NumElements != i / Scale)
7240         return SDValue(); // Non-consecutive strided elements.
7241     }
7242
7243     // If we fail to find an input, we have a zero-shuffle which should always
7244     // have already been handled.
7245     // FIXME: Maybe handle this here in case during blending we end up with one?
7246     if (!InputV)
7247       return SDValue();
7248
7249     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7250         DL, VT, Scale, AnyExt, InputV, Mask, Subtarget, DAG);
7251   };
7252
7253   // The widest scale possible for extending is to a 64-bit integer.
7254   assert(Bits % 64 == 0 &&
7255          "The number of bits in a vector must be divisible by 64 on x86!");
7256   int NumExtElements = Bits / 64;
7257
7258   // Each iteration, try extending the elements half as much, but into twice as
7259   // many elements.
7260   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7261     assert(NumElements % NumExtElements == 0 &&
7262            "The input vector size must be divisible by the extended size.");
7263     if (SDValue V = Lower(NumElements / NumExtElements))
7264       return V;
7265   }
7266
7267   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7268   if (Bits != 128)
7269     return SDValue();
7270
7271   // Returns one of the source operands if the shuffle can be reduced to a
7272   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7273   auto CanZExtLowHalf = [&]() {
7274     for (int i = NumElements / 2; i != NumElements; ++i)
7275       if (!Zeroable[i])
7276         return SDValue();
7277     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7278       return V1;
7279     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7280       return V2;
7281     return SDValue();
7282   };
7283
7284   if (SDValue V = CanZExtLowHalf()) {
7285     V = DAG.getBitcast(MVT::v2i64, V);
7286     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7287     return DAG.getBitcast(VT, V);
7288   }
7289
7290   // No viable ext lowering found.
7291   return SDValue();
7292 }
7293
7294 /// \brief Try to get a scalar value for a specific element of a vector.
7295 ///
7296 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7297 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7298                                               SelectionDAG &DAG) {
7299   MVT VT = V.getSimpleValueType();
7300   MVT EltVT = VT.getVectorElementType();
7301   while (V.getOpcode() == ISD::BITCAST)
7302     V = V.getOperand(0);
7303   // If the bitcasts shift the element size, we can't extract an equivalent
7304   // element from it.
7305   MVT NewVT = V.getSimpleValueType();
7306   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7307     return SDValue();
7308
7309   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7310       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7311     // Ensure the scalar operand is the same size as the destination.
7312     // FIXME: Add support for scalar truncation where possible.
7313     SDValue S = V.getOperand(Idx);
7314     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7315       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7316   }
7317
7318   return SDValue();
7319 }
7320
7321 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7322 ///
7323 /// This is particularly important because the set of instructions varies
7324 /// significantly based on whether the operand is a load or not.
7325 static bool isShuffleFoldableLoad(SDValue V) {
7326   while (V.getOpcode() == ISD::BITCAST)
7327     V = V.getOperand(0);
7328
7329   return ISD::isNON_EXTLoad(V.getNode());
7330 }
7331
7332 /// \brief Try to lower insertion of a single element into a zero vector.
7333 ///
7334 /// This is a common pattern that we have especially efficient patterns to lower
7335 /// across all subtarget feature sets.
7336 static SDValue lowerVectorShuffleAsElementInsertion(
7337     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7338     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7339   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7340   MVT ExtVT = VT;
7341   MVT EltVT = VT.getVectorElementType();
7342
7343   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7344                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7345                 Mask.begin();
7346   bool IsV1Zeroable = true;
7347   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7348     if (i != V2Index && !Zeroable[i]) {
7349       IsV1Zeroable = false;
7350       break;
7351     }
7352
7353   // Check for a single input from a SCALAR_TO_VECTOR node.
7354   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7355   // all the smarts here sunk into that routine. However, the current
7356   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7357   // vector shuffle lowering is dead.
7358   if (SDValue V2S = getScalarValueForVectorElement(
7359           V2, Mask[V2Index] - Mask.size(), DAG)) {
7360     // We need to zext the scalar if it is smaller than an i32.
7361     V2S = DAG.getBitcast(EltVT, V2S);
7362     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7363       // Using zext to expand a narrow element won't work for non-zero
7364       // insertions.
7365       if (!IsV1Zeroable)
7366         return SDValue();
7367
7368       // Zero-extend directly to i32.
7369       ExtVT = MVT::v4i32;
7370       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7371     }
7372     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7373   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7374              EltVT == MVT::i16) {
7375     // Either not inserting from the low element of the input or the input
7376     // element size is too small to use VZEXT_MOVL to clear the high bits.
7377     return SDValue();
7378   }
7379
7380   if (!IsV1Zeroable) {
7381     // If V1 can't be treated as a zero vector we have fewer options to lower
7382     // this. We can't support integer vectors or non-zero targets cheaply, and
7383     // the V1 elements can't be permuted in any way.
7384     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7385     if (!VT.isFloatingPoint() || V2Index != 0)
7386       return SDValue();
7387     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7388     V1Mask[V2Index] = -1;
7389     if (!isNoopShuffleMask(V1Mask))
7390       return SDValue();
7391     // This is essentially a special case blend operation, but if we have
7392     // general purpose blend operations, they are always faster. Bail and let
7393     // the rest of the lowering handle these as blends.
7394     if (Subtarget->hasSSE41())
7395       return SDValue();
7396
7397     // Otherwise, use MOVSD or MOVSS.
7398     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7399            "Only two types of floating point element types to handle!");
7400     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7401                        ExtVT, V1, V2);
7402   }
7403
7404   // This lowering only works for the low element with floating point vectors.
7405   if (VT.isFloatingPoint() && V2Index != 0)
7406     return SDValue();
7407
7408   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7409   if (ExtVT != VT)
7410     V2 = DAG.getBitcast(VT, V2);
7411
7412   if (V2Index != 0) {
7413     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7414     // the desired position. Otherwise it is more efficient to do a vector
7415     // shift left. We know that we can do a vector shift left because all
7416     // the inputs are zero.
7417     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7418       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7419       V2Shuffle[V2Index] = 0;
7420       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7421     } else {
7422       V2 = DAG.getBitcast(MVT::v2i64, V2);
7423       V2 = DAG.getNode(
7424           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7425           DAG.getConstant(V2Index * EltVT.getSizeInBits() / 8, DL,
7426                           DAG.getTargetLoweringInfo().getScalarShiftAmountTy(
7427                               DAG.getDataLayout(), VT)));
7428       V2 = DAG.getBitcast(VT, V2);
7429     }
7430   }
7431   return V2;
7432 }
7433
7434 /// \brief Try to lower broadcast of a single element.
7435 ///
7436 /// For convenience, this code also bundles all of the subtarget feature set
7437 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7438 /// a convenient way to factor it out.
7439 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7440                                              ArrayRef<int> Mask,
7441                                              const X86Subtarget *Subtarget,
7442                                              SelectionDAG &DAG) {
7443   if (!Subtarget->hasAVX())
7444     return SDValue();
7445   if (VT.isInteger() && !Subtarget->hasAVX2())
7446     return SDValue();
7447
7448   // Check that the mask is a broadcast.
7449   int BroadcastIdx = -1;
7450   for (int M : Mask)
7451     if (M >= 0 && BroadcastIdx == -1)
7452       BroadcastIdx = M;
7453     else if (M >= 0 && M != BroadcastIdx)
7454       return SDValue();
7455
7456   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7457                                             "a sorted mask where the broadcast "
7458                                             "comes from V1.");
7459
7460   // Go up the chain of (vector) values to find a scalar load that we can
7461   // combine with the broadcast.
7462   for (;;) {
7463     switch (V.getOpcode()) {
7464     case ISD::CONCAT_VECTORS: {
7465       int OperandSize = Mask.size() / V.getNumOperands();
7466       V = V.getOperand(BroadcastIdx / OperandSize);
7467       BroadcastIdx %= OperandSize;
7468       continue;
7469     }
7470
7471     case ISD::INSERT_SUBVECTOR: {
7472       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7473       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7474       if (!ConstantIdx)
7475         break;
7476
7477       int BeginIdx = (int)ConstantIdx->getZExtValue();
7478       int EndIdx =
7479           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7480       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7481         BroadcastIdx -= BeginIdx;
7482         V = VInner;
7483       } else {
7484         V = VOuter;
7485       }
7486       continue;
7487     }
7488     }
7489     break;
7490   }
7491
7492   // Check if this is a broadcast of a scalar. We special case lowering
7493   // for scalars so that we can more effectively fold with loads.
7494   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7495       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7496     V = V.getOperand(BroadcastIdx);
7497
7498     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7499     // Only AVX2 has register broadcasts.
7500     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7501       return SDValue();
7502   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7503     // We can't broadcast from a vector register without AVX2, and we can only
7504     // broadcast from the zero-element of a vector register.
7505     return SDValue();
7506   }
7507
7508   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7509 }
7510
7511 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7512 // INSERTPS when the V1 elements are already in the correct locations
7513 // because otherwise we can just always use two SHUFPS instructions which
7514 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7515 // perform INSERTPS if a single V1 element is out of place and all V2
7516 // elements are zeroable.
7517 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7518                                             ArrayRef<int> Mask,
7519                                             SelectionDAG &DAG) {
7520   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7521   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7522   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7523   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7524
7525   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7526
7527   unsigned ZMask = 0;
7528   int V1DstIndex = -1;
7529   int V2DstIndex = -1;
7530   bool V1UsedInPlace = false;
7531
7532   for (int i = 0; i < 4; ++i) {
7533     // Synthesize a zero mask from the zeroable elements (includes undefs).
7534     if (Zeroable[i]) {
7535       ZMask |= 1 << i;
7536       continue;
7537     }
7538
7539     // Flag if we use any V1 inputs in place.
7540     if (i == Mask[i]) {
7541       V1UsedInPlace = true;
7542       continue;
7543     }
7544
7545     // We can only insert a single non-zeroable element.
7546     if (V1DstIndex != -1 || V2DstIndex != -1)
7547       return SDValue();
7548
7549     if (Mask[i] < 4) {
7550       // V1 input out of place for insertion.
7551       V1DstIndex = i;
7552     } else {
7553       // V2 input for insertion.
7554       V2DstIndex = i;
7555     }
7556   }
7557
7558   // Don't bother if we have no (non-zeroable) element for insertion.
7559   if (V1DstIndex == -1 && V2DstIndex == -1)
7560     return SDValue();
7561
7562   // Determine element insertion src/dst indices. The src index is from the
7563   // start of the inserted vector, not the start of the concatenated vector.
7564   unsigned V2SrcIndex = 0;
7565   if (V1DstIndex != -1) {
7566     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7567     // and don't use the original V2 at all.
7568     V2SrcIndex = Mask[V1DstIndex];
7569     V2DstIndex = V1DstIndex;
7570     V2 = V1;
7571   } else {
7572     V2SrcIndex = Mask[V2DstIndex] - 4;
7573   }
7574
7575   // If no V1 inputs are used in place, then the result is created only from
7576   // the zero mask and the V2 insertion - so remove V1 dependency.
7577   if (!V1UsedInPlace)
7578     V1 = DAG.getUNDEF(MVT::v4f32);
7579
7580   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7581   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7582
7583   // Insert the V2 element into the desired position.
7584   SDLoc DL(Op);
7585   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7586                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7587 }
7588
7589 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7590 /// UNPCK instruction.
7591 ///
7592 /// This specifically targets cases where we end up with alternating between
7593 /// the two inputs, and so can permute them into something that feeds a single
7594 /// UNPCK instruction. Note that this routine only targets integer vectors
7595 /// because for floating point vectors we have a generalized SHUFPS lowering
7596 /// strategy that handles everything that doesn't *exactly* match an unpack,
7597 /// making this clever lowering unnecessary.
7598 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7599                                           SDValue V2, ArrayRef<int> Mask,
7600                                           SelectionDAG &DAG) {
7601   assert(!VT.isFloatingPoint() &&
7602          "This routine only supports integer vectors.");
7603   assert(!isSingleInputShuffleMask(Mask) &&
7604          "This routine should only be used when blending two inputs.");
7605   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7606
7607   int Size = Mask.size();
7608
7609   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7610     return M >= 0 && M % Size < Size / 2;
7611   });
7612   int NumHiInputs = std::count_if(
7613       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7614
7615   bool UnpackLo = NumLoInputs >= NumHiInputs;
7616
7617   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7618     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7619     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7620
7621     for (int i = 0; i < Size; ++i) {
7622       if (Mask[i] < 0)
7623         continue;
7624
7625       // Each element of the unpack contains Scale elements from this mask.
7626       int UnpackIdx = i / Scale;
7627
7628       // We only handle the case where V1 feeds the first slots of the unpack.
7629       // We rely on canonicalization to ensure this is the case.
7630       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7631         return SDValue();
7632
7633       // Setup the mask for this input. The indexing is tricky as we have to
7634       // handle the unpack stride.
7635       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7636       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7637           Mask[i] % Size;
7638     }
7639
7640     // If we will have to shuffle both inputs to use the unpack, check whether
7641     // we can just unpack first and shuffle the result. If so, skip this unpack.
7642     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7643         !isNoopShuffleMask(V2Mask))
7644       return SDValue();
7645
7646     // Shuffle the inputs into place.
7647     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7648     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7649
7650     // Cast the inputs to the type we will use to unpack them.
7651     V1 = DAG.getBitcast(UnpackVT, V1);
7652     V2 = DAG.getBitcast(UnpackVT, V2);
7653
7654     // Unpack the inputs and cast the result back to the desired type.
7655     return DAG.getBitcast(
7656         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7657                         UnpackVT, V1, V2));
7658   };
7659
7660   // We try each unpack from the largest to the smallest to try and find one
7661   // that fits this mask.
7662   int OrigNumElements = VT.getVectorNumElements();
7663   int OrigScalarSize = VT.getScalarSizeInBits();
7664   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7665     int Scale = ScalarSize / OrigScalarSize;
7666     int NumElements = OrigNumElements / Scale;
7667     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7668     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7669       return Unpack;
7670   }
7671
7672   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7673   // initial unpack.
7674   if (NumLoInputs == 0 || NumHiInputs == 0) {
7675     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7676            "We have to have *some* inputs!");
7677     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7678
7679     // FIXME: We could consider the total complexity of the permute of each
7680     // possible unpacking. Or at the least we should consider how many
7681     // half-crossings are created.
7682     // FIXME: We could consider commuting the unpacks.
7683
7684     SmallVector<int, 32> PermMask;
7685     PermMask.assign(Size, -1);
7686     for (int i = 0; i < Size; ++i) {
7687       if (Mask[i] < 0)
7688         continue;
7689
7690       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7691
7692       PermMask[i] =
7693           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7694     }
7695     return DAG.getVectorShuffle(
7696         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7697                             DL, VT, V1, V2),
7698         DAG.getUNDEF(VT), PermMask);
7699   }
7700
7701   return SDValue();
7702 }
7703
7704 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7705 ///
7706 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7707 /// support for floating point shuffles but not integer shuffles. These
7708 /// instructions will incur a domain crossing penalty on some chips though so
7709 /// it is better to avoid lowering through this for integer vectors where
7710 /// possible.
7711 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7712                                        const X86Subtarget *Subtarget,
7713                                        SelectionDAG &DAG) {
7714   SDLoc DL(Op);
7715   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7716   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7717   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7718   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7719   ArrayRef<int> Mask = SVOp->getMask();
7720   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7721
7722   if (isSingleInputShuffleMask(Mask)) {
7723     // Use low duplicate instructions for masks that match their pattern.
7724     if (Subtarget->hasSSE3())
7725       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7726         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7727
7728     // Straight shuffle of a single input vector. Simulate this by using the
7729     // single input as both of the "inputs" to this instruction..
7730     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7731
7732     if (Subtarget->hasAVX()) {
7733       // If we have AVX, we can use VPERMILPS which will allow folding a load
7734       // into the shuffle.
7735       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7736                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7737     }
7738
7739     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7740                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7741   }
7742   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7743   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7744
7745   // If we have a single input, insert that into V1 if we can do so cheaply.
7746   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7747     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7748             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7749       return Insertion;
7750     // Try inverting the insertion since for v2 masks it is easy to do and we
7751     // can't reliably sort the mask one way or the other.
7752     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7753                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7754     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7755             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7756       return Insertion;
7757   }
7758
7759   // Try to use one of the special instruction patterns to handle two common
7760   // blend patterns if a zero-blend above didn't work.
7761   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7762       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7763     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7764       // We can either use a special instruction to load over the low double or
7765       // to move just the low double.
7766       return DAG.getNode(
7767           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7768           DL, MVT::v2f64, V2,
7769           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7770
7771   if (Subtarget->hasSSE41())
7772     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7773                                                   Subtarget, DAG))
7774       return Blend;
7775
7776   // Use dedicated unpack instructions for masks that match their pattern.
7777   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7778     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7779   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7780     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7781
7782   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7783   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7784                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7785 }
7786
7787 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7788 ///
7789 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7790 /// the integer unit to minimize domain crossing penalties. However, for blends
7791 /// it falls back to the floating point shuffle operation with appropriate bit
7792 /// casting.
7793 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7794                                        const X86Subtarget *Subtarget,
7795                                        SelectionDAG &DAG) {
7796   SDLoc DL(Op);
7797   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7798   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7799   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7800   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7801   ArrayRef<int> Mask = SVOp->getMask();
7802   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7803
7804   if (isSingleInputShuffleMask(Mask)) {
7805     // Check for being able to broadcast a single element.
7806     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7807                                                           Mask, Subtarget, DAG))
7808       return Broadcast;
7809
7810     // Straight shuffle of a single input vector. For everything from SSE2
7811     // onward this has a single fast instruction with no scary immediates.
7812     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7813     V1 = DAG.getBitcast(MVT::v4i32, V1);
7814     int WidenedMask[4] = {
7815         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7816         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7817     return DAG.getBitcast(
7818         MVT::v2i64,
7819         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7820                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7821   }
7822   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7823   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7824   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7825   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7826
7827   // If we have a blend of two PACKUS operations an the blend aligns with the
7828   // low and half halves, we can just merge the PACKUS operations. This is
7829   // particularly important as it lets us merge shuffles that this routine itself
7830   // creates.
7831   auto GetPackNode = [](SDValue V) {
7832     while (V.getOpcode() == ISD::BITCAST)
7833       V = V.getOperand(0);
7834
7835     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7836   };
7837   if (SDValue V1Pack = GetPackNode(V1))
7838     if (SDValue V2Pack = GetPackNode(V2))
7839       return DAG.getBitcast(MVT::v2i64,
7840                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7841                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7842                                                      : V1Pack.getOperand(1),
7843                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7844                                                      : V2Pack.getOperand(1)));
7845
7846   // Try to use shift instructions.
7847   if (SDValue Shift =
7848           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7849     return Shift;
7850
7851   // When loading a scalar and then shuffling it into a vector we can often do
7852   // the insertion cheaply.
7853   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7854           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7855     return Insertion;
7856   // Try inverting the insertion since for v2 masks it is easy to do and we
7857   // can't reliably sort the mask one way or the other.
7858   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7859   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7860           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7861     return Insertion;
7862
7863   // We have different paths for blend lowering, but they all must use the
7864   // *exact* same predicate.
7865   bool IsBlendSupported = Subtarget->hasSSE41();
7866   if (IsBlendSupported)
7867     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7868                                                   Subtarget, DAG))
7869       return Blend;
7870
7871   // Use dedicated unpack instructions for masks that match their pattern.
7872   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7873     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7874   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7875     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7876
7877   // Try to use byte rotation instructions.
7878   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7879   if (Subtarget->hasSSSE3())
7880     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7881             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7882       return Rotate;
7883
7884   // If we have direct support for blends, we should lower by decomposing into
7885   // a permute. That will be faster than the domain cross.
7886   if (IsBlendSupported)
7887     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7888                                                       Mask, DAG);
7889
7890   // We implement this with SHUFPD which is pretty lame because it will likely
7891   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7892   // However, all the alternatives are still more cycles and newer chips don't
7893   // have this problem. It would be really nice if x86 had better shuffles here.
7894   V1 = DAG.getBitcast(MVT::v2f64, V1);
7895   V2 = DAG.getBitcast(MVT::v2f64, V2);
7896   return DAG.getBitcast(MVT::v2i64,
7897                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7898 }
7899
7900 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7901 ///
7902 /// This is used to disable more specialized lowerings when the shufps lowering
7903 /// will happen to be efficient.
7904 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7905   // This routine only handles 128-bit shufps.
7906   assert(Mask.size() == 4 && "Unsupported mask size!");
7907
7908   // To lower with a single SHUFPS we need to have the low half and high half
7909   // each requiring a single input.
7910   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7911     return false;
7912   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7913     return false;
7914
7915   return true;
7916 }
7917
7918 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7919 ///
7920 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7921 /// It makes no assumptions about whether this is the *best* lowering, it simply
7922 /// uses it.
7923 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7924                                             ArrayRef<int> Mask, SDValue V1,
7925                                             SDValue V2, SelectionDAG &DAG) {
7926   SDValue LowV = V1, HighV = V2;
7927   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7928
7929   int NumV2Elements =
7930       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7931
7932   if (NumV2Elements == 1) {
7933     int V2Index =
7934         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7935         Mask.begin();
7936
7937     // Compute the index adjacent to V2Index and in the same half by toggling
7938     // the low bit.
7939     int V2AdjIndex = V2Index ^ 1;
7940
7941     if (Mask[V2AdjIndex] == -1) {
7942       // Handles all the cases where we have a single V2 element and an undef.
7943       // This will only ever happen in the high lanes because we commute the
7944       // vector otherwise.
7945       if (V2Index < 2)
7946         std::swap(LowV, HighV);
7947       NewMask[V2Index] -= 4;
7948     } else {
7949       // Handle the case where the V2 element ends up adjacent to a V1 element.
7950       // To make this work, blend them together as the first step.
7951       int V1Index = V2AdjIndex;
7952       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7953       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7954                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7955
7956       // Now proceed to reconstruct the final blend as we have the necessary
7957       // high or low half formed.
7958       if (V2Index < 2) {
7959         LowV = V2;
7960         HighV = V1;
7961       } else {
7962         HighV = V2;
7963       }
7964       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7965       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7966     }
7967   } else if (NumV2Elements == 2) {
7968     if (Mask[0] < 4 && Mask[1] < 4) {
7969       // Handle the easy case where we have V1 in the low lanes and V2 in the
7970       // high lanes.
7971       NewMask[2] -= 4;
7972       NewMask[3] -= 4;
7973     } else if (Mask[2] < 4 && Mask[3] < 4) {
7974       // We also handle the reversed case because this utility may get called
7975       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7976       // arrange things in the right direction.
7977       NewMask[0] -= 4;
7978       NewMask[1] -= 4;
7979       HighV = V1;
7980       LowV = V2;
7981     } else {
7982       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7983       // trying to place elements directly, just blend them and set up the final
7984       // shuffle to place them.
7985
7986       // The first two blend mask elements are for V1, the second two are for
7987       // V2.
7988       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7989                           Mask[2] < 4 ? Mask[2] : Mask[3],
7990                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7991                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7992       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7993                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7994
7995       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7996       // a blend.
7997       LowV = HighV = V1;
7998       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7999       NewMask[1] = Mask[0] < 4 ? 2 : 0;
8000       NewMask[2] = Mask[2] < 4 ? 1 : 3;
8001       NewMask[3] = Mask[2] < 4 ? 3 : 1;
8002     }
8003   }
8004   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
8005                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
8006 }
8007
8008 /// \brief Lower 4-lane 32-bit floating point shuffles.
8009 ///
8010 /// Uses instructions exclusively from the floating point unit to minimize
8011 /// domain crossing penalties, as these are sufficient to implement all v4f32
8012 /// shuffles.
8013 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8014                                        const X86Subtarget *Subtarget,
8015                                        SelectionDAG &DAG) {
8016   SDLoc DL(Op);
8017   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
8018   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8019   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
8020   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8021   ArrayRef<int> Mask = SVOp->getMask();
8022   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8023
8024   int NumV2Elements =
8025       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8026
8027   if (NumV2Elements == 0) {
8028     // Check for being able to broadcast a single element.
8029     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
8030                                                           Mask, Subtarget, DAG))
8031       return Broadcast;
8032
8033     // Use even/odd duplicate instructions for masks that match their pattern.
8034     if (Subtarget->hasSSE3()) {
8035       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
8036         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
8037       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
8038         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
8039     }
8040
8041     if (Subtarget->hasAVX()) {
8042       // If we have AVX, we can use VPERMILPS which will allow folding a load
8043       // into the shuffle.
8044       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
8045                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8046     }
8047
8048     // Otherwise, use a straight shuffle of a single input vector. We pass the
8049     // input vector to both operands to simulate this with a SHUFPS.
8050     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
8051                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8052   }
8053
8054   // There are special ways we can lower some single-element blends. However, we
8055   // have custom ways we can lower more complex single-element blends below that
8056   // we defer to if both this and BLENDPS fail to match, so restrict this to
8057   // when the V2 input is targeting element 0 of the mask -- that is the fast
8058   // case here.
8059   if (NumV2Elements == 1 && Mask[0] >= 4)
8060     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
8061                                                          Mask, Subtarget, DAG))
8062       return V;
8063
8064   if (Subtarget->hasSSE41()) {
8065     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
8066                                                   Subtarget, DAG))
8067       return Blend;
8068
8069     // Use INSERTPS if we can complete the shuffle efficiently.
8070     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
8071       return V;
8072
8073     if (!isSingleSHUFPSMask(Mask))
8074       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
8075               DL, MVT::v4f32, V1, V2, Mask, DAG))
8076         return BlendPerm;
8077   }
8078
8079   // Use dedicated unpack instructions for masks that match their pattern.
8080   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8081     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
8082   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8083     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
8084   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8085     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
8086   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8087     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
8088
8089   // Otherwise fall back to a SHUFPS lowering strategy.
8090   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
8091 }
8092
8093 /// \brief Lower 4-lane i32 vector shuffles.
8094 ///
8095 /// We try to handle these with integer-domain shuffles where we can, but for
8096 /// blends we use the floating point domain blend instructions.
8097 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8098                                        const X86Subtarget *Subtarget,
8099                                        SelectionDAG &DAG) {
8100   SDLoc DL(Op);
8101   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
8102   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8103   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
8104   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8105   ArrayRef<int> Mask = SVOp->getMask();
8106   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
8107
8108   // Whenever we can lower this as a zext, that instruction is strictly faster
8109   // than any alternative. It also allows us to fold memory operands into the
8110   // shuffle in many cases.
8111   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
8112                                                          Mask, Subtarget, DAG))
8113     return ZExt;
8114
8115   int NumV2Elements =
8116       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
8117
8118   if (NumV2Elements == 0) {
8119     // Check for being able to broadcast a single element.
8120     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
8121                                                           Mask, Subtarget, DAG))
8122       return Broadcast;
8123
8124     // Straight shuffle of a single input vector. For everything from SSE2
8125     // onward this has a single fast instruction with no scary immediates.
8126     // We coerce the shuffle pattern to be compatible with UNPCK instructions
8127     // but we aren't actually going to use the UNPCK instruction because doing
8128     // so prevents folding a load into this instruction or making a copy.
8129     const int UnpackLoMask[] = {0, 0, 1, 1};
8130     const int UnpackHiMask[] = {2, 2, 3, 3};
8131     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
8132       Mask = UnpackLoMask;
8133     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
8134       Mask = UnpackHiMask;
8135
8136     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
8137                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
8138   }
8139
8140   // Try to use shift instructions.
8141   if (SDValue Shift =
8142           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
8143     return Shift;
8144
8145   // There are special ways we can lower some single-element blends.
8146   if (NumV2Elements == 1)
8147     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
8148                                                          Mask, Subtarget, DAG))
8149       return V;
8150
8151   // We have different paths for blend lowering, but they all must use the
8152   // *exact* same predicate.
8153   bool IsBlendSupported = Subtarget->hasSSE41();
8154   if (IsBlendSupported)
8155     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
8156                                                   Subtarget, DAG))
8157       return Blend;
8158
8159   if (SDValue Masked =
8160           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
8161     return Masked;
8162
8163   // Use dedicated unpack instructions for masks that match their pattern.
8164   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
8165     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
8166   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
8167     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
8168   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
8169     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
8170   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
8171     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
8172
8173   // Try to use byte rotation instructions.
8174   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
8175   if (Subtarget->hasSSSE3())
8176     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8177             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
8178       return Rotate;
8179
8180   // If we have direct support for blends, we should lower by decomposing into
8181   // a permute. That will be faster than the domain cross.
8182   if (IsBlendSupported)
8183     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
8184                                                       Mask, DAG);
8185
8186   // Try to lower by permuting the inputs into an unpack instruction.
8187   if (SDValue Unpack =
8188           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
8189     return Unpack;
8190
8191   // We implement this with SHUFPS because it can blend from two vectors.
8192   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
8193   // up the inputs, bypassing domain shift penalties that we would encur if we
8194   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
8195   // relevant.
8196   return DAG.getBitcast(
8197       MVT::v4i32,
8198       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8199                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8200 }
8201
8202 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8203 /// shuffle lowering, and the most complex part.
8204 ///
8205 /// The lowering strategy is to try to form pairs of input lanes which are
8206 /// targeted at the same half of the final vector, and then use a dword shuffle
8207 /// to place them onto the right half, and finally unpack the paired lanes into
8208 /// their final position.
8209 ///
8210 /// The exact breakdown of how to form these dword pairs and align them on the
8211 /// correct sides is really tricky. See the comments within the function for
8212 /// more of the details.
8213 ///
8214 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8215 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8216 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8217 /// vector, form the analogous 128-bit 8-element Mask.
8218 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8219     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8220     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8221   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8222   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8223
8224   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8225   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8226   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8227
8228   SmallVector<int, 4> LoInputs;
8229   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8230                [](int M) { return M >= 0; });
8231   std::sort(LoInputs.begin(), LoInputs.end());
8232   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8233   SmallVector<int, 4> HiInputs;
8234   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8235                [](int M) { return M >= 0; });
8236   std::sort(HiInputs.begin(), HiInputs.end());
8237   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8238   int NumLToL =
8239       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8240   int NumHToL = LoInputs.size() - NumLToL;
8241   int NumLToH =
8242       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8243   int NumHToH = HiInputs.size() - NumLToH;
8244   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8245   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8246   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8247   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8248
8249   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8250   // such inputs we can swap two of the dwords across the half mark and end up
8251   // with <=2 inputs to each half in each half. Once there, we can fall through
8252   // to the generic code below. For example:
8253   //
8254   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8255   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8256   //
8257   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8258   // and an existing 2-into-2 on the other half. In this case we may have to
8259   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8260   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8261   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8262   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8263   // half than the one we target for fixing) will be fixed when we re-enter this
8264   // path. We will also combine away any sequence of PSHUFD instructions that
8265   // result into a single instruction. Here is an example of the tricky case:
8266   //
8267   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8268   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8269   //
8270   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8271   //
8272   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8273   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8274   //
8275   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8276   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8277   //
8278   // The result is fine to be handled by the generic logic.
8279   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8280                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8281                           int AOffset, int BOffset) {
8282     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8283            "Must call this with A having 3 or 1 inputs from the A half.");
8284     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8285            "Must call this with B having 1 or 3 inputs from the B half.");
8286     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8287            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8288
8289     // Compute the index of dword with only one word among the three inputs in
8290     // a half by taking the sum of the half with three inputs and subtracting
8291     // the sum of the actual three inputs. The difference is the remaining
8292     // slot.
8293     int ADWord, BDWord;
8294     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8295     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8296     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8297     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8298     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8299     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8300     int TripleNonInputIdx =
8301         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8302     TripleDWord = TripleNonInputIdx / 2;
8303
8304     // We use xor with one to compute the adjacent DWord to whichever one the
8305     // OneInput is in.
8306     OneInputDWord = (OneInput / 2) ^ 1;
8307
8308     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8309     // and BToA inputs. If there is also such a problem with the BToB and AToB
8310     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8311     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8312     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8313     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8314       // Compute how many inputs will be flipped by swapping these DWords. We
8315       // need
8316       // to balance this to ensure we don't form a 3-1 shuffle in the other
8317       // half.
8318       int NumFlippedAToBInputs =
8319           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8320           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8321       int NumFlippedBToBInputs =
8322           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8323           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8324       if ((NumFlippedAToBInputs == 1 &&
8325            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8326           (NumFlippedBToBInputs == 1 &&
8327            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8328         // We choose whether to fix the A half or B half based on whether that
8329         // half has zero flipped inputs. At zero, we may not be able to fix it
8330         // with that half. We also bias towards fixing the B half because that
8331         // will more commonly be the high half, and we have to bias one way.
8332         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8333                                                        ArrayRef<int> Inputs) {
8334           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8335           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8336                                          PinnedIdx ^ 1) != Inputs.end();
8337           // Determine whether the free index is in the flipped dword or the
8338           // unflipped dword based on where the pinned index is. We use this bit
8339           // in an xor to conditionally select the adjacent dword.
8340           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8341           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8342                                              FixFreeIdx) != Inputs.end();
8343           if (IsFixIdxInput == IsFixFreeIdxInput)
8344             FixFreeIdx += 1;
8345           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8346                                         FixFreeIdx) != Inputs.end();
8347           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8348                  "We need to be changing the number of flipped inputs!");
8349           int PSHUFHalfMask[] = {0, 1, 2, 3};
8350           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8351           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8352                           MVT::v8i16, V,
8353                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8354
8355           for (int &M : Mask)
8356             if (M != -1 && M == FixIdx)
8357               M = FixFreeIdx;
8358             else if (M != -1 && M == FixFreeIdx)
8359               M = FixIdx;
8360         };
8361         if (NumFlippedBToBInputs != 0) {
8362           int BPinnedIdx =
8363               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8364           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8365         } else {
8366           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8367           int APinnedIdx =
8368               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8369           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8370         }
8371       }
8372     }
8373
8374     int PSHUFDMask[] = {0, 1, 2, 3};
8375     PSHUFDMask[ADWord] = BDWord;
8376     PSHUFDMask[BDWord] = ADWord;
8377     V = DAG.getBitcast(
8378         VT,
8379         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8380                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8381
8382     // Adjust the mask to match the new locations of A and B.
8383     for (int &M : Mask)
8384       if (M != -1 && M/2 == ADWord)
8385         M = 2 * BDWord + M % 2;
8386       else if (M != -1 && M/2 == BDWord)
8387         M = 2 * ADWord + M % 2;
8388
8389     // Recurse back into this routine to re-compute state now that this isn't
8390     // a 3 and 1 problem.
8391     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8392                                                      DAG);
8393   };
8394   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8395     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8396   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8397     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8398
8399   // At this point there are at most two inputs to the low and high halves from
8400   // each half. That means the inputs can always be grouped into dwords and
8401   // those dwords can then be moved to the correct half with a dword shuffle.
8402   // We use at most one low and one high word shuffle to collect these paired
8403   // inputs into dwords, and finally a dword shuffle to place them.
8404   int PSHUFLMask[4] = {-1, -1, -1, -1};
8405   int PSHUFHMask[4] = {-1, -1, -1, -1};
8406   int PSHUFDMask[4] = {-1, -1, -1, -1};
8407
8408   // First fix the masks for all the inputs that are staying in their
8409   // original halves. This will then dictate the targets of the cross-half
8410   // shuffles.
8411   auto fixInPlaceInputs =
8412       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8413                     MutableArrayRef<int> SourceHalfMask,
8414                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8415     if (InPlaceInputs.empty())
8416       return;
8417     if (InPlaceInputs.size() == 1) {
8418       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8419           InPlaceInputs[0] - HalfOffset;
8420       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8421       return;
8422     }
8423     if (IncomingInputs.empty()) {
8424       // Just fix all of the in place inputs.
8425       for (int Input : InPlaceInputs) {
8426         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8427         PSHUFDMask[Input / 2] = Input / 2;
8428       }
8429       return;
8430     }
8431
8432     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8433     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8434         InPlaceInputs[0] - HalfOffset;
8435     // Put the second input next to the first so that they are packed into
8436     // a dword. We find the adjacent index by toggling the low bit.
8437     int AdjIndex = InPlaceInputs[0] ^ 1;
8438     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8439     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8440     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8441   };
8442   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8443   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8444
8445   // Now gather the cross-half inputs and place them into a free dword of
8446   // their target half.
8447   // FIXME: This operation could almost certainly be simplified dramatically to
8448   // look more like the 3-1 fixing operation.
8449   auto moveInputsToRightHalf = [&PSHUFDMask](
8450       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8451       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8452       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8453       int DestOffset) {
8454     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8455       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8456     };
8457     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8458                                                int Word) {
8459       int LowWord = Word & ~1;
8460       int HighWord = Word | 1;
8461       return isWordClobbered(SourceHalfMask, LowWord) ||
8462              isWordClobbered(SourceHalfMask, HighWord);
8463     };
8464
8465     if (IncomingInputs.empty())
8466       return;
8467
8468     if (ExistingInputs.empty()) {
8469       // Map any dwords with inputs from them into the right half.
8470       for (int Input : IncomingInputs) {
8471         // If the source half mask maps over the inputs, turn those into
8472         // swaps and use the swapped lane.
8473         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8474           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8475             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8476                 Input - SourceOffset;
8477             // We have to swap the uses in our half mask in one sweep.
8478             for (int &M : HalfMask)
8479               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8480                 M = Input;
8481               else if (M == Input)
8482                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8483           } else {
8484             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8485                        Input - SourceOffset &&
8486                    "Previous placement doesn't match!");
8487           }
8488           // Note that this correctly re-maps both when we do a swap and when
8489           // we observe the other side of the swap above. We rely on that to
8490           // avoid swapping the members of the input list directly.
8491           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8492         }
8493
8494         // Map the input's dword into the correct half.
8495         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8496           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8497         else
8498           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8499                      Input / 2 &&
8500                  "Previous placement doesn't match!");
8501       }
8502
8503       // And just directly shift any other-half mask elements to be same-half
8504       // as we will have mirrored the dword containing the element into the
8505       // same position within that half.
8506       for (int &M : HalfMask)
8507         if (M >= SourceOffset && M < SourceOffset + 4) {
8508           M = M - SourceOffset + DestOffset;
8509           assert(M >= 0 && "This should never wrap below zero!");
8510         }
8511       return;
8512     }
8513
8514     // Ensure we have the input in a viable dword of its current half. This
8515     // is particularly tricky because the original position may be clobbered
8516     // by inputs being moved and *staying* in that half.
8517     if (IncomingInputs.size() == 1) {
8518       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8519         int InputFixed = std::find(std::begin(SourceHalfMask),
8520                                    std::end(SourceHalfMask), -1) -
8521                          std::begin(SourceHalfMask) + SourceOffset;
8522         SourceHalfMask[InputFixed - SourceOffset] =
8523             IncomingInputs[0] - SourceOffset;
8524         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8525                      InputFixed);
8526         IncomingInputs[0] = InputFixed;
8527       }
8528     } else if (IncomingInputs.size() == 2) {
8529       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8530           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8531         // We have two non-adjacent or clobbered inputs we need to extract from
8532         // the source half. To do this, we need to map them into some adjacent
8533         // dword slot in the source mask.
8534         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8535                               IncomingInputs[1] - SourceOffset};
8536
8537         // If there is a free slot in the source half mask adjacent to one of
8538         // the inputs, place the other input in it. We use (Index XOR 1) to
8539         // compute an adjacent index.
8540         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8541             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8542           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8543           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8544           InputsFixed[1] = InputsFixed[0] ^ 1;
8545         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8546                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8547           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8548           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8549           InputsFixed[0] = InputsFixed[1] ^ 1;
8550         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8551                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8552           // The two inputs are in the same DWord but it is clobbered and the
8553           // adjacent DWord isn't used at all. Move both inputs to the free
8554           // slot.
8555           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8556           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8557           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8558           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8559         } else {
8560           // The only way we hit this point is if there is no clobbering
8561           // (because there are no off-half inputs to this half) and there is no
8562           // free slot adjacent to one of the inputs. In this case, we have to
8563           // swap an input with a non-input.
8564           for (int i = 0; i < 4; ++i)
8565             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8566                    "We can't handle any clobbers here!");
8567           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8568                  "Cannot have adjacent inputs here!");
8569
8570           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8571           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8572
8573           // We also have to update the final source mask in this case because
8574           // it may need to undo the above swap.
8575           for (int &M : FinalSourceHalfMask)
8576             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8577               M = InputsFixed[1] + SourceOffset;
8578             else if (M == InputsFixed[1] + SourceOffset)
8579               M = (InputsFixed[0] ^ 1) + SourceOffset;
8580
8581           InputsFixed[1] = InputsFixed[0] ^ 1;
8582         }
8583
8584         // Point everything at the fixed inputs.
8585         for (int &M : HalfMask)
8586           if (M == IncomingInputs[0])
8587             M = InputsFixed[0] + SourceOffset;
8588           else if (M == IncomingInputs[1])
8589             M = InputsFixed[1] + SourceOffset;
8590
8591         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8592         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8593       }
8594     } else {
8595       llvm_unreachable("Unhandled input size!");
8596     }
8597
8598     // Now hoist the DWord down to the right half.
8599     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8600     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8601     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8602     for (int &M : HalfMask)
8603       for (int Input : IncomingInputs)
8604         if (M == Input)
8605           M = FreeDWord * 2 + Input % 2;
8606   };
8607   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8608                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8609   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8610                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8611
8612   // Now enact all the shuffles we've computed to move the inputs into their
8613   // target half.
8614   if (!isNoopShuffleMask(PSHUFLMask))
8615     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8616                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8617   if (!isNoopShuffleMask(PSHUFHMask))
8618     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8619                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8620   if (!isNoopShuffleMask(PSHUFDMask))
8621     V = DAG.getBitcast(
8622         VT,
8623         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8624                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8625
8626   // At this point, each half should contain all its inputs, and we can then
8627   // just shuffle them into their final position.
8628   assert(std::count_if(LoMask.begin(), LoMask.end(),
8629                        [](int M) { return M >= 4; }) == 0 &&
8630          "Failed to lift all the high half inputs to the low mask!");
8631   assert(std::count_if(HiMask.begin(), HiMask.end(),
8632                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8633          "Failed to lift all the low half inputs to the high mask!");
8634
8635   // Do a half shuffle for the low mask.
8636   if (!isNoopShuffleMask(LoMask))
8637     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8638                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8639
8640   // Do a half shuffle with the high mask after shifting its values down.
8641   for (int &M : HiMask)
8642     if (M >= 0)
8643       M -= 4;
8644   if (!isNoopShuffleMask(HiMask))
8645     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8646                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8647
8648   return V;
8649 }
8650
8651 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8652 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8653                                           SDValue V2, ArrayRef<int> Mask,
8654                                           SelectionDAG &DAG, bool &V1InUse,
8655                                           bool &V2InUse) {
8656   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8657   SDValue V1Mask[16];
8658   SDValue V2Mask[16];
8659   V1InUse = false;
8660   V2InUse = false;
8661
8662   int Size = Mask.size();
8663   int Scale = 16 / Size;
8664   for (int i = 0; i < 16; ++i) {
8665     if (Mask[i / Scale] == -1) {
8666       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8667     } else {
8668       const int ZeroMask = 0x80;
8669       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8670                                           : ZeroMask;
8671       int V2Idx = Mask[i / Scale] < Size
8672                       ? ZeroMask
8673                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8674       if (Zeroable[i / Scale])
8675         V1Idx = V2Idx = ZeroMask;
8676       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8677       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8678       V1InUse |= (ZeroMask != V1Idx);
8679       V2InUse |= (ZeroMask != V2Idx);
8680     }
8681   }
8682
8683   if (V1InUse)
8684     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8685                      DAG.getBitcast(MVT::v16i8, V1),
8686                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8687   if (V2InUse)
8688     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8689                      DAG.getBitcast(MVT::v16i8, V2),
8690                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8691
8692   // If we need shuffled inputs from both, blend the two.
8693   SDValue V;
8694   if (V1InUse && V2InUse)
8695     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8696   else
8697     V = V1InUse ? V1 : V2;
8698
8699   // Cast the result back to the correct type.
8700   return DAG.getBitcast(VT, V);
8701 }
8702
8703 /// \brief Generic lowering of 8-lane i16 shuffles.
8704 ///
8705 /// This handles both single-input shuffles and combined shuffle/blends with
8706 /// two inputs. The single input shuffles are immediately delegated to
8707 /// a dedicated lowering routine.
8708 ///
8709 /// The blends are lowered in one of three fundamental ways. If there are few
8710 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8711 /// of the input is significantly cheaper when lowered as an interleaving of
8712 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8713 /// halves of the inputs separately (making them have relatively few inputs)
8714 /// and then concatenate them.
8715 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8716                                        const X86Subtarget *Subtarget,
8717                                        SelectionDAG &DAG) {
8718   SDLoc DL(Op);
8719   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8720   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8721   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8722   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8723   ArrayRef<int> OrigMask = SVOp->getMask();
8724   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8725                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8726   MutableArrayRef<int> Mask(MaskStorage);
8727
8728   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8729
8730   // Whenever we can lower this as a zext, that instruction is strictly faster
8731   // than any alternative.
8732   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8733           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8734     return ZExt;
8735
8736   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8737   (void)isV1;
8738   auto isV2 = [](int M) { return M >= 8; };
8739
8740   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8741
8742   if (NumV2Inputs == 0) {
8743     // Check for being able to broadcast a single element.
8744     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8745                                                           Mask, Subtarget, DAG))
8746       return Broadcast;
8747
8748     // Try to use shift instructions.
8749     if (SDValue Shift =
8750             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8751       return Shift;
8752
8753     // Use dedicated unpack instructions for masks that match their pattern.
8754     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8755       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8756     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8757       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8758
8759     // Try to use byte rotation instructions.
8760     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8761                                                         Mask, Subtarget, DAG))
8762       return Rotate;
8763
8764     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8765                                                      Subtarget, DAG);
8766   }
8767
8768   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8769          "All single-input shuffles should be canonicalized to be V1-input "
8770          "shuffles.");
8771
8772   // Try to use shift instructions.
8773   if (SDValue Shift =
8774           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8775     return Shift;
8776
8777   // See if we can use SSE4A Extraction / Insertion.
8778   if (Subtarget->hasSSE4A())
8779     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v8i16, V1, V2, Mask, DAG))
8780       return V;
8781
8782   // There are special ways we can lower some single-element blends.
8783   if (NumV2Inputs == 1)
8784     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8785                                                          Mask, Subtarget, DAG))
8786       return V;
8787
8788   // We have different paths for blend lowering, but they all must use the
8789   // *exact* same predicate.
8790   bool IsBlendSupported = Subtarget->hasSSE41();
8791   if (IsBlendSupported)
8792     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8793                                                   Subtarget, DAG))
8794       return Blend;
8795
8796   if (SDValue Masked =
8797           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8798     return Masked;
8799
8800   // Use dedicated unpack instructions for masks that match their pattern.
8801   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8802     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8803   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8804     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8805
8806   // Try to use byte rotation instructions.
8807   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8808           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8809     return Rotate;
8810
8811   if (SDValue BitBlend =
8812           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8813     return BitBlend;
8814
8815   if (SDValue Unpack =
8816           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8817     return Unpack;
8818
8819   // If we can't directly blend but can use PSHUFB, that will be better as it
8820   // can both shuffle and set up the inefficient blend.
8821   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8822     bool V1InUse, V2InUse;
8823     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8824                                       V1InUse, V2InUse);
8825   }
8826
8827   // We can always bit-blend if we have to so the fallback strategy is to
8828   // decompose into single-input permutes and blends.
8829   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8830                                                       Mask, DAG);
8831 }
8832
8833 /// \brief Check whether a compaction lowering can be done by dropping even
8834 /// elements and compute how many times even elements must be dropped.
8835 ///
8836 /// This handles shuffles which take every Nth element where N is a power of
8837 /// two. Example shuffle masks:
8838 ///
8839 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8840 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8841 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8842 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8843 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8844 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8845 ///
8846 /// Any of these lanes can of course be undef.
8847 ///
8848 /// This routine only supports N <= 3.
8849 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8850 /// for larger N.
8851 ///
8852 /// \returns N above, or the number of times even elements must be dropped if
8853 /// there is such a number. Otherwise returns zero.
8854 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8855   // Figure out whether we're looping over two inputs or just one.
8856   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8857
8858   // The modulus for the shuffle vector entries is based on whether this is
8859   // a single input or not.
8860   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8861   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8862          "We should only be called with masks with a power-of-2 size!");
8863
8864   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8865
8866   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8867   // and 2^3 simultaneously. This is because we may have ambiguity with
8868   // partially undef inputs.
8869   bool ViableForN[3] = {true, true, true};
8870
8871   for (int i = 0, e = Mask.size(); i < e; ++i) {
8872     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8873     // want.
8874     if (Mask[i] == -1)
8875       continue;
8876
8877     bool IsAnyViable = false;
8878     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8879       if (ViableForN[j]) {
8880         uint64_t N = j + 1;
8881
8882         // The shuffle mask must be equal to (i * 2^N) % M.
8883         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8884           IsAnyViable = true;
8885         else
8886           ViableForN[j] = false;
8887       }
8888     // Early exit if we exhaust the possible powers of two.
8889     if (!IsAnyViable)
8890       break;
8891   }
8892
8893   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8894     if (ViableForN[j])
8895       return j + 1;
8896
8897   // Return 0 as there is no viable power of two.
8898   return 0;
8899 }
8900
8901 /// \brief Generic lowering of v16i8 shuffles.
8902 ///
8903 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8904 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8905 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8906 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8907 /// back together.
8908 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8909                                        const X86Subtarget *Subtarget,
8910                                        SelectionDAG &DAG) {
8911   SDLoc DL(Op);
8912   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8913   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8914   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8915   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8916   ArrayRef<int> Mask = SVOp->getMask();
8917   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8918
8919   // Try to use shift instructions.
8920   if (SDValue Shift =
8921           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8922     return Shift;
8923
8924   // Try to use byte rotation instructions.
8925   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8926           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8927     return Rotate;
8928
8929   // Try to use a zext lowering.
8930   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8931           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8932     return ZExt;
8933
8934   // See if we can use SSE4A Extraction / Insertion.
8935   if (Subtarget->hasSSE4A())
8936     if (SDValue V = lowerVectorShuffleWithSSE4A(DL, MVT::v16i8, V1, V2, Mask, DAG))
8937       return V;
8938
8939   int NumV2Elements =
8940       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8941
8942   // For single-input shuffles, there are some nicer lowering tricks we can use.
8943   if (NumV2Elements == 0) {
8944     // Check for being able to broadcast a single element.
8945     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8946                                                           Mask, Subtarget, DAG))
8947       return Broadcast;
8948
8949     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8950     // Notably, this handles splat and partial-splat shuffles more efficiently.
8951     // However, it only makes sense if the pre-duplication shuffle simplifies
8952     // things significantly. Currently, this means we need to be able to
8953     // express the pre-duplication shuffle as an i16 shuffle.
8954     //
8955     // FIXME: We should check for other patterns which can be widened into an
8956     // i16 shuffle as well.
8957     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8958       for (int i = 0; i < 16; i += 2)
8959         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8960           return false;
8961
8962       return true;
8963     };
8964     auto tryToWidenViaDuplication = [&]() -> SDValue {
8965       if (!canWidenViaDuplication(Mask))
8966         return SDValue();
8967       SmallVector<int, 4> LoInputs;
8968       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8969                    [](int M) { return M >= 0 && M < 8; });
8970       std::sort(LoInputs.begin(), LoInputs.end());
8971       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8972                      LoInputs.end());
8973       SmallVector<int, 4> HiInputs;
8974       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8975                    [](int M) { return M >= 8; });
8976       std::sort(HiInputs.begin(), HiInputs.end());
8977       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8978                      HiInputs.end());
8979
8980       bool TargetLo = LoInputs.size() >= HiInputs.size();
8981       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8982       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8983
8984       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8985       SmallDenseMap<int, int, 8> LaneMap;
8986       for (int I : InPlaceInputs) {
8987         PreDupI16Shuffle[I/2] = I/2;
8988         LaneMap[I] = I;
8989       }
8990       int j = TargetLo ? 0 : 4, je = j + 4;
8991       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8992         // Check if j is already a shuffle of this input. This happens when
8993         // there are two adjacent bytes after we move the low one.
8994         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8995           // If we haven't yet mapped the input, search for a slot into which
8996           // we can map it.
8997           while (j < je && PreDupI16Shuffle[j] != -1)
8998             ++j;
8999
9000           if (j == je)
9001             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
9002             return SDValue();
9003
9004           // Map this input with the i16 shuffle.
9005           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
9006         }
9007
9008         // Update the lane map based on the mapping we ended up with.
9009         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
9010       }
9011       V1 = DAG.getBitcast(
9012           MVT::v16i8,
9013           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9014                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
9015
9016       // Unpack the bytes to form the i16s that will be shuffled into place.
9017       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
9018                        MVT::v16i8, V1, V1);
9019
9020       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9021       for (int i = 0; i < 16; ++i)
9022         if (Mask[i] != -1) {
9023           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
9024           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
9025           if (PostDupI16Shuffle[i / 2] == -1)
9026             PostDupI16Shuffle[i / 2] = MappedMask;
9027           else
9028             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
9029                    "Conflicting entrties in the original shuffle!");
9030         }
9031       return DAG.getBitcast(
9032           MVT::v16i8,
9033           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
9034                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
9035     };
9036     if (SDValue V = tryToWidenViaDuplication())
9037       return V;
9038   }
9039
9040   // Use dedicated unpack instructions for masks that match their pattern.
9041   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9042                                          0, 16, 1, 17, 2, 18, 3, 19,
9043                                          // High half.
9044                                          4, 20, 5, 21, 6, 22, 7, 23}))
9045     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
9046   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
9047                                          8, 24, 9, 25, 10, 26, 11, 27,
9048                                          // High half.
9049                                          12, 28, 13, 29, 14, 30, 15, 31}))
9050     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
9051
9052   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
9053   // with PSHUFB. It is important to do this before we attempt to generate any
9054   // blends but after all of the single-input lowerings. If the single input
9055   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
9056   // want to preserve that and we can DAG combine any longer sequences into
9057   // a PSHUFB in the end. But once we start blending from multiple inputs,
9058   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
9059   // and there are *very* few patterns that would actually be faster than the
9060   // PSHUFB approach because of its ability to zero lanes.
9061   //
9062   // FIXME: The only exceptions to the above are blends which are exact
9063   // interleavings with direct instructions supporting them. We currently don't
9064   // handle those well here.
9065   if (Subtarget->hasSSSE3()) {
9066     bool V1InUse = false;
9067     bool V2InUse = false;
9068
9069     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
9070                                                 DAG, V1InUse, V2InUse);
9071
9072     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
9073     // do so. This avoids using them to handle blends-with-zero which is
9074     // important as a single pshufb is significantly faster for that.
9075     if (V1InUse && V2InUse) {
9076       if (Subtarget->hasSSE41())
9077         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
9078                                                       Mask, Subtarget, DAG))
9079           return Blend;
9080
9081       // We can use an unpack to do the blending rather than an or in some
9082       // cases. Even though the or may be (very minorly) more efficient, we
9083       // preference this lowering because there are common cases where part of
9084       // the complexity of the shuffles goes away when we do the final blend as
9085       // an unpack.
9086       // FIXME: It might be worth trying to detect if the unpack-feeding
9087       // shuffles will both be pshufb, in which case we shouldn't bother with
9088       // this.
9089       if (SDValue Unpack =
9090               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
9091         return Unpack;
9092     }
9093
9094     return PSHUFB;
9095   }
9096
9097   // There are special ways we can lower some single-element blends.
9098   if (NumV2Elements == 1)
9099     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
9100                                                          Mask, Subtarget, DAG))
9101       return V;
9102
9103   if (SDValue BitBlend =
9104           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
9105     return BitBlend;
9106
9107   // Check whether a compaction lowering can be done. This handles shuffles
9108   // which take every Nth element for some even N. See the helper function for
9109   // details.
9110   //
9111   // We special case these as they can be particularly efficiently handled with
9112   // the PACKUSB instruction on x86 and they show up in common patterns of
9113   // rearranging bytes to truncate wide elements.
9114   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
9115     // NumEvenDrops is the power of two stride of the elements. Another way of
9116     // thinking about it is that we need to drop the even elements this many
9117     // times to get the original input.
9118     bool IsSingleInput = isSingleInputShuffleMask(Mask);
9119
9120     // First we need to zero all the dropped bytes.
9121     assert(NumEvenDrops <= 3 &&
9122            "No support for dropping even elements more than 3 times.");
9123     // We use the mask type to pick which bytes are preserved based on how many
9124     // elements are dropped.
9125     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
9126     SDValue ByteClearMask = DAG.getBitcast(
9127         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
9128     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
9129     if (!IsSingleInput)
9130       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
9131
9132     // Now pack things back together.
9133     V1 = DAG.getBitcast(MVT::v8i16, V1);
9134     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
9135     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
9136     for (int i = 1; i < NumEvenDrops; ++i) {
9137       Result = DAG.getBitcast(MVT::v8i16, Result);
9138       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
9139     }
9140
9141     return Result;
9142   }
9143
9144   // Handle multi-input cases by blending single-input shuffles.
9145   if (NumV2Elements > 0)
9146     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
9147                                                       Mask, DAG);
9148
9149   // The fallback path for single-input shuffles widens this into two v8i16
9150   // vectors with unpacks, shuffles those, and then pulls them back together
9151   // with a pack.
9152   SDValue V = V1;
9153
9154   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9155   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
9156   for (int i = 0; i < 16; ++i)
9157     if (Mask[i] >= 0)
9158       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
9159
9160   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
9161
9162   SDValue VLoHalf, VHiHalf;
9163   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
9164   // them out and avoid using UNPCK{L,H} to extract the elements of V as
9165   // i16s.
9166   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
9167                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
9168       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
9169                    [](int M) { return M >= 0 && M % 2 == 1; })) {
9170     // Use a mask to drop the high bytes.
9171     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
9172     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
9173                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
9174
9175     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
9176     VHiHalf = DAG.getUNDEF(MVT::v8i16);
9177
9178     // Squash the masks to point directly into VLoHalf.
9179     for (int &M : LoBlendMask)
9180       if (M >= 0)
9181         M /= 2;
9182     for (int &M : HiBlendMask)
9183       if (M >= 0)
9184         M /= 2;
9185   } else {
9186     // Otherwise just unpack the low half of V into VLoHalf and the high half into
9187     // VHiHalf so that we can blend them as i16s.
9188     VLoHalf = DAG.getBitcast(
9189         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
9190     VHiHalf = DAG.getBitcast(
9191         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
9192   }
9193
9194   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
9195   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
9196
9197   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
9198 }
9199
9200 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
9201 ///
9202 /// This routine breaks down the specific type of 128-bit shuffle and
9203 /// dispatches to the lowering routines accordingly.
9204 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9205                                         MVT VT, const X86Subtarget *Subtarget,
9206                                         SelectionDAG &DAG) {
9207   switch (VT.SimpleTy) {
9208   case MVT::v2i64:
9209     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9210   case MVT::v2f64:
9211     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9212   case MVT::v4i32:
9213     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9214   case MVT::v4f32:
9215     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9216   case MVT::v8i16:
9217     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9218   case MVT::v16i8:
9219     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9220
9221   default:
9222     llvm_unreachable("Unimplemented!");
9223   }
9224 }
9225
9226 /// \brief Helper function to test whether a shuffle mask could be
9227 /// simplified by widening the elements being shuffled.
9228 ///
9229 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9230 /// leaves it in an unspecified state.
9231 ///
9232 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9233 /// shuffle masks. The latter have the special property of a '-2' representing
9234 /// a zero-ed lane of a vector.
9235 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9236                                     SmallVectorImpl<int> &WidenedMask) {
9237   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9238     // If both elements are undef, its trivial.
9239     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9240       WidenedMask.push_back(SM_SentinelUndef);
9241       continue;
9242     }
9243
9244     // Check for an undef mask and a mask value properly aligned to fit with
9245     // a pair of values. If we find such a case, use the non-undef mask's value.
9246     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9247       WidenedMask.push_back(Mask[i + 1] / 2);
9248       continue;
9249     }
9250     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9251       WidenedMask.push_back(Mask[i] / 2);
9252       continue;
9253     }
9254
9255     // When zeroing, we need to spread the zeroing across both lanes to widen.
9256     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9257       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9258           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9259         WidenedMask.push_back(SM_SentinelZero);
9260         continue;
9261       }
9262       return false;
9263     }
9264
9265     // Finally check if the two mask values are adjacent and aligned with
9266     // a pair.
9267     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9268       WidenedMask.push_back(Mask[i] / 2);
9269       continue;
9270     }
9271
9272     // Otherwise we can't safely widen the elements used in this shuffle.
9273     return false;
9274   }
9275   assert(WidenedMask.size() == Mask.size() / 2 &&
9276          "Incorrect size of mask after widening the elements!");
9277
9278   return true;
9279 }
9280
9281 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9282 ///
9283 /// This routine just extracts two subvectors, shuffles them independently, and
9284 /// then concatenates them back together. This should work effectively with all
9285 /// AVX vector shuffle types.
9286 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9287                                           SDValue V2, ArrayRef<int> Mask,
9288                                           SelectionDAG &DAG) {
9289   assert(VT.getSizeInBits() >= 256 &&
9290          "Only for 256-bit or wider vector shuffles!");
9291   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9292   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9293
9294   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9295   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9296
9297   int NumElements = VT.getVectorNumElements();
9298   int SplitNumElements = NumElements / 2;
9299   MVT ScalarVT = VT.getScalarType();
9300   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9301
9302   // Rather than splitting build-vectors, just build two narrower build
9303   // vectors. This helps shuffling with splats and zeros.
9304   auto SplitVector = [&](SDValue V) {
9305     while (V.getOpcode() == ISD::BITCAST)
9306       V = V->getOperand(0);
9307
9308     MVT OrigVT = V.getSimpleValueType();
9309     int OrigNumElements = OrigVT.getVectorNumElements();
9310     int OrigSplitNumElements = OrigNumElements / 2;
9311     MVT OrigScalarVT = OrigVT.getScalarType();
9312     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9313
9314     SDValue LoV, HiV;
9315
9316     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9317     if (!BV) {
9318       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9319                         DAG.getIntPtrConstant(0, DL));
9320       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9321                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9322     } else {
9323
9324       SmallVector<SDValue, 16> LoOps, HiOps;
9325       for (int i = 0; i < OrigSplitNumElements; ++i) {
9326         LoOps.push_back(BV->getOperand(i));
9327         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9328       }
9329       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9330       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9331     }
9332     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9333                           DAG.getBitcast(SplitVT, HiV));
9334   };
9335
9336   SDValue LoV1, HiV1, LoV2, HiV2;
9337   std::tie(LoV1, HiV1) = SplitVector(V1);
9338   std::tie(LoV2, HiV2) = SplitVector(V2);
9339
9340   // Now create two 4-way blends of these half-width vectors.
9341   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9342     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9343     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9344     for (int i = 0; i < SplitNumElements; ++i) {
9345       int M = HalfMask[i];
9346       if (M >= NumElements) {
9347         if (M >= NumElements + SplitNumElements)
9348           UseHiV2 = true;
9349         else
9350           UseLoV2 = true;
9351         V2BlendMask.push_back(M - NumElements);
9352         V1BlendMask.push_back(-1);
9353         BlendMask.push_back(SplitNumElements + i);
9354       } else if (M >= 0) {
9355         if (M >= SplitNumElements)
9356           UseHiV1 = true;
9357         else
9358           UseLoV1 = true;
9359         V2BlendMask.push_back(-1);
9360         V1BlendMask.push_back(M);
9361         BlendMask.push_back(i);
9362       } else {
9363         V2BlendMask.push_back(-1);
9364         V1BlendMask.push_back(-1);
9365         BlendMask.push_back(-1);
9366       }
9367     }
9368
9369     // Because the lowering happens after all combining takes place, we need to
9370     // manually combine these blend masks as much as possible so that we create
9371     // a minimal number of high-level vector shuffle nodes.
9372
9373     // First try just blending the halves of V1 or V2.
9374     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9375       return DAG.getUNDEF(SplitVT);
9376     if (!UseLoV2 && !UseHiV2)
9377       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9378     if (!UseLoV1 && !UseHiV1)
9379       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9380
9381     SDValue V1Blend, V2Blend;
9382     if (UseLoV1 && UseHiV1) {
9383       V1Blend =
9384         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9385     } else {
9386       // We only use half of V1 so map the usage down into the final blend mask.
9387       V1Blend = UseLoV1 ? LoV1 : HiV1;
9388       for (int i = 0; i < SplitNumElements; ++i)
9389         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9390           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9391     }
9392     if (UseLoV2 && UseHiV2) {
9393       V2Blend =
9394         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9395     } else {
9396       // We only use half of V2 so map the usage down into the final blend mask.
9397       V2Blend = UseLoV2 ? LoV2 : HiV2;
9398       for (int i = 0; i < SplitNumElements; ++i)
9399         if (BlendMask[i] >= SplitNumElements)
9400           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9401     }
9402     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9403   };
9404   SDValue Lo = HalfBlend(LoMask);
9405   SDValue Hi = HalfBlend(HiMask);
9406   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9407 }
9408
9409 /// \brief Either split a vector in halves or decompose the shuffles and the
9410 /// blend.
9411 ///
9412 /// This is provided as a good fallback for many lowerings of non-single-input
9413 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9414 /// between splitting the shuffle into 128-bit components and stitching those
9415 /// back together vs. extracting the single-input shuffles and blending those
9416 /// results.
9417 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9418                                                 SDValue V2, ArrayRef<int> Mask,
9419                                                 SelectionDAG &DAG) {
9420   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9421                                             "lower single-input shuffles as it "
9422                                             "could then recurse on itself.");
9423   int Size = Mask.size();
9424
9425   // If this can be modeled as a broadcast of two elements followed by a blend,
9426   // prefer that lowering. This is especially important because broadcasts can
9427   // often fold with memory operands.
9428   auto DoBothBroadcast = [&] {
9429     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9430     for (int M : Mask)
9431       if (M >= Size) {
9432         if (V2BroadcastIdx == -1)
9433           V2BroadcastIdx = M - Size;
9434         else if (M - Size != V2BroadcastIdx)
9435           return false;
9436       } else if (M >= 0) {
9437         if (V1BroadcastIdx == -1)
9438           V1BroadcastIdx = M;
9439         else if (M != V1BroadcastIdx)
9440           return false;
9441       }
9442     return true;
9443   };
9444   if (DoBothBroadcast())
9445     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9446                                                       DAG);
9447
9448   // If the inputs all stem from a single 128-bit lane of each input, then we
9449   // split them rather than blending because the split will decompose to
9450   // unusually few instructions.
9451   int LaneCount = VT.getSizeInBits() / 128;
9452   int LaneSize = Size / LaneCount;
9453   SmallBitVector LaneInputs[2];
9454   LaneInputs[0].resize(LaneCount, false);
9455   LaneInputs[1].resize(LaneCount, false);
9456   for (int i = 0; i < Size; ++i)
9457     if (Mask[i] >= 0)
9458       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9459   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9460     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9461
9462   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9463   // that the decomposed single-input shuffles don't end up here.
9464   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9465 }
9466
9467 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9468 /// a permutation and blend of those lanes.
9469 ///
9470 /// This essentially blends the out-of-lane inputs to each lane into the lane
9471 /// from a permuted copy of the vector. This lowering strategy results in four
9472 /// instructions in the worst case for a single-input cross lane shuffle which
9473 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9474 /// of. Special cases for each particular shuffle pattern should be handled
9475 /// prior to trying this lowering.
9476 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9477                                                        SDValue V1, SDValue V2,
9478                                                        ArrayRef<int> Mask,
9479                                                        SelectionDAG &DAG) {
9480   // FIXME: This should probably be generalized for 512-bit vectors as well.
9481   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9482   int LaneSize = Mask.size() / 2;
9483
9484   // If there are only inputs from one 128-bit lane, splitting will in fact be
9485   // less expensive. The flags track whether the given lane contains an element
9486   // that crosses to another lane.
9487   bool LaneCrossing[2] = {false, false};
9488   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9489     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9490       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9491   if (!LaneCrossing[0] || !LaneCrossing[1])
9492     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9493
9494   if (isSingleInputShuffleMask(Mask)) {
9495     SmallVector<int, 32> FlippedBlendMask;
9496     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9497       FlippedBlendMask.push_back(
9498           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9499                                   ? Mask[i]
9500                                   : Mask[i] % LaneSize +
9501                                         (i / LaneSize) * LaneSize + Size));
9502
9503     // Flip the vector, and blend the results which should now be in-lane. The
9504     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9505     // 5 for the high source. The value 3 selects the high half of source 2 and
9506     // the value 2 selects the low half of source 2. We only use source 2 to
9507     // allow folding it into a memory operand.
9508     unsigned PERMMask = 3 | 2 << 4;
9509     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9510                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9511     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9512   }
9513
9514   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9515   // will be handled by the above logic and a blend of the results, much like
9516   // other patterns in AVX.
9517   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9518 }
9519
9520 /// \brief Handle lowering 2-lane 128-bit shuffles.
9521 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9522                                         SDValue V2, ArrayRef<int> Mask,
9523                                         const X86Subtarget *Subtarget,
9524                                         SelectionDAG &DAG) {
9525   // TODO: If minimizing size and one of the inputs is a zero vector and the
9526   // the zero vector has only one use, we could use a VPERM2X128 to save the
9527   // instruction bytes needed to explicitly generate the zero vector.
9528
9529   // Blends are faster and handle all the non-lane-crossing cases.
9530   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9531                                                 Subtarget, DAG))
9532     return Blend;
9533
9534   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9535   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9536
9537   // If either input operand is a zero vector, use VPERM2X128 because its mask
9538   // allows us to replace the zero input with an implicit zero.
9539   if (!IsV1Zero && !IsV2Zero) {
9540     // Check for patterns which can be matched with a single insert of a 128-bit
9541     // subvector.
9542     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9543     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9544       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9545                                    VT.getVectorNumElements() / 2);
9546       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9547                                 DAG.getIntPtrConstant(0, DL));
9548       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9549                                 OnlyUsesV1 ? V1 : V2,
9550                                 DAG.getIntPtrConstant(0, DL));
9551       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9552     }
9553   }
9554
9555   // Otherwise form a 128-bit permutation. After accounting for undefs,
9556   // convert the 64-bit shuffle mask selection values into 128-bit
9557   // selection bits by dividing the indexes by 2 and shifting into positions
9558   // defined by a vperm2*128 instruction's immediate control byte.
9559
9560   // The immediate permute control byte looks like this:
9561   //    [1:0] - select 128 bits from sources for low half of destination
9562   //    [2]   - ignore
9563   //    [3]   - zero low half of destination
9564   //    [5:4] - select 128 bits from sources for high half of destination
9565   //    [6]   - ignore
9566   //    [7]   - zero high half of destination
9567
9568   int MaskLO = Mask[0];
9569   if (MaskLO == SM_SentinelUndef)
9570     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9571
9572   int MaskHI = Mask[2];
9573   if (MaskHI == SM_SentinelUndef)
9574     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9575
9576   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9577
9578   // If either input is a zero vector, replace it with an undef input.
9579   // Shuffle mask values <  4 are selecting elements of V1.
9580   // Shuffle mask values >= 4 are selecting elements of V2.
9581   // Adjust each half of the permute mask by clearing the half that was
9582   // selecting the zero vector and setting the zero mask bit.
9583   if (IsV1Zero) {
9584     V1 = DAG.getUNDEF(VT);
9585     if (MaskLO < 4)
9586       PermMask = (PermMask & 0xf0) | 0x08;
9587     if (MaskHI < 4)
9588       PermMask = (PermMask & 0x0f) | 0x80;
9589   }
9590   if (IsV2Zero) {
9591     V2 = DAG.getUNDEF(VT);
9592     if (MaskLO >= 4)
9593       PermMask = (PermMask & 0xf0) | 0x08;
9594     if (MaskHI >= 4)
9595       PermMask = (PermMask & 0x0f) | 0x80;
9596   }
9597
9598   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9599                      DAG.getConstant(PermMask, DL, MVT::i8));
9600 }
9601
9602 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9603 /// shuffling each lane.
9604 ///
9605 /// This will only succeed when the result of fixing the 128-bit lanes results
9606 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9607 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9608 /// the lane crosses early and then use simpler shuffles within each lane.
9609 ///
9610 /// FIXME: It might be worthwhile at some point to support this without
9611 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9612 /// in x86 only floating point has interesting non-repeating shuffles, and even
9613 /// those are still *marginally* more expensive.
9614 static SDValue lowerVectorShuffleByMerging128BitLanes(
9615     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9616     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9617   assert(!isSingleInputShuffleMask(Mask) &&
9618          "This is only useful with multiple inputs.");
9619
9620   int Size = Mask.size();
9621   int LaneSize = 128 / VT.getScalarSizeInBits();
9622   int NumLanes = Size / LaneSize;
9623   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9624
9625   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9626   // check whether the in-128-bit lane shuffles share a repeating pattern.
9627   SmallVector<int, 4> Lanes;
9628   Lanes.resize(NumLanes, -1);
9629   SmallVector<int, 4> InLaneMask;
9630   InLaneMask.resize(LaneSize, -1);
9631   for (int i = 0; i < Size; ++i) {
9632     if (Mask[i] < 0)
9633       continue;
9634
9635     int j = i / LaneSize;
9636
9637     if (Lanes[j] < 0) {
9638       // First entry we've seen for this lane.
9639       Lanes[j] = Mask[i] / LaneSize;
9640     } else if (Lanes[j] != Mask[i] / LaneSize) {
9641       // This doesn't match the lane selected previously!
9642       return SDValue();
9643     }
9644
9645     // Check that within each lane we have a consistent shuffle mask.
9646     int k = i % LaneSize;
9647     if (InLaneMask[k] < 0) {
9648       InLaneMask[k] = Mask[i] % LaneSize;
9649     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9650       // This doesn't fit a repeating in-lane mask.
9651       return SDValue();
9652     }
9653   }
9654
9655   // First shuffle the lanes into place.
9656   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9657                                 VT.getSizeInBits() / 64);
9658   SmallVector<int, 8> LaneMask;
9659   LaneMask.resize(NumLanes * 2, -1);
9660   for (int i = 0; i < NumLanes; ++i)
9661     if (Lanes[i] >= 0) {
9662       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9663       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9664     }
9665
9666   V1 = DAG.getBitcast(LaneVT, V1);
9667   V2 = DAG.getBitcast(LaneVT, V2);
9668   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9669
9670   // Cast it back to the type we actually want.
9671   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9672
9673   // Now do a simple shuffle that isn't lane crossing.
9674   SmallVector<int, 8> NewMask;
9675   NewMask.resize(Size, -1);
9676   for (int i = 0; i < Size; ++i)
9677     if (Mask[i] >= 0)
9678       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9679   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9680          "Must not introduce lane crosses at this point!");
9681
9682   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9683 }
9684
9685 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9686 /// given mask.
9687 ///
9688 /// This returns true if the elements from a particular input are already in the
9689 /// slot required by the given mask and require no permutation.
9690 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9691   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9692   int Size = Mask.size();
9693   for (int i = 0; i < Size; ++i)
9694     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9695       return false;
9696
9697   return true;
9698 }
9699
9700 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9701                                             ArrayRef<int> Mask, SDValue V1,
9702                                             SDValue V2, SelectionDAG &DAG) {
9703
9704   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9705   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9706   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9707   int NumElts = VT.getVectorNumElements();
9708   bool ShufpdMask = true;
9709   bool CommutableMask = true;
9710   unsigned Immediate = 0;
9711   for (int i = 0; i < NumElts; ++i) {
9712     if (Mask[i] < 0)
9713       continue;
9714     int Val = (i & 6) + NumElts * (i & 1);
9715     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9716     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9717       ShufpdMask = false;
9718     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9719       CommutableMask = false;
9720     Immediate |= (Mask[i] % 2) << i;
9721   }
9722   if (ShufpdMask)
9723     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9724                        DAG.getConstant(Immediate, DL, MVT::i8));
9725   if (CommutableMask)
9726     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9727                        DAG.getConstant(Immediate, DL, MVT::i8));
9728   return SDValue();
9729 }
9730
9731 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9732 ///
9733 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9734 /// isn't available.
9735 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9736                                        const X86Subtarget *Subtarget,
9737                                        SelectionDAG &DAG) {
9738   SDLoc DL(Op);
9739   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9740   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9741   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9742   ArrayRef<int> Mask = SVOp->getMask();
9743   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9744
9745   SmallVector<int, 4> WidenedMask;
9746   if (canWidenShuffleElements(Mask, WidenedMask))
9747     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9748                                     DAG);
9749
9750   if (isSingleInputShuffleMask(Mask)) {
9751     // Check for being able to broadcast a single element.
9752     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9753                                                           Mask, Subtarget, DAG))
9754       return Broadcast;
9755
9756     // Use low duplicate instructions for masks that match their pattern.
9757     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9758       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9759
9760     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9761       // Non-half-crossing single input shuffles can be lowerid with an
9762       // interleaved permutation.
9763       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9764                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9765       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9766                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9767     }
9768
9769     // With AVX2 we have direct support for this permutation.
9770     if (Subtarget->hasAVX2())
9771       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9772                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9773
9774     // Otherwise, fall back.
9775     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9776                                                    DAG);
9777   }
9778
9779   // X86 has dedicated unpack instructions that can handle specific blend
9780   // operations: UNPCKH and UNPCKL.
9781   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9782     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9783   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9784     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9785   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9786     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9787   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9788     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9789
9790   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9791                                                 Subtarget, DAG))
9792     return Blend;
9793
9794   // Check if the blend happens to exactly fit that of SHUFPD.
9795   if (SDValue Op =
9796       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9797     return Op;
9798
9799   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9800   // shuffle. However, if we have AVX2 and either inputs are already in place,
9801   // we will be able to shuffle even across lanes the other input in a single
9802   // instruction so skip this pattern.
9803   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9804                                  isShuffleMaskInputInPlace(1, Mask))))
9805     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9806             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9807       return Result;
9808
9809   // If we have AVX2 then we always want to lower with a blend because an v4 we
9810   // can fully permute the elements.
9811   if (Subtarget->hasAVX2())
9812     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9813                                                       Mask, DAG);
9814
9815   // Otherwise fall back on generic lowering.
9816   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9817 }
9818
9819 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9820 ///
9821 /// This routine is only called when we have AVX2 and thus a reasonable
9822 /// instruction set for v4i64 shuffling..
9823 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9824                                        const X86Subtarget *Subtarget,
9825                                        SelectionDAG &DAG) {
9826   SDLoc DL(Op);
9827   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9828   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9829   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9830   ArrayRef<int> Mask = SVOp->getMask();
9831   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9832   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9833
9834   SmallVector<int, 4> WidenedMask;
9835   if (canWidenShuffleElements(Mask, WidenedMask))
9836     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9837                                     DAG);
9838
9839   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9840                                                 Subtarget, DAG))
9841     return Blend;
9842
9843   // Check for being able to broadcast a single element.
9844   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9845                                                         Mask, Subtarget, DAG))
9846     return Broadcast;
9847
9848   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9849   // use lower latency instructions that will operate on both 128-bit lanes.
9850   SmallVector<int, 2> RepeatedMask;
9851   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9852     if (isSingleInputShuffleMask(Mask)) {
9853       int PSHUFDMask[] = {-1, -1, -1, -1};
9854       for (int i = 0; i < 2; ++i)
9855         if (RepeatedMask[i] >= 0) {
9856           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9857           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9858         }
9859       return DAG.getBitcast(
9860           MVT::v4i64,
9861           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9862                       DAG.getBitcast(MVT::v8i32, V1),
9863                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9864     }
9865   }
9866
9867   // AVX2 provides a direct instruction for permuting a single input across
9868   // lanes.
9869   if (isSingleInputShuffleMask(Mask))
9870     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9871                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9872
9873   // Try to use shift instructions.
9874   if (SDValue Shift =
9875           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9876     return Shift;
9877
9878   // Use dedicated unpack instructions for masks that match their pattern.
9879   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9880     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9881   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9882     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9883   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9884     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9885   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9886     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9887
9888   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9889   // shuffle. However, if we have AVX2 and either inputs are already in place,
9890   // we will be able to shuffle even across lanes the other input in a single
9891   // instruction so skip this pattern.
9892   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9893                                  isShuffleMaskInputInPlace(1, Mask))))
9894     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9895             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9896       return Result;
9897
9898   // Otherwise fall back on generic blend lowering.
9899   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9900                                                     Mask, DAG);
9901 }
9902
9903 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9904 ///
9905 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9906 /// isn't available.
9907 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9908                                        const X86Subtarget *Subtarget,
9909                                        SelectionDAG &DAG) {
9910   SDLoc DL(Op);
9911   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9912   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9913   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9914   ArrayRef<int> Mask = SVOp->getMask();
9915   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9916
9917   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9918                                                 Subtarget, DAG))
9919     return Blend;
9920
9921   // Check for being able to broadcast a single element.
9922   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9923                                                         Mask, Subtarget, DAG))
9924     return Broadcast;
9925
9926   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9927   // options to efficiently lower the shuffle.
9928   SmallVector<int, 4> RepeatedMask;
9929   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9930     assert(RepeatedMask.size() == 4 &&
9931            "Repeated masks must be half the mask width!");
9932
9933     // Use even/odd duplicate instructions for masks that match their pattern.
9934     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9935       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9936     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9937       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9938
9939     if (isSingleInputShuffleMask(Mask))
9940       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9941                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9942
9943     // Use dedicated unpack instructions for masks that match their pattern.
9944     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9945       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9946     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9947       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9948     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9949       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9950     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9951       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9952
9953     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9954     // have already handled any direct blends. We also need to squash the
9955     // repeated mask into a simulated v4f32 mask.
9956     for (int i = 0; i < 4; ++i)
9957       if (RepeatedMask[i] >= 8)
9958         RepeatedMask[i] -= 4;
9959     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9960   }
9961
9962   // If we have a single input shuffle with different shuffle patterns in the
9963   // two 128-bit lanes use the variable mask to VPERMILPS.
9964   if (isSingleInputShuffleMask(Mask)) {
9965     SDValue VPermMask[8];
9966     for (int i = 0; i < 8; ++i)
9967       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9968                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9969     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9970       return DAG.getNode(
9971           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9972           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9973
9974     if (Subtarget->hasAVX2())
9975       return DAG.getNode(
9976           X86ISD::VPERMV, DL, MVT::v8f32,
9977           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9978                                                  MVT::v8i32, VPermMask)),
9979           V1);
9980
9981     // Otherwise, fall back.
9982     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9983                                                    DAG);
9984   }
9985
9986   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9987   // shuffle.
9988   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9989           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9990     return Result;
9991
9992   // If we have AVX2 then we always want to lower with a blend because at v8 we
9993   // can fully permute the elements.
9994   if (Subtarget->hasAVX2())
9995     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9996                                                       Mask, DAG);
9997
9998   // Otherwise fall back on generic lowering.
9999   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
10000 }
10001
10002 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
10003 ///
10004 /// This routine is only called when we have AVX2 and thus a reasonable
10005 /// instruction set for v8i32 shuffling..
10006 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10007                                        const X86Subtarget *Subtarget,
10008                                        SelectionDAG &DAG) {
10009   SDLoc DL(Op);
10010   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10011   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
10012   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10013   ArrayRef<int> Mask = SVOp->getMask();
10014   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10015   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
10016
10017   // Whenever we can lower this as a zext, that instruction is strictly faster
10018   // than any alternative. It also allows us to fold memory operands into the
10019   // shuffle in many cases.
10020   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
10021                                                          Mask, Subtarget, DAG))
10022     return ZExt;
10023
10024   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
10025                                                 Subtarget, DAG))
10026     return Blend;
10027
10028   // Check for being able to broadcast a single element.
10029   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
10030                                                         Mask, Subtarget, DAG))
10031     return Broadcast;
10032
10033   // If the shuffle mask is repeated in each 128-bit lane we can use more
10034   // efficient instructions that mirror the shuffles across the two 128-bit
10035   // lanes.
10036   SmallVector<int, 4> RepeatedMask;
10037   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
10038     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
10039     if (isSingleInputShuffleMask(Mask))
10040       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
10041                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
10042
10043     // Use dedicated unpack instructions for masks that match their pattern.
10044     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
10045       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
10046     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
10047       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
10048     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
10049       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
10050     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
10051       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
10052   }
10053
10054   // Try to use shift instructions.
10055   if (SDValue Shift =
10056           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
10057     return Shift;
10058
10059   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10060           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10061     return Rotate;
10062
10063   // If the shuffle patterns aren't repeated but it is a single input, directly
10064   // generate a cross-lane VPERMD instruction.
10065   if (isSingleInputShuffleMask(Mask)) {
10066     SDValue VPermMask[8];
10067     for (int i = 0; i < 8; ++i)
10068       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
10069                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
10070     return DAG.getNode(
10071         X86ISD::VPERMV, DL, MVT::v8i32,
10072         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
10073   }
10074
10075   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10076   // shuffle.
10077   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10078           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
10079     return Result;
10080
10081   // Otherwise fall back on generic blend lowering.
10082   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
10083                                                     Mask, DAG);
10084 }
10085
10086 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
10087 ///
10088 /// This routine is only called when we have AVX2 and thus a reasonable
10089 /// instruction set for v16i16 shuffling..
10090 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10091                                         const X86Subtarget *Subtarget,
10092                                         SelectionDAG &DAG) {
10093   SDLoc DL(Op);
10094   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10095   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
10096   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10097   ArrayRef<int> Mask = SVOp->getMask();
10098   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10099   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
10100
10101   // Whenever we can lower this as a zext, that instruction is strictly faster
10102   // than any alternative. It also allows us to fold memory operands into the
10103   // shuffle in many cases.
10104   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
10105                                                          Mask, Subtarget, DAG))
10106     return ZExt;
10107
10108   // Check for being able to broadcast a single element.
10109   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
10110                                                         Mask, Subtarget, DAG))
10111     return Broadcast;
10112
10113   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
10114                                                 Subtarget, DAG))
10115     return Blend;
10116
10117   // Use dedicated unpack instructions for masks that match their pattern.
10118   if (isShuffleEquivalent(V1, V2, Mask,
10119                           {// First 128-bit lane:
10120                            0, 16, 1, 17, 2, 18, 3, 19,
10121                            // Second 128-bit lane:
10122                            8, 24, 9, 25, 10, 26, 11, 27}))
10123     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
10124   if (isShuffleEquivalent(V1, V2, Mask,
10125                           {// First 128-bit lane:
10126                            4, 20, 5, 21, 6, 22, 7, 23,
10127                            // Second 128-bit lane:
10128                            12, 28, 13, 29, 14, 30, 15, 31}))
10129     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
10130
10131   // Try to use shift instructions.
10132   if (SDValue Shift =
10133           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
10134     return Shift;
10135
10136   // Try to use byte rotation instructions.
10137   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10138           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10139     return Rotate;
10140
10141   if (isSingleInputShuffleMask(Mask)) {
10142     // There are no generalized cross-lane shuffle operations available on i16
10143     // element types.
10144     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
10145       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
10146                                                      Mask, DAG);
10147
10148     SmallVector<int, 8> RepeatedMask;
10149     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
10150       // As this is a single-input shuffle, the repeated mask should be
10151       // a strictly valid v8i16 mask that we can pass through to the v8i16
10152       // lowering to handle even the v16 case.
10153       return lowerV8I16GeneralSingleInputVectorShuffle(
10154           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
10155     }
10156
10157     SDValue PSHUFBMask[32];
10158     for (int i = 0; i < 16; ++i) {
10159       if (Mask[i] == -1) {
10160         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
10161         continue;
10162       }
10163
10164       int M = i < 8 ? Mask[i] : Mask[i] - 8;
10165       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
10166       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
10167       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
10168     }
10169     return DAG.getBitcast(MVT::v16i16,
10170                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
10171                                       DAG.getBitcast(MVT::v32i8, V1),
10172                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
10173                                                   MVT::v32i8, PSHUFBMask)));
10174   }
10175
10176   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10177   // shuffle.
10178   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10179           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
10180     return Result;
10181
10182   // Otherwise fall back on generic lowering.
10183   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
10184 }
10185
10186 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
10187 ///
10188 /// This routine is only called when we have AVX2 and thus a reasonable
10189 /// instruction set for v32i8 shuffling..
10190 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10191                                        const X86Subtarget *Subtarget,
10192                                        SelectionDAG &DAG) {
10193   SDLoc DL(Op);
10194   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10195   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
10196   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10197   ArrayRef<int> Mask = SVOp->getMask();
10198   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10199   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
10200
10201   // Whenever we can lower this as a zext, that instruction is strictly faster
10202   // than any alternative. It also allows us to fold memory operands into the
10203   // shuffle in many cases.
10204   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
10205                                                          Mask, Subtarget, DAG))
10206     return ZExt;
10207
10208   // Check for being able to broadcast a single element.
10209   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10210                                                         Mask, Subtarget, DAG))
10211     return Broadcast;
10212
10213   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10214                                                 Subtarget, DAG))
10215     return Blend;
10216
10217   // Use dedicated unpack instructions for masks that match their pattern.
10218   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10219   // 256-bit lanes.
10220   if (isShuffleEquivalent(
10221           V1, V2, Mask,
10222           {// First 128-bit lane:
10223            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10224            // Second 128-bit lane:
10225            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10226     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10227   if (isShuffleEquivalent(
10228           V1, V2, Mask,
10229           {// First 128-bit lane:
10230            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10231            // Second 128-bit lane:
10232            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10233     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10234
10235   // Try to use shift instructions.
10236   if (SDValue Shift =
10237           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10238     return Shift;
10239
10240   // Try to use byte rotation instructions.
10241   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10242           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10243     return Rotate;
10244
10245   if (isSingleInputShuffleMask(Mask)) {
10246     // There are no generalized cross-lane shuffle operations available on i8
10247     // element types.
10248     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10249       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10250                                                      Mask, DAG);
10251
10252     SDValue PSHUFBMask[32];
10253     for (int i = 0; i < 32; ++i)
10254       PSHUFBMask[i] =
10255           Mask[i] < 0
10256               ? DAG.getUNDEF(MVT::i8)
10257               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10258                                 MVT::i8);
10259
10260     return DAG.getNode(
10261         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10262         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10263   }
10264
10265   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10266   // shuffle.
10267   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10268           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10269     return Result;
10270
10271   // Otherwise fall back on generic lowering.
10272   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10273 }
10274
10275 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10276 ///
10277 /// This routine either breaks down the specific type of a 256-bit x86 vector
10278 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10279 /// together based on the available instructions.
10280 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10281                                         MVT VT, const X86Subtarget *Subtarget,
10282                                         SelectionDAG &DAG) {
10283   SDLoc DL(Op);
10284   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10285   ArrayRef<int> Mask = SVOp->getMask();
10286
10287   // If we have a single input to the zero element, insert that into V1 if we
10288   // can do so cheaply.
10289   int NumElts = VT.getVectorNumElements();
10290   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10291     return M >= NumElts;
10292   });
10293
10294   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10295     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10296                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10297       return Insertion;
10298
10299   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10300   // check for those subtargets here and avoid much of the subtarget querying in
10301   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10302   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10303   // floating point types there eventually, just immediately cast everything to
10304   // a float and operate entirely in that domain.
10305   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10306     int ElementBits = VT.getScalarSizeInBits();
10307     if (ElementBits < 32)
10308       // No floating point type available, decompose into 128-bit vectors.
10309       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10310
10311     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10312                                 VT.getVectorNumElements());
10313     V1 = DAG.getBitcast(FpVT, V1);
10314     V2 = DAG.getBitcast(FpVT, V2);
10315     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10316   }
10317
10318   switch (VT.SimpleTy) {
10319   case MVT::v4f64:
10320     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10321   case MVT::v4i64:
10322     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10323   case MVT::v8f32:
10324     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10325   case MVT::v8i32:
10326     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10327   case MVT::v16i16:
10328     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10329   case MVT::v32i8:
10330     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10331
10332   default:
10333     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10334   }
10335 }
10336
10337 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10338 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10339                                        const X86Subtarget *Subtarget,
10340                                        SelectionDAG &DAG) {
10341   SDLoc DL(Op);
10342   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10343   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10344   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10345   ArrayRef<int> Mask = SVOp->getMask();
10346   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10347
10348   // X86 has dedicated unpack instructions that can handle specific blend
10349   // operations: UNPCKH and UNPCKL.
10350   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10351     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10352   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10353     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10354
10355   // FIXME: Implement direct support for this type!
10356   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10357 }
10358
10359 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10360 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10361                                        const X86Subtarget *Subtarget,
10362                                        SelectionDAG &DAG) {
10363   SDLoc DL(Op);
10364   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10365   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10366   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10367   ArrayRef<int> Mask = SVOp->getMask();
10368   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10369
10370   // Use dedicated unpack instructions for masks that match their pattern.
10371   if (isShuffleEquivalent(V1, V2, Mask,
10372                           {// First 128-bit lane.
10373                            0, 16, 1, 17, 4, 20, 5, 21,
10374                            // Second 128-bit lane.
10375                            8, 24, 9, 25, 12, 28, 13, 29}))
10376     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10377   if (isShuffleEquivalent(V1, V2, Mask,
10378                           {// First 128-bit lane.
10379                            2, 18, 3, 19, 6, 22, 7, 23,
10380                            // Second 128-bit lane.
10381                            10, 26, 11, 27, 14, 30, 15, 31}))
10382     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10383
10384   // FIXME: Implement direct support for this type!
10385   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10386 }
10387
10388 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10389 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10390                                        const X86Subtarget *Subtarget,
10391                                        SelectionDAG &DAG) {
10392   SDLoc DL(Op);
10393   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10394   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10395   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10396   ArrayRef<int> Mask = SVOp->getMask();
10397   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10398
10399   // X86 has dedicated unpack instructions that can handle specific blend
10400   // operations: UNPCKH and UNPCKL.
10401   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10402     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10403   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10404     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10405
10406   // FIXME: Implement direct support for this type!
10407   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10408 }
10409
10410 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10411 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10412                                        const X86Subtarget *Subtarget,
10413                                        SelectionDAG &DAG) {
10414   SDLoc DL(Op);
10415   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10416   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10417   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10418   ArrayRef<int> Mask = SVOp->getMask();
10419   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10420
10421   // Use dedicated unpack instructions for masks that match their pattern.
10422   if (isShuffleEquivalent(V1, V2, Mask,
10423                           {// First 128-bit lane.
10424                            0, 16, 1, 17, 4, 20, 5, 21,
10425                            // Second 128-bit lane.
10426                            8, 24, 9, 25, 12, 28, 13, 29}))
10427     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10428   if (isShuffleEquivalent(V1, V2, Mask,
10429                           {// First 128-bit lane.
10430                            2, 18, 3, 19, 6, 22, 7, 23,
10431                            // Second 128-bit lane.
10432                            10, 26, 11, 27, 14, 30, 15, 31}))
10433     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10434
10435   // FIXME: Implement direct support for this type!
10436   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10437 }
10438
10439 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10440 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10441                                         const X86Subtarget *Subtarget,
10442                                         SelectionDAG &DAG) {
10443   SDLoc DL(Op);
10444   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10445   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10446   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10447   ArrayRef<int> Mask = SVOp->getMask();
10448   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10449   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10450
10451   // FIXME: Implement direct support for this type!
10452   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10453 }
10454
10455 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10456 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10457                                        const X86Subtarget *Subtarget,
10458                                        SelectionDAG &DAG) {
10459   SDLoc DL(Op);
10460   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10461   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10462   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10463   ArrayRef<int> Mask = SVOp->getMask();
10464   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10465   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10466
10467   // FIXME: Implement direct support for this type!
10468   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10469 }
10470
10471 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10472 ///
10473 /// This routine either breaks down the specific type of a 512-bit x86 vector
10474 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10475 /// together based on the available instructions.
10476 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10477                                         MVT VT, const X86Subtarget *Subtarget,
10478                                         SelectionDAG &DAG) {
10479   SDLoc DL(Op);
10480   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10481   ArrayRef<int> Mask = SVOp->getMask();
10482   assert(Subtarget->hasAVX512() &&
10483          "Cannot lower 512-bit vectors w/ basic ISA!");
10484
10485   // Check for being able to broadcast a single element.
10486   if (SDValue Broadcast =
10487           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10488     return Broadcast;
10489
10490   // Dispatch to each element type for lowering. If we don't have supprot for
10491   // specific element type shuffles at 512 bits, immediately split them and
10492   // lower them. Each lowering routine of a given type is allowed to assume that
10493   // the requisite ISA extensions for that element type are available.
10494   switch (VT.SimpleTy) {
10495   case MVT::v8f64:
10496     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10497   case MVT::v16f32:
10498     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10499   case MVT::v8i64:
10500     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10501   case MVT::v16i32:
10502     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10503   case MVT::v32i16:
10504     if (Subtarget->hasBWI())
10505       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10506     break;
10507   case MVT::v64i8:
10508     if (Subtarget->hasBWI())
10509       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10510     break;
10511
10512   default:
10513     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10514   }
10515
10516   // Otherwise fall back on splitting.
10517   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10518 }
10519
10520 /// \brief Top-level lowering for x86 vector shuffles.
10521 ///
10522 /// This handles decomposition, canonicalization, and lowering of all x86
10523 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10524 /// above in helper routines. The canonicalization attempts to widen shuffles
10525 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10526 /// s.t. only one of the two inputs needs to be tested, etc.
10527 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10528                                   SelectionDAG &DAG) {
10529   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10530   ArrayRef<int> Mask = SVOp->getMask();
10531   SDValue V1 = Op.getOperand(0);
10532   SDValue V2 = Op.getOperand(1);
10533   MVT VT = Op.getSimpleValueType();
10534   int NumElements = VT.getVectorNumElements();
10535   SDLoc dl(Op);
10536
10537   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10538
10539   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10540   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10541   if (V1IsUndef && V2IsUndef)
10542     return DAG.getUNDEF(VT);
10543
10544   // When we create a shuffle node we put the UNDEF node to second operand,
10545   // but in some cases the first operand may be transformed to UNDEF.
10546   // In this case we should just commute the node.
10547   if (V1IsUndef)
10548     return DAG.getCommutedVectorShuffle(*SVOp);
10549
10550   // Check for non-undef masks pointing at an undef vector and make the masks
10551   // undef as well. This makes it easier to match the shuffle based solely on
10552   // the mask.
10553   if (V2IsUndef)
10554     for (int M : Mask)
10555       if (M >= NumElements) {
10556         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10557         for (int &M : NewMask)
10558           if (M >= NumElements)
10559             M = -1;
10560         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10561       }
10562
10563   // We actually see shuffles that are entirely re-arrangements of a set of
10564   // zero inputs. This mostly happens while decomposing complex shuffles into
10565   // simple ones. Directly lower these as a buildvector of zeros.
10566   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10567   if (Zeroable.all())
10568     return getZeroVector(VT, Subtarget, DAG, dl);
10569
10570   // Try to collapse shuffles into using a vector type with fewer elements but
10571   // wider element types. We cap this to not form integers or floating point
10572   // elements wider than 64 bits, but it might be interesting to form i128
10573   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10574   SmallVector<int, 16> WidenedMask;
10575   if (VT.getScalarSizeInBits() < 64 &&
10576       canWidenShuffleElements(Mask, WidenedMask)) {
10577     MVT NewEltVT = VT.isFloatingPoint()
10578                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10579                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10580     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10581     // Make sure that the new vector type is legal. For example, v2f64 isn't
10582     // legal on SSE1.
10583     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10584       V1 = DAG.getBitcast(NewVT, V1);
10585       V2 = DAG.getBitcast(NewVT, V2);
10586       return DAG.getBitcast(
10587           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10588     }
10589   }
10590
10591   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10592   for (int M : SVOp->getMask())
10593     if (M < 0)
10594       ++NumUndefElements;
10595     else if (M < NumElements)
10596       ++NumV1Elements;
10597     else
10598       ++NumV2Elements;
10599
10600   // Commute the shuffle as needed such that more elements come from V1 than
10601   // V2. This allows us to match the shuffle pattern strictly on how many
10602   // elements come from V1 without handling the symmetric cases.
10603   if (NumV2Elements > NumV1Elements)
10604     return DAG.getCommutedVectorShuffle(*SVOp);
10605
10606   // When the number of V1 and V2 elements are the same, try to minimize the
10607   // number of uses of V2 in the low half of the vector. When that is tied,
10608   // ensure that the sum of indices for V1 is equal to or lower than the sum
10609   // indices for V2. When those are equal, try to ensure that the number of odd
10610   // indices for V1 is lower than the number of odd indices for V2.
10611   if (NumV1Elements == NumV2Elements) {
10612     int LowV1Elements = 0, LowV2Elements = 0;
10613     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10614       if (M >= NumElements)
10615         ++LowV2Elements;
10616       else if (M >= 0)
10617         ++LowV1Elements;
10618     if (LowV2Elements > LowV1Elements) {
10619       return DAG.getCommutedVectorShuffle(*SVOp);
10620     } else if (LowV2Elements == LowV1Elements) {
10621       int SumV1Indices = 0, SumV2Indices = 0;
10622       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10623         if (SVOp->getMask()[i] >= NumElements)
10624           SumV2Indices += i;
10625         else if (SVOp->getMask()[i] >= 0)
10626           SumV1Indices += i;
10627       if (SumV2Indices < SumV1Indices) {
10628         return DAG.getCommutedVectorShuffle(*SVOp);
10629       } else if (SumV2Indices == SumV1Indices) {
10630         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10631         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10632           if (SVOp->getMask()[i] >= NumElements)
10633             NumV2OddIndices += i % 2;
10634           else if (SVOp->getMask()[i] >= 0)
10635             NumV1OddIndices += i % 2;
10636         if (NumV2OddIndices < NumV1OddIndices)
10637           return DAG.getCommutedVectorShuffle(*SVOp);
10638       }
10639     }
10640   }
10641
10642   // For each vector width, delegate to a specialized lowering routine.
10643   if (VT.getSizeInBits() == 128)
10644     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10645
10646   if (VT.getSizeInBits() == 256)
10647     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10648
10649   // Force AVX-512 vectors to be scalarized for now.
10650   // FIXME: Implement AVX-512 support!
10651   if (VT.getSizeInBits() == 512)
10652     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10653
10654   llvm_unreachable("Unimplemented!");
10655 }
10656
10657 // This function assumes its argument is a BUILD_VECTOR of constants or
10658 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10659 // true.
10660 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10661                                     unsigned &MaskValue) {
10662   MaskValue = 0;
10663   unsigned NumElems = BuildVector->getNumOperands();
10664   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10665   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10666   unsigned NumElemsInLane = NumElems / NumLanes;
10667
10668   // Blend for v16i16 should be symetric for the both lanes.
10669   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10670     SDValue EltCond = BuildVector->getOperand(i);
10671     SDValue SndLaneEltCond =
10672         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10673
10674     int Lane1Cond = -1, Lane2Cond = -1;
10675     if (isa<ConstantSDNode>(EltCond))
10676       Lane1Cond = !isZero(EltCond);
10677     if (isa<ConstantSDNode>(SndLaneEltCond))
10678       Lane2Cond = !isZero(SndLaneEltCond);
10679
10680     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10681       // Lane1Cond != 0, means we want the first argument.
10682       // Lane1Cond == 0, means we want the second argument.
10683       // The encoding of this argument is 0 for the first argument, 1
10684       // for the second. Therefore, invert the condition.
10685       MaskValue |= !Lane1Cond << i;
10686     else if (Lane1Cond < 0)
10687       MaskValue |= !Lane2Cond << i;
10688     else
10689       return false;
10690   }
10691   return true;
10692 }
10693
10694 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10695 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10696                                            const X86Subtarget *Subtarget,
10697                                            SelectionDAG &DAG) {
10698   SDValue Cond = Op.getOperand(0);
10699   SDValue LHS = Op.getOperand(1);
10700   SDValue RHS = Op.getOperand(2);
10701   SDLoc dl(Op);
10702   MVT VT = Op.getSimpleValueType();
10703
10704   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10705     return SDValue();
10706   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10707
10708   // Only non-legal VSELECTs reach this lowering, convert those into generic
10709   // shuffles and re-use the shuffle lowering path for blends.
10710   SmallVector<int, 32> Mask;
10711   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10712     SDValue CondElt = CondBV->getOperand(i);
10713     Mask.push_back(
10714         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10715   }
10716   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10717 }
10718
10719 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10720   // A vselect where all conditions and data are constants can be optimized into
10721   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10722   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10723       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10724       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10725     return SDValue();
10726
10727   // Try to lower this to a blend-style vector shuffle. This can handle all
10728   // constant condition cases.
10729   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10730     return BlendOp;
10731
10732   // Variable blends are only legal from SSE4.1 onward.
10733   if (!Subtarget->hasSSE41())
10734     return SDValue();
10735
10736   // Only some types will be legal on some subtargets. If we can emit a legal
10737   // VSELECT-matching blend, return Op, and but if we need to expand, return
10738   // a null value.
10739   switch (Op.getSimpleValueType().SimpleTy) {
10740   default:
10741     // Most of the vector types have blends past SSE4.1.
10742     return Op;
10743
10744   case MVT::v32i8:
10745     // The byte blends for AVX vectors were introduced only in AVX2.
10746     if (Subtarget->hasAVX2())
10747       return Op;
10748
10749     return SDValue();
10750
10751   case MVT::v8i16:
10752   case MVT::v16i16:
10753     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10754     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10755       return Op;
10756
10757     // FIXME: We should custom lower this by fixing the condition and using i8
10758     // blends.
10759     return SDValue();
10760   }
10761 }
10762
10763 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10764   MVT VT = Op.getSimpleValueType();
10765   SDLoc dl(Op);
10766
10767   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10768     return SDValue();
10769
10770   if (VT.getSizeInBits() == 8) {
10771     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10772                                   Op.getOperand(0), Op.getOperand(1));
10773     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10774                                   DAG.getValueType(VT));
10775     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10776   }
10777
10778   if (VT.getSizeInBits() == 16) {
10779     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10780     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10781     if (Idx == 0)
10782       return DAG.getNode(
10783           ISD::TRUNCATE, dl, MVT::i16,
10784           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10785                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10786                       Op.getOperand(1)));
10787     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10788                                   Op.getOperand(0), Op.getOperand(1));
10789     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10790                                   DAG.getValueType(VT));
10791     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10792   }
10793
10794   if (VT == MVT::f32) {
10795     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10796     // the result back to FR32 register. It's only worth matching if the
10797     // result has a single use which is a store or a bitcast to i32.  And in
10798     // the case of a store, it's not worth it if the index is a constant 0,
10799     // because a MOVSSmr can be used instead, which is smaller and faster.
10800     if (!Op.hasOneUse())
10801       return SDValue();
10802     SDNode *User = *Op.getNode()->use_begin();
10803     if ((User->getOpcode() != ISD::STORE ||
10804          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10805           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10806         (User->getOpcode() != ISD::BITCAST ||
10807          User->getValueType(0) != MVT::i32))
10808       return SDValue();
10809     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10810                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10811                                   Op.getOperand(1));
10812     return DAG.getBitcast(MVT::f32, Extract);
10813   }
10814
10815   if (VT == MVT::i32 || VT == MVT::i64) {
10816     // ExtractPS/pextrq works with constant index.
10817     if (isa<ConstantSDNode>(Op.getOperand(1)))
10818       return Op;
10819   }
10820   return SDValue();
10821 }
10822
10823 /// Extract one bit from mask vector, like v16i1 or v8i1.
10824 /// AVX-512 feature.
10825 SDValue
10826 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10827   SDValue Vec = Op.getOperand(0);
10828   SDLoc dl(Vec);
10829   MVT VecVT = Vec.getSimpleValueType();
10830   SDValue Idx = Op.getOperand(1);
10831   MVT EltVT = Op.getSimpleValueType();
10832
10833   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10834   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10835          "Unexpected vector type in ExtractBitFromMaskVector");
10836
10837   // variable index can't be handled in mask registers,
10838   // extend vector to VR512
10839   if (!isa<ConstantSDNode>(Idx)) {
10840     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10841     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10842     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10843                               ExtVT.getVectorElementType(), Ext, Idx);
10844     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10845   }
10846
10847   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10848   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10849   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10850     rc = getRegClassFor(MVT::v16i1);
10851   unsigned MaxSift = rc->getSize()*8 - 1;
10852   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10853                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10854   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10855                     DAG.getConstant(MaxSift, dl, MVT::i8));
10856   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10857                        DAG.getIntPtrConstant(0, dl));
10858 }
10859
10860 SDValue
10861 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10862                                            SelectionDAG &DAG) const {
10863   SDLoc dl(Op);
10864   SDValue Vec = Op.getOperand(0);
10865   MVT VecVT = Vec.getSimpleValueType();
10866   SDValue Idx = Op.getOperand(1);
10867
10868   if (Op.getSimpleValueType() == MVT::i1)
10869     return ExtractBitFromMaskVector(Op, DAG);
10870
10871   if (!isa<ConstantSDNode>(Idx)) {
10872     if (VecVT.is512BitVector() ||
10873         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10874          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10875
10876       MVT MaskEltVT =
10877         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10878       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10879                                     MaskEltVT.getSizeInBits());
10880
10881       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10882       auto PtrVT = getPointerTy(DAG.getDataLayout());
10883       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10884                                  getZeroVector(MaskVT, Subtarget, DAG, dl), Idx,
10885                                  DAG.getConstant(0, dl, PtrVT));
10886       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10887       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Perm,
10888                          DAG.getConstant(0, dl, PtrVT));
10889     }
10890     return SDValue();
10891   }
10892
10893   // If this is a 256-bit vector result, first extract the 128-bit vector and
10894   // then extract the element from the 128-bit vector.
10895   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10896
10897     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10898     // Get the 128-bit vector.
10899     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10900     MVT EltVT = VecVT.getVectorElementType();
10901
10902     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10903
10904     //if (IdxVal >= NumElems/2)
10905     //  IdxVal -= NumElems/2;
10906     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10907     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10908                        DAG.getConstant(IdxVal, dl, MVT::i32));
10909   }
10910
10911   assert(VecVT.is128BitVector() && "Unexpected vector length");
10912
10913   if (Subtarget->hasSSE41())
10914     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10915       return Res;
10916
10917   MVT VT = Op.getSimpleValueType();
10918   // TODO: handle v16i8.
10919   if (VT.getSizeInBits() == 16) {
10920     SDValue Vec = Op.getOperand(0);
10921     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10922     if (Idx == 0)
10923       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10924                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10925                                      DAG.getBitcast(MVT::v4i32, Vec),
10926                                      Op.getOperand(1)));
10927     // Transform it so it match pextrw which produces a 32-bit result.
10928     MVT EltVT = MVT::i32;
10929     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10930                                   Op.getOperand(0), Op.getOperand(1));
10931     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10932                                   DAG.getValueType(VT));
10933     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10934   }
10935
10936   if (VT.getSizeInBits() == 32) {
10937     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10938     if (Idx == 0)
10939       return Op;
10940
10941     // SHUFPS the element to the lowest double word, then movss.
10942     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10943     MVT VVT = Op.getOperand(0).getSimpleValueType();
10944     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10945                                        DAG.getUNDEF(VVT), Mask);
10946     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10947                        DAG.getIntPtrConstant(0, dl));
10948   }
10949
10950   if (VT.getSizeInBits() == 64) {
10951     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10952     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10953     //        to match extract_elt for f64.
10954     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10955     if (Idx == 0)
10956       return Op;
10957
10958     // UNPCKHPD the element to the lowest double word, then movsd.
10959     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10960     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10961     int Mask[2] = { 1, -1 };
10962     MVT VVT = Op.getOperand(0).getSimpleValueType();
10963     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10964                                        DAG.getUNDEF(VVT), Mask);
10965     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10966                        DAG.getIntPtrConstant(0, dl));
10967   }
10968
10969   return SDValue();
10970 }
10971
10972 /// Insert one bit to mask vector, like v16i1 or v8i1.
10973 /// AVX-512 feature.
10974 SDValue
10975 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10976   SDLoc dl(Op);
10977   SDValue Vec = Op.getOperand(0);
10978   SDValue Elt = Op.getOperand(1);
10979   SDValue Idx = Op.getOperand(2);
10980   MVT VecVT = Vec.getSimpleValueType();
10981
10982   if (!isa<ConstantSDNode>(Idx)) {
10983     // Non constant index. Extend source and destination,
10984     // insert element and then truncate the result.
10985     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10986     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10987     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10988       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10989       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10990     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10991   }
10992
10993   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10994   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10995   if (IdxVal)
10996     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10997                            DAG.getConstant(IdxVal, dl, MVT::i8));
10998   if (Vec.getOpcode() == ISD::UNDEF)
10999     return EltInVec;
11000   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
11001 }
11002
11003 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
11004                                                   SelectionDAG &DAG) const {
11005   MVT VT = Op.getSimpleValueType();
11006   MVT EltVT = VT.getVectorElementType();
11007
11008   if (EltVT == MVT::i1)
11009     return InsertBitToMaskVector(Op, DAG);
11010
11011   SDLoc dl(Op);
11012   SDValue N0 = Op.getOperand(0);
11013   SDValue N1 = Op.getOperand(1);
11014   SDValue N2 = Op.getOperand(2);
11015   if (!isa<ConstantSDNode>(N2))
11016     return SDValue();
11017   auto *N2C = cast<ConstantSDNode>(N2);
11018   unsigned IdxVal = N2C->getZExtValue();
11019
11020   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
11021   // into that, and then insert the subvector back into the result.
11022   if (VT.is256BitVector() || VT.is512BitVector()) {
11023     // With a 256-bit vector, we can insert into the zero element efficiently
11024     // using a blend if we have AVX or AVX2 and the right data type.
11025     if (VT.is256BitVector() && IdxVal == 0) {
11026       // TODO: It is worthwhile to cast integer to floating point and back
11027       // and incur a domain crossing penalty if that's what we'll end up
11028       // doing anyway after extracting to a 128-bit vector.
11029       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
11030           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
11031         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
11032         N2 = DAG.getIntPtrConstant(1, dl);
11033         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
11034       }
11035     }
11036
11037     // Get the desired 128-bit vector chunk.
11038     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
11039
11040     // Insert the element into the desired chunk.
11041     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
11042     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
11043
11044     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
11045                     DAG.getConstant(IdxIn128, dl, MVT::i32));
11046
11047     // Insert the changed part back into the bigger vector
11048     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
11049   }
11050   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
11051
11052   if (Subtarget->hasSSE41()) {
11053     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
11054       unsigned Opc;
11055       if (VT == MVT::v8i16) {
11056         Opc = X86ISD::PINSRW;
11057       } else {
11058         assert(VT == MVT::v16i8);
11059         Opc = X86ISD::PINSRB;
11060       }
11061
11062       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
11063       // argument.
11064       if (N1.getValueType() != MVT::i32)
11065         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11066       if (N2.getValueType() != MVT::i32)
11067         N2 = DAG.getIntPtrConstant(IdxVal, dl);
11068       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
11069     }
11070
11071     if (EltVT == MVT::f32) {
11072       // Bits [7:6] of the constant are the source select. This will always be
11073       //   zero here. The DAG Combiner may combine an extract_elt index into
11074       //   these bits. For example (insert (extract, 3), 2) could be matched by
11075       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
11076       // Bits [5:4] of the constant are the destination select. This is the
11077       //   value of the incoming immediate.
11078       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
11079       //   combine either bitwise AND or insert of float 0.0 to set these bits.
11080
11081       const Function *F = DAG.getMachineFunction().getFunction();
11082       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
11083       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
11084         // If this is an insertion of 32-bits into the low 32-bits of
11085         // a vector, we prefer to generate a blend with immediate rather
11086         // than an insertps. Blends are simpler operations in hardware and so
11087         // will always have equal or better performance than insertps.
11088         // But if optimizing for size and there's a load folding opportunity,
11089         // generate insertps because blendps does not have a 32-bit memory
11090         // operand form.
11091         N2 = DAG.getIntPtrConstant(1, dl);
11092         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11093         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
11094       }
11095       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
11096       // Create this as a scalar to vector..
11097       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
11098       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
11099     }
11100
11101     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
11102       // PINSR* works with constant index.
11103       return Op;
11104     }
11105   }
11106
11107   if (EltVT == MVT::i8)
11108     return SDValue();
11109
11110   if (EltVT.getSizeInBits() == 16) {
11111     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
11112     // as its second argument.
11113     if (N1.getValueType() != MVT::i32)
11114       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
11115     if (N2.getValueType() != MVT::i32)
11116       N2 = DAG.getIntPtrConstant(IdxVal, dl);
11117     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
11118   }
11119   return SDValue();
11120 }
11121
11122 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
11123   SDLoc dl(Op);
11124   MVT OpVT = Op.getSimpleValueType();
11125
11126   // If this is a 256-bit vector result, first insert into a 128-bit
11127   // vector and then insert into the 256-bit vector.
11128   if (!OpVT.is128BitVector()) {
11129     // Insert into a 128-bit vector.
11130     unsigned SizeFactor = OpVT.getSizeInBits()/128;
11131     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
11132                                  OpVT.getVectorNumElements() / SizeFactor);
11133
11134     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
11135
11136     // Insert the 128-bit vector.
11137     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
11138   }
11139
11140   if (OpVT == MVT::v1i64 &&
11141       Op.getOperand(0).getValueType() == MVT::i64)
11142     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
11143
11144   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
11145   assert(OpVT.is128BitVector() && "Expected an SSE type!");
11146   return DAG.getBitcast(
11147       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
11148 }
11149
11150 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
11151 // a simple subregister reference or explicit instructions to grab
11152 // upper bits of a vector.
11153 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11154                                       SelectionDAG &DAG) {
11155   SDLoc dl(Op);
11156   SDValue In =  Op.getOperand(0);
11157   SDValue Idx = Op.getOperand(1);
11158   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11159   MVT ResVT   = Op.getSimpleValueType();
11160   MVT InVT    = In.getSimpleValueType();
11161
11162   if (Subtarget->hasFp256()) {
11163     if (ResVT.is128BitVector() &&
11164         (InVT.is256BitVector() || InVT.is512BitVector()) &&
11165         isa<ConstantSDNode>(Idx)) {
11166       return Extract128BitVector(In, IdxVal, DAG, dl);
11167     }
11168     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
11169         isa<ConstantSDNode>(Idx)) {
11170       return Extract256BitVector(In, IdxVal, DAG, dl);
11171     }
11172   }
11173   return SDValue();
11174 }
11175
11176 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
11177 // simple superregister reference or explicit instructions to insert
11178 // the upper bits of a vector.
11179 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
11180                                      SelectionDAG &DAG) {
11181   if (!Subtarget->hasAVX())
11182     return SDValue();
11183
11184   SDLoc dl(Op);
11185   SDValue Vec = Op.getOperand(0);
11186   SDValue SubVec = Op.getOperand(1);
11187   SDValue Idx = Op.getOperand(2);
11188
11189   if (!isa<ConstantSDNode>(Idx))
11190     return SDValue();
11191
11192   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
11193   MVT OpVT = Op.getSimpleValueType();
11194   MVT SubVecVT = SubVec.getSimpleValueType();
11195
11196   // Fold two 16-byte subvector loads into one 32-byte load:
11197   // (insert_subvector (insert_subvector undef, (load addr), 0),
11198   //                   (load addr + 16), Elts/2)
11199   // --> load32 addr
11200   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
11201       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
11202       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
11203       !Subtarget->isUnalignedMem32Slow()) {
11204     SDValue SubVec2 = Vec.getOperand(1);
11205     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
11206       if (Idx2->getZExtValue() == 0) {
11207         SDValue Ops[] = { SubVec2, SubVec };
11208         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
11209           return Ld;
11210       }
11211     }
11212   }
11213
11214   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11215       SubVecVT.is128BitVector())
11216     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11217
11218   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11219     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11220
11221   if (OpVT.getVectorElementType() == MVT::i1) {
11222     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11223       return Op;
11224     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11225     SDValue Undef = DAG.getUNDEF(OpVT);
11226     unsigned NumElems = OpVT.getVectorNumElements();
11227     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11228
11229     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11230       // Zero upper bits of the Vec
11231       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11232       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11233
11234       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11235                                  SubVec, ZeroIdx);
11236       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11237       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11238     }
11239     if (IdxVal == 0) {
11240       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11241                                  SubVec, ZeroIdx);
11242       // Zero upper bits of the Vec2
11243       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11244       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11245       // Zero lower bits of the Vec
11246       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11247       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11248       // Merge them together
11249       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11250     }
11251   }
11252   return SDValue();
11253 }
11254
11255 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11256 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11257 // one of the above mentioned nodes. It has to be wrapped because otherwise
11258 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11259 // be used to form addressing mode. These wrapped nodes will be selected
11260 // into MOV32ri.
11261 SDValue
11262 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11263   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11264
11265   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11266   // global base reg.
11267   unsigned char OpFlag = 0;
11268   unsigned WrapperKind = X86ISD::Wrapper;
11269   CodeModel::Model M = DAG.getTarget().getCodeModel();
11270
11271   if (Subtarget->isPICStyleRIPRel() &&
11272       (M == CodeModel::Small || M == CodeModel::Kernel))
11273     WrapperKind = X86ISD::WrapperRIP;
11274   else if (Subtarget->isPICStyleGOT())
11275     OpFlag = X86II::MO_GOTOFF;
11276   else if (Subtarget->isPICStyleStubPIC())
11277     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11278
11279   auto PtrVT = getPointerTy(DAG.getDataLayout());
11280   SDValue Result = DAG.getTargetConstantPool(
11281       CP->getConstVal(), PtrVT, CP->getAlignment(), CP->getOffset(), OpFlag);
11282   SDLoc DL(CP);
11283   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11284   // With PIC, the address is actually $g + Offset.
11285   if (OpFlag) {
11286     Result =
11287         DAG.getNode(ISD::ADD, DL, PtrVT,
11288                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11289   }
11290
11291   return Result;
11292 }
11293
11294 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11295   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11296
11297   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11298   // global base reg.
11299   unsigned char OpFlag = 0;
11300   unsigned WrapperKind = X86ISD::Wrapper;
11301   CodeModel::Model M = DAG.getTarget().getCodeModel();
11302
11303   if (Subtarget->isPICStyleRIPRel() &&
11304       (M == CodeModel::Small || M == CodeModel::Kernel))
11305     WrapperKind = X86ISD::WrapperRIP;
11306   else if (Subtarget->isPICStyleGOT())
11307     OpFlag = X86II::MO_GOTOFF;
11308   else if (Subtarget->isPICStyleStubPIC())
11309     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11310
11311   auto PtrVT = getPointerTy(DAG.getDataLayout());
11312   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OpFlag);
11313   SDLoc DL(JT);
11314   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11315
11316   // With PIC, the address is actually $g + Offset.
11317   if (OpFlag)
11318     Result =
11319         DAG.getNode(ISD::ADD, DL, PtrVT,
11320                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11321
11322   return Result;
11323 }
11324
11325 SDValue
11326 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11327   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11328
11329   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11330   // global base reg.
11331   unsigned char OpFlag = 0;
11332   unsigned WrapperKind = X86ISD::Wrapper;
11333   CodeModel::Model M = DAG.getTarget().getCodeModel();
11334
11335   if (Subtarget->isPICStyleRIPRel() &&
11336       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11337     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11338       OpFlag = X86II::MO_GOTPCREL;
11339     WrapperKind = X86ISD::WrapperRIP;
11340   } else if (Subtarget->isPICStyleGOT()) {
11341     OpFlag = X86II::MO_GOT;
11342   } else if (Subtarget->isPICStyleStubPIC()) {
11343     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11344   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11345     OpFlag = X86II::MO_DARWIN_NONLAZY;
11346   }
11347
11348   auto PtrVT = getPointerTy(DAG.getDataLayout());
11349   SDValue Result = DAG.getTargetExternalSymbol(Sym, PtrVT, OpFlag);
11350
11351   SDLoc DL(Op);
11352   Result = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11353
11354   // With PIC, the address is actually $g + Offset.
11355   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11356       !Subtarget->is64Bit()) {
11357     Result =
11358         DAG.getNode(ISD::ADD, DL, PtrVT,
11359                     DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), Result);
11360   }
11361
11362   // For symbols that require a load from a stub to get the address, emit the
11363   // load.
11364   if (isGlobalStubReference(OpFlag))
11365     Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
11366                          MachinePointerInfo::getGOT(), false, false, false, 0);
11367
11368   return Result;
11369 }
11370
11371 SDValue
11372 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11373   // Create the TargetBlockAddressAddress node.
11374   unsigned char OpFlags =
11375     Subtarget->ClassifyBlockAddressReference();
11376   CodeModel::Model M = DAG.getTarget().getCodeModel();
11377   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11378   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11379   SDLoc dl(Op);
11380   auto PtrVT = getPointerTy(DAG.getDataLayout());
11381   SDValue Result = DAG.getTargetBlockAddress(BA, PtrVT, Offset, OpFlags);
11382
11383   if (Subtarget->isPICStyleRIPRel() &&
11384       (M == CodeModel::Small || M == CodeModel::Kernel))
11385     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11386   else
11387     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11388
11389   // With PIC, the address is actually $g + Offset.
11390   if (isGlobalRelativeToPICBase(OpFlags)) {
11391     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11392                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11393   }
11394
11395   return Result;
11396 }
11397
11398 SDValue
11399 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11400                                       int64_t Offset, SelectionDAG &DAG) const {
11401   // Create the TargetGlobalAddress node, folding in the constant
11402   // offset if it is legal.
11403   unsigned char OpFlags =
11404       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11405   CodeModel::Model M = DAG.getTarget().getCodeModel();
11406   auto PtrVT = getPointerTy(DAG.getDataLayout());
11407   SDValue Result;
11408   if (OpFlags == X86II::MO_NO_FLAG &&
11409       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11410     // A direct static reference to a global.
11411     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, Offset);
11412     Offset = 0;
11413   } else {
11414     Result = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, OpFlags);
11415   }
11416
11417   if (Subtarget->isPICStyleRIPRel() &&
11418       (M == CodeModel::Small || M == CodeModel::Kernel))
11419     Result = DAG.getNode(X86ISD::WrapperRIP, dl, PtrVT, Result);
11420   else
11421     Result = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, Result);
11422
11423   // With PIC, the address is actually $g + Offset.
11424   if (isGlobalRelativeToPICBase(OpFlags)) {
11425     Result = DAG.getNode(ISD::ADD, dl, PtrVT,
11426                          DAG.getNode(X86ISD::GlobalBaseReg, dl, PtrVT), Result);
11427   }
11428
11429   // For globals that require a load from a stub to get the address, emit the
11430   // load.
11431   if (isGlobalStubReference(OpFlags))
11432     Result = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Result,
11433                          MachinePointerInfo::getGOT(), false, false, false, 0);
11434
11435   // If there was a non-zero offset that we didn't fold, create an explicit
11436   // addition for it.
11437   if (Offset != 0)
11438     Result = DAG.getNode(ISD::ADD, dl, PtrVT, Result,
11439                          DAG.getConstant(Offset, dl, PtrVT));
11440
11441   return Result;
11442 }
11443
11444 SDValue
11445 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11446   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11447   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11448   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11449 }
11450
11451 static SDValue
11452 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11453            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11454            unsigned char OperandFlags, bool LocalDynamic = false) {
11455   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11456   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11457   SDLoc dl(GA);
11458   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11459                                            GA->getValueType(0),
11460                                            GA->getOffset(),
11461                                            OperandFlags);
11462
11463   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11464                                            : X86ISD::TLSADDR;
11465
11466   if (InFlag) {
11467     SDValue Ops[] = { Chain,  TGA, *InFlag };
11468     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11469   } else {
11470     SDValue Ops[]  = { Chain, TGA };
11471     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11472   }
11473
11474   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11475   MFI->setAdjustsStack(true);
11476   MFI->setHasCalls(true);
11477
11478   SDValue Flag = Chain.getValue(1);
11479   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11480 }
11481
11482 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11483 static SDValue
11484 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11485                                 const EVT PtrVT) {
11486   SDValue InFlag;
11487   SDLoc dl(GA);  // ? function entry point might be better
11488   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11489                                    DAG.getNode(X86ISD::GlobalBaseReg,
11490                                                SDLoc(), PtrVT), InFlag);
11491   InFlag = Chain.getValue(1);
11492
11493   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11494 }
11495
11496 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11497 static SDValue
11498 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11499                                 const EVT PtrVT) {
11500   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11501                     X86::RAX, X86II::MO_TLSGD);
11502 }
11503
11504 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11505                                            SelectionDAG &DAG,
11506                                            const EVT PtrVT,
11507                                            bool is64Bit) {
11508   SDLoc dl(GA);
11509
11510   // Get the start address of the TLS block for this module.
11511   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11512       .getInfo<X86MachineFunctionInfo>();
11513   MFI->incNumLocalDynamicTLSAccesses();
11514
11515   SDValue Base;
11516   if (is64Bit) {
11517     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11518                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11519   } else {
11520     SDValue InFlag;
11521     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11522         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11523     InFlag = Chain.getValue(1);
11524     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11525                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11526   }
11527
11528   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11529   // of Base.
11530
11531   // Build x@dtpoff.
11532   unsigned char OperandFlags = X86II::MO_DTPOFF;
11533   unsigned WrapperKind = X86ISD::Wrapper;
11534   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11535                                            GA->getValueType(0),
11536                                            GA->getOffset(), OperandFlags);
11537   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11538
11539   // Add x@dtpoff with the base.
11540   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11541 }
11542
11543 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11544 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11545                                    const EVT PtrVT, TLSModel::Model model,
11546                                    bool is64Bit, bool isPIC) {
11547   SDLoc dl(GA);
11548
11549   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11550   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11551                                                          is64Bit ? 257 : 256));
11552
11553   SDValue ThreadPointer =
11554       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11555                   MachinePointerInfo(Ptr), false, false, false, 0);
11556
11557   unsigned char OperandFlags = 0;
11558   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11559   // initialexec.
11560   unsigned WrapperKind = X86ISD::Wrapper;
11561   if (model == TLSModel::LocalExec) {
11562     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11563   } else if (model == TLSModel::InitialExec) {
11564     if (is64Bit) {
11565       OperandFlags = X86II::MO_GOTTPOFF;
11566       WrapperKind = X86ISD::WrapperRIP;
11567     } else {
11568       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11569     }
11570   } else {
11571     llvm_unreachable("Unexpected model");
11572   }
11573
11574   // emit "addl x@ntpoff,%eax" (local exec)
11575   // or "addl x@indntpoff,%eax" (initial exec)
11576   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11577   SDValue TGA =
11578       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11579                                  GA->getOffset(), OperandFlags);
11580   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11581
11582   if (model == TLSModel::InitialExec) {
11583     if (isPIC && !is64Bit) {
11584       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11585                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11586                            Offset);
11587     }
11588
11589     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11590                          MachinePointerInfo::getGOT(), false, false, false, 0);
11591   }
11592
11593   // The address of the thread local variable is the add of the thread
11594   // pointer with the offset of the variable.
11595   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11596 }
11597
11598 SDValue
11599 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11600
11601   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11602   const GlobalValue *GV = GA->getGlobal();
11603   auto PtrVT = getPointerTy(DAG.getDataLayout());
11604
11605   if (Subtarget->isTargetELF()) {
11606     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11607     switch (model) {
11608       case TLSModel::GeneralDynamic:
11609         if (Subtarget->is64Bit())
11610           return LowerToTLSGeneralDynamicModel64(GA, DAG, PtrVT);
11611         return LowerToTLSGeneralDynamicModel32(GA, DAG, PtrVT);
11612       case TLSModel::LocalDynamic:
11613         return LowerToTLSLocalDynamicModel(GA, DAG, PtrVT,
11614                                            Subtarget->is64Bit());
11615       case TLSModel::InitialExec:
11616       case TLSModel::LocalExec:
11617         return LowerToTLSExecModel(GA, DAG, PtrVT, model, Subtarget->is64Bit(),
11618                                    DAG.getTarget().getRelocationModel() ==
11619                                        Reloc::PIC_);
11620     }
11621     llvm_unreachable("Unknown TLS model.");
11622   }
11623
11624   if (Subtarget->isTargetDarwin()) {
11625     // Darwin only has one model of TLS.  Lower to that.
11626     unsigned char OpFlag = 0;
11627     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11628                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11629
11630     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11631     // global base reg.
11632     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11633                  !Subtarget->is64Bit();
11634     if (PIC32)
11635       OpFlag = X86II::MO_TLVP_PIC_BASE;
11636     else
11637       OpFlag = X86II::MO_TLVP;
11638     SDLoc DL(Op);
11639     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11640                                                 GA->getValueType(0),
11641                                                 GA->getOffset(), OpFlag);
11642     SDValue Offset = DAG.getNode(WrapperKind, DL, PtrVT, Result);
11643
11644     // With PIC32, the address is actually $g + Offset.
11645     if (PIC32)
11646       Offset = DAG.getNode(ISD::ADD, DL, PtrVT,
11647                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11648                            Offset);
11649
11650     // Lowering the machine isd will make sure everything is in the right
11651     // location.
11652     SDValue Chain = DAG.getEntryNode();
11653     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11654     SDValue Args[] = { Chain, Offset };
11655     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11656
11657     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11658     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11659     MFI->setAdjustsStack(true);
11660
11661     // And our return value (tls address) is in the standard call return value
11662     // location.
11663     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11664     return DAG.getCopyFromReg(Chain, DL, Reg, PtrVT, Chain.getValue(1));
11665   }
11666
11667   if (Subtarget->isTargetKnownWindowsMSVC() ||
11668       Subtarget->isTargetWindowsGNU()) {
11669     // Just use the implicit TLS architecture
11670     // Need to generate someting similar to:
11671     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11672     //                                  ; from TEB
11673     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11674     //   mov     rcx, qword [rdx+rcx*8]
11675     //   mov     eax, .tls$:tlsvar
11676     //   [rax+rcx] contains the address
11677     // Windows 64bit: gs:0x58
11678     // Windows 32bit: fs:__tls_array
11679
11680     SDLoc dl(GA);
11681     SDValue Chain = DAG.getEntryNode();
11682
11683     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11684     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11685     // use its literal value of 0x2C.
11686     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11687                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11688                                                              256)
11689                                         : Type::getInt32PtrTy(*DAG.getContext(),
11690                                                               257));
11691
11692     SDValue TlsArray = Subtarget->is64Bit()
11693                            ? DAG.getIntPtrConstant(0x58, dl)
11694                            : (Subtarget->isTargetWindowsGNU()
11695                                   ? DAG.getIntPtrConstant(0x2C, dl)
11696                                   : DAG.getExternalSymbol("_tls_array", PtrVT));
11697
11698     SDValue ThreadPointer =
11699         DAG.getLoad(PtrVT, dl, Chain, TlsArray, MachinePointerInfo(Ptr), false,
11700                     false, false, 0);
11701
11702     SDValue res;
11703     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11704       res = ThreadPointer;
11705     } else {
11706       // Load the _tls_index variable
11707       SDValue IDX = DAG.getExternalSymbol("_tls_index", PtrVT);
11708       if (Subtarget->is64Bit())
11709         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, PtrVT, Chain, IDX,
11710                              MachinePointerInfo(), MVT::i32, false, false,
11711                              false, 0);
11712       else
11713         IDX = DAG.getLoad(PtrVT, dl, Chain, IDX, MachinePointerInfo(), false,
11714                           false, false, 0);
11715
11716       auto &DL = DAG.getDataLayout();
11717       SDValue Scale =
11718           DAG.getConstant(Log2_64_Ceil(DL.getPointerSize()), dl, PtrVT);
11719       IDX = DAG.getNode(ISD::SHL, dl, PtrVT, IDX, Scale);
11720
11721       res = DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, IDX);
11722     }
11723
11724     res = DAG.getLoad(PtrVT, dl, Chain, res, MachinePointerInfo(), false, false,
11725                       false, 0);
11726
11727     // Get the offset of start of .tls section
11728     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11729                                              GA->getValueType(0),
11730                                              GA->getOffset(), X86II::MO_SECREL);
11731     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, PtrVT, TGA);
11732
11733     // The address of the thread local variable is the add of the thread
11734     // pointer with the offset of the variable.
11735     return DAG.getNode(ISD::ADD, dl, PtrVT, res, Offset);
11736   }
11737
11738   llvm_unreachable("TLS not implemented for this target.");
11739 }
11740
11741 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11742 /// and take a 2 x i32 value to shift plus a shift amount.
11743 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11744   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11745   MVT VT = Op.getSimpleValueType();
11746   unsigned VTBits = VT.getSizeInBits();
11747   SDLoc dl(Op);
11748   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11749   SDValue ShOpLo = Op.getOperand(0);
11750   SDValue ShOpHi = Op.getOperand(1);
11751   SDValue ShAmt  = Op.getOperand(2);
11752   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11753   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11754   // during isel.
11755   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11756                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11757   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11758                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11759                        : DAG.getConstant(0, dl, VT);
11760
11761   SDValue Tmp2, Tmp3;
11762   if (Op.getOpcode() == ISD::SHL_PARTS) {
11763     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11764     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11765   } else {
11766     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11767     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11768   }
11769
11770   // If the shift amount is larger or equal than the width of a part we can't
11771   // rely on the results of shld/shrd. Insert a test and select the appropriate
11772   // values for large shift amounts.
11773   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11774                                 DAG.getConstant(VTBits, dl, MVT::i8));
11775   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11776                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11777
11778   SDValue Hi, Lo;
11779   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11780   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11781   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11782
11783   if (Op.getOpcode() == ISD::SHL_PARTS) {
11784     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11785     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11786   } else {
11787     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11788     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11789   }
11790
11791   SDValue Ops[2] = { Lo, Hi };
11792   return DAG.getMergeValues(Ops, dl);
11793 }
11794
11795 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11796                                            SelectionDAG &DAG) const {
11797   SDValue Src = Op.getOperand(0);
11798   MVT SrcVT = Src.getSimpleValueType();
11799   MVT VT = Op.getSimpleValueType();
11800   SDLoc dl(Op);
11801
11802   if (SrcVT.isVector()) {
11803     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11804       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11805                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11806                          DAG.getUNDEF(SrcVT)));
11807     }
11808     if (SrcVT.getVectorElementType() == MVT::i1) {
11809       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11810       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11811                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11812     }
11813     return SDValue();
11814   }
11815
11816   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11817          "Unknown SINT_TO_FP to lower!");
11818
11819   // These are really Legal; return the operand so the caller accepts it as
11820   // Legal.
11821   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11822     return Op;
11823   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11824       Subtarget->is64Bit()) {
11825     return Op;
11826   }
11827
11828   unsigned Size = SrcVT.getSizeInBits()/8;
11829   MachineFunction &MF = DAG.getMachineFunction();
11830   auto PtrVT = getPointerTy(MF.getDataLayout());
11831   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11832   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11833   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11834                                StackSlot,
11835                                MachinePointerInfo::getFixedStack(SSFI),
11836                                false, false, 0);
11837   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11838 }
11839
11840 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11841                                      SDValue StackSlot,
11842                                      SelectionDAG &DAG) const {
11843   // Build the FILD
11844   SDLoc DL(Op);
11845   SDVTList Tys;
11846   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11847   if (useSSE)
11848     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11849   else
11850     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11851
11852   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11853
11854   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11855   MachineMemOperand *MMO;
11856   if (FI) {
11857     int SSFI = FI->getIndex();
11858     MMO =
11859       DAG.getMachineFunction()
11860       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11861                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11862   } else {
11863     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11864     StackSlot = StackSlot.getOperand(1);
11865   }
11866   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11867   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11868                                            X86ISD::FILD, DL,
11869                                            Tys, Ops, SrcVT, MMO);
11870
11871   if (useSSE) {
11872     Chain = Result.getValue(1);
11873     SDValue InFlag = Result.getValue(2);
11874
11875     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11876     // shouldn't be necessary except that RFP cannot be live across
11877     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11878     MachineFunction &MF = DAG.getMachineFunction();
11879     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11880     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11881     auto PtrVT = getPointerTy(MF.getDataLayout());
11882     SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
11883     Tys = DAG.getVTList(MVT::Other);
11884     SDValue Ops[] = {
11885       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11886     };
11887     MachineMemOperand *MMO =
11888       DAG.getMachineFunction()
11889       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11890                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11891
11892     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11893                                     Ops, Op.getValueType(), MMO);
11894     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11895                          MachinePointerInfo::getFixedStack(SSFI),
11896                          false, false, false, 0);
11897   }
11898
11899   return Result;
11900 }
11901
11902 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11903 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11904                                                SelectionDAG &DAG) const {
11905   // This algorithm is not obvious. Here it is what we're trying to output:
11906   /*
11907      movq       %rax,  %xmm0
11908      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11909      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11910      #ifdef __SSE3__
11911        haddpd   %xmm0, %xmm0
11912      #else
11913        pshufd   $0x4e, %xmm0, %xmm1
11914        addpd    %xmm1, %xmm0
11915      #endif
11916   */
11917
11918   SDLoc dl(Op);
11919   LLVMContext *Context = DAG.getContext();
11920
11921   // Build some magic constants.
11922   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11923   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11924   auto PtrVT = getPointerTy(DAG.getDataLayout());
11925   SDValue CPIdx0 = DAG.getConstantPool(C0, PtrVT, 16);
11926
11927   SmallVector<Constant*,2> CV1;
11928   CV1.push_back(
11929     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11930                                       APInt(64, 0x4330000000000000ULL))));
11931   CV1.push_back(
11932     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11933                                       APInt(64, 0x4530000000000000ULL))));
11934   Constant *C1 = ConstantVector::get(CV1);
11935   SDValue CPIdx1 = DAG.getConstantPool(C1, PtrVT, 16);
11936
11937   // Load the 64-bit value into an XMM register.
11938   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11939                             Op.getOperand(0));
11940   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11941                               MachinePointerInfo::getConstantPool(),
11942                               false, false, false, 16);
11943   SDValue Unpck1 =
11944       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11945
11946   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11947                               MachinePointerInfo::getConstantPool(),
11948                               false, false, false, 16);
11949   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11950   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11951   SDValue Result;
11952
11953   if (Subtarget->hasSSE3()) {
11954     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11955     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11956   } else {
11957     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11958     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11959                                            S2F, 0x4E, DAG);
11960     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11961                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11962   }
11963
11964   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11965                      DAG.getIntPtrConstant(0, dl));
11966 }
11967
11968 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11969 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11970                                                SelectionDAG &DAG) const {
11971   SDLoc dl(Op);
11972   // FP constant to bias correct the final result.
11973   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11974                                    MVT::f64);
11975
11976   // Load the 32-bit value into an XMM register.
11977   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11978                              Op.getOperand(0));
11979
11980   // Zero out the upper parts of the register.
11981   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11982
11983   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11984                      DAG.getBitcast(MVT::v2f64, Load),
11985                      DAG.getIntPtrConstant(0, dl));
11986
11987   // Or the load with the bias.
11988   SDValue Or = DAG.getNode(
11989       ISD::OR, dl, MVT::v2i64,
11990       DAG.getBitcast(MVT::v2i64,
11991                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11992       DAG.getBitcast(MVT::v2i64,
11993                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11994   Or =
11995       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11996                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11997
11998   // Subtract the bias.
11999   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
12000
12001   // Handle final rounding.
12002   EVT DestVT = Op.getValueType();
12003
12004   if (DestVT.bitsLT(MVT::f64))
12005     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
12006                        DAG.getIntPtrConstant(0, dl));
12007   if (DestVT.bitsGT(MVT::f64))
12008     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
12009
12010   // Handle final rounding.
12011   return Sub;
12012 }
12013
12014 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
12015                                      const X86Subtarget &Subtarget) {
12016   // The algorithm is the following:
12017   // #ifdef __SSE4_1__
12018   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12019   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12020   //                                 (uint4) 0x53000000, 0xaa);
12021   // #else
12022   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12023   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12024   // #endif
12025   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12026   //     return (float4) lo + fhi;
12027
12028   SDLoc DL(Op);
12029   SDValue V = Op->getOperand(0);
12030   EVT VecIntVT = V.getValueType();
12031   bool Is128 = VecIntVT == MVT::v4i32;
12032   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
12033   // If we convert to something else than the supported type, e.g., to v4f64,
12034   // abort early.
12035   if (VecFloatVT != Op->getValueType(0))
12036     return SDValue();
12037
12038   unsigned NumElts = VecIntVT.getVectorNumElements();
12039   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
12040          "Unsupported custom type");
12041   assert(NumElts <= 8 && "The size of the constant array must be fixed");
12042
12043   // In the #idef/#else code, we have in common:
12044   // - The vector of constants:
12045   // -- 0x4b000000
12046   // -- 0x53000000
12047   // - A shift:
12048   // -- v >> 16
12049
12050   // Create the splat vector for 0x4b000000.
12051   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
12052   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
12053                            CstLow, CstLow, CstLow, CstLow};
12054   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12055                                   makeArrayRef(&CstLowArray[0], NumElts));
12056   // Create the splat vector for 0x53000000.
12057   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
12058   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
12059                             CstHigh, CstHigh, CstHigh, CstHigh};
12060   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12061                                    makeArrayRef(&CstHighArray[0], NumElts));
12062
12063   // Create the right shift.
12064   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
12065   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
12066                              CstShift, CstShift, CstShift, CstShift};
12067   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
12068                                     makeArrayRef(&CstShiftArray[0], NumElts));
12069   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
12070
12071   SDValue Low, High;
12072   if (Subtarget.hasSSE41()) {
12073     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
12074     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
12075     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
12076     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
12077     // Low will be bitcasted right away, so do not bother bitcasting back to its
12078     // original type.
12079     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
12080                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12081     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
12082     //                                 (uint4) 0x53000000, 0xaa);
12083     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
12084     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
12085     // High will be bitcasted right away, so do not bother bitcasting back to
12086     // its original type.
12087     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
12088                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
12089   } else {
12090     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
12091     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
12092                                      CstMask, CstMask, CstMask);
12093     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
12094     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
12095     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
12096
12097     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
12098     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
12099   }
12100
12101   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
12102   SDValue CstFAdd = DAG.getConstantFP(
12103       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
12104   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
12105                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
12106   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
12107                                    makeArrayRef(&CstFAddArray[0], NumElts));
12108
12109   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
12110   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
12111   SDValue FHigh =
12112       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
12113   //     return (float4) lo + fhi;
12114   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
12115   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
12116 }
12117
12118 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
12119                                                SelectionDAG &DAG) const {
12120   SDValue N0 = Op.getOperand(0);
12121   MVT SVT = N0.getSimpleValueType();
12122   SDLoc dl(Op);
12123
12124   switch (SVT.SimpleTy) {
12125   default:
12126     llvm_unreachable("Custom UINT_TO_FP is not supported!");
12127   case MVT::v4i8:
12128   case MVT::v4i16:
12129   case MVT::v8i8:
12130   case MVT::v8i16: {
12131     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
12132     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
12133                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
12134   }
12135   case MVT::v4i32:
12136   case MVT::v8i32:
12137     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
12138   case MVT::v16i8:
12139   case MVT::v16i16:
12140     if (Subtarget->hasAVX512())
12141       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
12142                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
12143   }
12144   llvm_unreachable(nullptr);
12145 }
12146
12147 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
12148                                            SelectionDAG &DAG) const {
12149   SDValue N0 = Op.getOperand(0);
12150   SDLoc dl(Op);
12151   auto PtrVT = getPointerTy(DAG.getDataLayout());
12152
12153   if (Op.getValueType().isVector())
12154     return lowerUINT_TO_FP_vec(Op, DAG);
12155
12156   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
12157   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
12158   // the optimization here.
12159   if (DAG.SignBitIsZero(N0))
12160     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
12161
12162   MVT SrcVT = N0.getSimpleValueType();
12163   MVT DstVT = Op.getSimpleValueType();
12164   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
12165     return LowerUINT_TO_FP_i64(Op, DAG);
12166   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
12167     return LowerUINT_TO_FP_i32(Op, DAG);
12168   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
12169     return SDValue();
12170
12171   // Make a 64-bit buffer, and use it to build an FILD.
12172   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
12173   if (SrcVT == MVT::i32) {
12174     SDValue WordOff = DAG.getConstant(4, dl, PtrVT);
12175     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl, PtrVT, StackSlot, WordOff);
12176     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12177                                   StackSlot, MachinePointerInfo(),
12178                                   false, false, 0);
12179     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
12180                                   OffsetSlot, MachinePointerInfo(),
12181                                   false, false, 0);
12182     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
12183     return Fild;
12184   }
12185
12186   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
12187   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
12188                                StackSlot, MachinePointerInfo(),
12189                                false, false, 0);
12190   // For i64 source, we need to add the appropriate power of 2 if the input
12191   // was negative.  This is the same as the optimization in
12192   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
12193   // we must be careful to do the computation in x87 extended precision, not
12194   // in SSE. (The generic code can't know it's OK to do this, or how to.)
12195   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
12196   MachineMemOperand *MMO =
12197     DAG.getMachineFunction()
12198     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12199                           MachineMemOperand::MOLoad, 8, 8);
12200
12201   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
12202   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
12203   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
12204                                          MVT::i64, MMO);
12205
12206   APInt FF(32, 0x5F800000ULL);
12207
12208   // Check whether the sign bit is set.
12209   SDValue SignSet = DAG.getSetCC(
12210       dl, getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), MVT::i64),
12211       Op.getOperand(0), DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12212
12213   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12214   SDValue FudgePtr = DAG.getConstantPool(
12215       ConstantInt::get(*DAG.getContext(), FF.zext(64)), PtrVT);
12216
12217   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12218   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12219   SDValue Four = DAG.getIntPtrConstant(4, dl);
12220   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12221                                Zero, Four);
12222   FudgePtr = DAG.getNode(ISD::ADD, dl, PtrVT, FudgePtr, Offset);
12223
12224   // Load the value out, extending it from f32 to f80.
12225   // FIXME: Avoid the extend by constructing the right constant pool?
12226   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12227                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12228                                  MVT::f32, false, false, false, 4);
12229   // Extend everything to 80 bits to force it to be done on x87.
12230   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12231   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12232                      DAG.getIntPtrConstant(0, dl));
12233 }
12234
12235 std::pair<SDValue,SDValue>
12236 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12237                                     bool IsSigned, bool IsReplace) const {
12238   SDLoc DL(Op);
12239
12240   EVT DstTy = Op.getValueType();
12241   auto PtrVT = getPointerTy(DAG.getDataLayout());
12242
12243   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12244     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12245     DstTy = MVT::i64;
12246   }
12247
12248   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12249          DstTy.getSimpleVT() >= MVT::i16 &&
12250          "Unknown FP_TO_INT to lower!");
12251
12252   // These are really Legal.
12253   if (DstTy == MVT::i32 &&
12254       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12255     return std::make_pair(SDValue(), SDValue());
12256   if (Subtarget->is64Bit() &&
12257       DstTy == MVT::i64 &&
12258       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12259     return std::make_pair(SDValue(), SDValue());
12260
12261   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12262   // stack slot, or into the FTOL runtime function.
12263   MachineFunction &MF = DAG.getMachineFunction();
12264   unsigned MemSize = DstTy.getSizeInBits()/8;
12265   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12266   SDValue StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12267
12268   unsigned Opc;
12269   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12270     Opc = X86ISD::WIN_FTOL;
12271   else
12272     switch (DstTy.getSimpleVT().SimpleTy) {
12273     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12274     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12275     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12276     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12277     }
12278
12279   SDValue Chain = DAG.getEntryNode();
12280   SDValue Value = Op.getOperand(0);
12281   EVT TheVT = Op.getOperand(0).getValueType();
12282   // FIXME This causes a redundant load/store if the SSE-class value is already
12283   // in memory, such as if it is on the callstack.
12284   if (isScalarFPTypeInSSEReg(TheVT)) {
12285     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12286     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12287                          MachinePointerInfo::getFixedStack(SSFI),
12288                          false, false, 0);
12289     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12290     SDValue Ops[] = {
12291       Chain, StackSlot, DAG.getValueType(TheVT)
12292     };
12293
12294     MachineMemOperand *MMO =
12295       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12296                               MachineMemOperand::MOLoad, MemSize, MemSize);
12297     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12298     Chain = Value.getValue(1);
12299     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12300     StackSlot = DAG.getFrameIndex(SSFI, PtrVT);
12301   }
12302
12303   MachineMemOperand *MMO =
12304     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12305                             MachineMemOperand::MOStore, MemSize, MemSize);
12306
12307   if (Opc != X86ISD::WIN_FTOL) {
12308     // Build the FP_TO_INT*_IN_MEM
12309     SDValue Ops[] = { Chain, Value, StackSlot };
12310     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12311                                            Ops, DstTy, MMO);
12312     return std::make_pair(FIST, StackSlot);
12313   } else {
12314     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12315       DAG.getVTList(MVT::Other, MVT::Glue),
12316       Chain, Value);
12317     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12318       MVT::i32, ftol.getValue(1));
12319     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12320       MVT::i32, eax.getValue(2));
12321     SDValue Ops[] = { eax, edx };
12322     SDValue pair = IsReplace
12323       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12324       : DAG.getMergeValues(Ops, DL);
12325     return std::make_pair(pair, SDValue());
12326   }
12327 }
12328
12329 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12330                               const X86Subtarget *Subtarget) {
12331   MVT VT = Op->getSimpleValueType(0);
12332   SDValue In = Op->getOperand(0);
12333   MVT InVT = In.getSimpleValueType();
12334   SDLoc dl(Op);
12335
12336   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12337     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12338
12339   // Optimize vectors in AVX mode:
12340   //
12341   //   v8i16 -> v8i32
12342   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12343   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12344   //   Concat upper and lower parts.
12345   //
12346   //   v4i32 -> v4i64
12347   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12348   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12349   //   Concat upper and lower parts.
12350   //
12351
12352   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12353       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12354       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12355     return SDValue();
12356
12357   if (Subtarget->hasInt256())
12358     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12359
12360   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12361   SDValue Undef = DAG.getUNDEF(InVT);
12362   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12363   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12364   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12365
12366   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12367                              VT.getVectorNumElements()/2);
12368
12369   OpLo = DAG.getBitcast(HVT, OpLo);
12370   OpHi = DAG.getBitcast(HVT, OpHi);
12371
12372   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12373 }
12374
12375 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12376                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12377   MVT VT = Op->getSimpleValueType(0);
12378   SDValue In = Op->getOperand(0);
12379   MVT InVT = In.getSimpleValueType();
12380   SDLoc DL(Op);
12381   unsigned int NumElts = VT.getVectorNumElements();
12382   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12383     return SDValue();
12384
12385   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12386     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12387
12388   assert(InVT.getVectorElementType() == MVT::i1);
12389   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12390   SDValue One =
12391    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12392   SDValue Zero =
12393    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12394
12395   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12396   if (VT.is512BitVector())
12397     return V;
12398   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12399 }
12400
12401 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12402                                SelectionDAG &DAG) {
12403   if (Subtarget->hasFp256())
12404     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12405       return Res;
12406
12407   return SDValue();
12408 }
12409
12410 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12411                                 SelectionDAG &DAG) {
12412   SDLoc DL(Op);
12413   MVT VT = Op.getSimpleValueType();
12414   SDValue In = Op.getOperand(0);
12415   MVT SVT = In.getSimpleValueType();
12416
12417   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12418     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12419
12420   if (Subtarget->hasFp256())
12421     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12422       return Res;
12423
12424   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12425          VT.getVectorNumElements() != SVT.getVectorNumElements());
12426   return SDValue();
12427 }
12428
12429 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12430   SDLoc DL(Op);
12431   MVT VT = Op.getSimpleValueType();
12432   SDValue In = Op.getOperand(0);
12433   MVT InVT = In.getSimpleValueType();
12434
12435   if (VT == MVT::i1) {
12436     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12437            "Invalid scalar TRUNCATE operation");
12438     if (InVT.getSizeInBits() >= 32)
12439       return SDValue();
12440     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12441     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12442   }
12443   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12444          "Invalid TRUNCATE operation");
12445
12446   // move vector to mask - truncate solution for SKX
12447   if (VT.getVectorElementType() == MVT::i1) {
12448     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12449         Subtarget->hasBWI())
12450       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12451     if ((InVT.is256BitVector() || InVT.is128BitVector())
12452         && InVT.getScalarSizeInBits() <= 16 &&
12453         Subtarget->hasBWI() && Subtarget->hasVLX())
12454       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12455     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12456         Subtarget->hasDQI())
12457       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12458     if ((InVT.is256BitVector() || InVT.is128BitVector())
12459         && InVT.getScalarSizeInBits() >= 32 &&
12460         Subtarget->hasDQI() && Subtarget->hasVLX())
12461       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12462   }
12463   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12464     if (VT.getVectorElementType().getSizeInBits() >=8)
12465       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12466
12467     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12468     unsigned NumElts = InVT.getVectorNumElements();
12469     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12470     if (InVT.getSizeInBits() < 512) {
12471       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12472       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12473       InVT = ExtVT;
12474     }
12475
12476     SDValue OneV =
12477      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12478     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12479     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12480   }
12481
12482   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12483     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12484     if (Subtarget->hasInt256()) {
12485       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12486       In = DAG.getBitcast(MVT::v8i32, In);
12487       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12488                                 ShufMask);
12489       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12490                          DAG.getIntPtrConstant(0, DL));
12491     }
12492
12493     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12494                                DAG.getIntPtrConstant(0, DL));
12495     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12496                                DAG.getIntPtrConstant(2, DL));
12497     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12498     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12499     static const int ShufMask[] = {0, 2, 4, 6};
12500     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12501   }
12502
12503   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12504     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12505     if (Subtarget->hasInt256()) {
12506       In = DAG.getBitcast(MVT::v32i8, In);
12507
12508       SmallVector<SDValue,32> pshufbMask;
12509       for (unsigned i = 0; i < 2; ++i) {
12510         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12511         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12512         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12513         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12514         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12515         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12516         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12517         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12518         for (unsigned j = 0; j < 8; ++j)
12519           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12520       }
12521       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12522       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12523       In = DAG.getBitcast(MVT::v4i64, In);
12524
12525       static const int ShufMask[] = {0,  2,  -1,  -1};
12526       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12527                                 &ShufMask[0]);
12528       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12529                        DAG.getIntPtrConstant(0, DL));
12530       return DAG.getBitcast(VT, In);
12531     }
12532
12533     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12534                                DAG.getIntPtrConstant(0, DL));
12535
12536     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12537                                DAG.getIntPtrConstant(4, DL));
12538
12539     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12540     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12541
12542     // The PSHUFB mask:
12543     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12544                                    -1, -1, -1, -1, -1, -1, -1, -1};
12545
12546     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12547     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12548     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12549
12550     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12551     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12552
12553     // The MOVLHPS Mask:
12554     static const int ShufMask2[] = {0, 1, 4, 5};
12555     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12556     return DAG.getBitcast(MVT::v8i16, res);
12557   }
12558
12559   // Handle truncation of V256 to V128 using shuffles.
12560   if (!VT.is128BitVector() || !InVT.is256BitVector())
12561     return SDValue();
12562
12563   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12564
12565   unsigned NumElems = VT.getVectorNumElements();
12566   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12567
12568   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12569   // Prepare truncation shuffle mask
12570   for (unsigned i = 0; i != NumElems; ++i)
12571     MaskVec[i] = i * 2;
12572   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12573                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12574   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12575                      DAG.getIntPtrConstant(0, DL));
12576 }
12577
12578 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12579                                            SelectionDAG &DAG) const {
12580   assert(!Op.getSimpleValueType().isVector());
12581
12582   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12583     /*IsSigned=*/ true, /*IsReplace=*/ false);
12584   SDValue FIST = Vals.first, StackSlot = Vals.second;
12585   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12586   if (!FIST.getNode()) return Op;
12587
12588   if (StackSlot.getNode())
12589     // Load the result.
12590     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12591                        FIST, StackSlot, MachinePointerInfo(),
12592                        false, false, false, 0);
12593
12594   // The node is the result.
12595   return FIST;
12596 }
12597
12598 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12599                                            SelectionDAG &DAG) const {
12600   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12601     /*IsSigned=*/ false, /*IsReplace=*/ false);
12602   SDValue FIST = Vals.first, StackSlot = Vals.second;
12603   assert(FIST.getNode() && "Unexpected failure");
12604
12605   if (StackSlot.getNode())
12606     // Load the result.
12607     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12608                        FIST, StackSlot, MachinePointerInfo(),
12609                        false, false, false, 0);
12610
12611   // The node is the result.
12612   return FIST;
12613 }
12614
12615 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12616   SDLoc DL(Op);
12617   MVT VT = Op.getSimpleValueType();
12618   SDValue In = Op.getOperand(0);
12619   MVT SVT = In.getSimpleValueType();
12620
12621   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12622
12623   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12624                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12625                                  In, DAG.getUNDEF(SVT)));
12626 }
12627
12628 /// The only differences between FABS and FNEG are the mask and the logic op.
12629 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12630 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12631   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12632          "Wrong opcode for lowering FABS or FNEG.");
12633
12634   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12635
12636   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12637   // into an FNABS. We'll lower the FABS after that if it is still in use.
12638   if (IsFABS)
12639     for (SDNode *User : Op->uses())
12640       if (User->getOpcode() == ISD::FNEG)
12641         return Op;
12642
12643   SDValue Op0 = Op.getOperand(0);
12644   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12645
12646   SDLoc dl(Op);
12647   MVT VT = Op.getSimpleValueType();
12648   // Assume scalar op for initialization; update for vector if needed.
12649   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12650   // generate a 16-byte vector constant and logic op even for the scalar case.
12651   // Using a 16-byte mask allows folding the load of the mask with
12652   // the logic op, so it can save (~4 bytes) on code size.
12653   MVT EltVT = VT;
12654   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12655   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12656   // decide if we should generate a 16-byte constant mask when we only need 4 or
12657   // 8 bytes for the scalar case.
12658   if (VT.isVector()) {
12659     EltVT = VT.getVectorElementType();
12660     NumElts = VT.getVectorNumElements();
12661   }
12662
12663   unsigned EltBits = EltVT.getSizeInBits();
12664   LLVMContext *Context = DAG.getContext();
12665   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12666   APInt MaskElt =
12667     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12668   Constant *C = ConstantInt::get(*Context, MaskElt);
12669   C = ConstantVector::getSplat(NumElts, C);
12670   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12671   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(DAG.getDataLayout()));
12672   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12673   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12674                              MachinePointerInfo::getConstantPool(),
12675                              false, false, false, Alignment);
12676
12677   if (VT.isVector()) {
12678     // For a vector, cast operands to a vector type, perform the logic op,
12679     // and cast the result back to the original value type.
12680     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12681     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12682     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12683                               : DAG.getBitcast(VecVT, Op0);
12684     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12685     return DAG.getBitcast(VT,
12686                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12687   }
12688
12689   // If not vector, then scalar.
12690   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12691   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12692   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12693 }
12694
12695 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12696   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12697   LLVMContext *Context = DAG.getContext();
12698   SDValue Op0 = Op.getOperand(0);
12699   SDValue Op1 = Op.getOperand(1);
12700   SDLoc dl(Op);
12701   MVT VT = Op.getSimpleValueType();
12702   MVT SrcVT = Op1.getSimpleValueType();
12703
12704   // If second operand is smaller, extend it first.
12705   if (SrcVT.bitsLT(VT)) {
12706     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12707     SrcVT = VT;
12708   }
12709   // And if it is bigger, shrink it first.
12710   if (SrcVT.bitsGT(VT)) {
12711     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12712     SrcVT = VT;
12713   }
12714
12715   // At this point the operands and the result should have the same
12716   // type, and that won't be f80 since that is not custom lowered.
12717
12718   const fltSemantics &Sem =
12719       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12720   const unsigned SizeInBits = VT.getSizeInBits();
12721
12722   SmallVector<Constant *, 4> CV(
12723       VT == MVT::f64 ? 2 : 4,
12724       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12725
12726   // First, clear all bits but the sign bit from the second operand (sign).
12727   CV[0] = ConstantFP::get(*Context,
12728                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12729   Constant *C = ConstantVector::get(CV);
12730   auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
12731   SDValue CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12732   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12733                               MachinePointerInfo::getConstantPool(),
12734                               false, false, false, 16);
12735   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12736
12737   // Next, clear the sign bit from the first operand (magnitude).
12738   // If it's a constant, we can clear it here.
12739   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12740     APFloat APF = Op0CN->getValueAPF();
12741     // If the magnitude is a positive zero, the sign bit alone is enough.
12742     if (APF.isPosZero())
12743       return SignBit;
12744     APF.clearSign();
12745     CV[0] = ConstantFP::get(*Context, APF);
12746   } else {
12747     CV[0] = ConstantFP::get(
12748         *Context,
12749         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12750   }
12751   C = ConstantVector::get(CV);
12752   CPIdx = DAG.getConstantPool(C, PtrVT, 16);
12753   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12754                             MachinePointerInfo::getConstantPool(),
12755                             false, false, false, 16);
12756   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12757   if (!isa<ConstantFPSDNode>(Op0))
12758     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12759
12760   // OR the magnitude value with the sign bit.
12761   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12762 }
12763
12764 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12765   SDValue N0 = Op.getOperand(0);
12766   SDLoc dl(Op);
12767   MVT VT = Op.getSimpleValueType();
12768
12769   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12770   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12771                                   DAG.getConstant(1, dl, VT));
12772   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12773 }
12774
12775 // Check whether an OR'd tree is PTEST-able.
12776 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12777                                       SelectionDAG &DAG) {
12778   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12779
12780   if (!Subtarget->hasSSE41())
12781     return SDValue();
12782
12783   if (!Op->hasOneUse())
12784     return SDValue();
12785
12786   SDNode *N = Op.getNode();
12787   SDLoc DL(N);
12788
12789   SmallVector<SDValue, 8> Opnds;
12790   DenseMap<SDValue, unsigned> VecInMap;
12791   SmallVector<SDValue, 8> VecIns;
12792   EVT VT = MVT::Other;
12793
12794   // Recognize a special case where a vector is casted into wide integer to
12795   // test all 0s.
12796   Opnds.push_back(N->getOperand(0));
12797   Opnds.push_back(N->getOperand(1));
12798
12799   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12800     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12801     // BFS traverse all OR'd operands.
12802     if (I->getOpcode() == ISD::OR) {
12803       Opnds.push_back(I->getOperand(0));
12804       Opnds.push_back(I->getOperand(1));
12805       // Re-evaluate the number of nodes to be traversed.
12806       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12807       continue;
12808     }
12809
12810     // Quit if a non-EXTRACT_VECTOR_ELT
12811     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12812       return SDValue();
12813
12814     // Quit if without a constant index.
12815     SDValue Idx = I->getOperand(1);
12816     if (!isa<ConstantSDNode>(Idx))
12817       return SDValue();
12818
12819     SDValue ExtractedFromVec = I->getOperand(0);
12820     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12821     if (M == VecInMap.end()) {
12822       VT = ExtractedFromVec.getValueType();
12823       // Quit if not 128/256-bit vector.
12824       if (!VT.is128BitVector() && !VT.is256BitVector())
12825         return SDValue();
12826       // Quit if not the same type.
12827       if (VecInMap.begin() != VecInMap.end() &&
12828           VT != VecInMap.begin()->first.getValueType())
12829         return SDValue();
12830       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12831       VecIns.push_back(ExtractedFromVec);
12832     }
12833     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12834   }
12835
12836   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12837          "Not extracted from 128-/256-bit vector.");
12838
12839   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12840
12841   for (DenseMap<SDValue, unsigned>::const_iterator
12842         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12843     // Quit if not all elements are used.
12844     if (I->second != FullMask)
12845       return SDValue();
12846   }
12847
12848   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12849
12850   // Cast all vectors into TestVT for PTEST.
12851   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12852     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12853
12854   // If more than one full vectors are evaluated, OR them first before PTEST.
12855   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12856     // Each iteration will OR 2 nodes and append the result until there is only
12857     // 1 node left, i.e. the final OR'd value of all vectors.
12858     SDValue LHS = VecIns[Slot];
12859     SDValue RHS = VecIns[Slot + 1];
12860     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12861   }
12862
12863   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12864                      VecIns.back(), VecIns.back());
12865 }
12866
12867 /// \brief return true if \c Op has a use that doesn't just read flags.
12868 static bool hasNonFlagsUse(SDValue Op) {
12869   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12870        ++UI) {
12871     SDNode *User = *UI;
12872     unsigned UOpNo = UI.getOperandNo();
12873     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12874       // Look pass truncate.
12875       UOpNo = User->use_begin().getOperandNo();
12876       User = *User->use_begin();
12877     }
12878
12879     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12880         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12881       return true;
12882   }
12883   return false;
12884 }
12885
12886 /// Emit nodes that will be selected as "test Op0,Op0", or something
12887 /// equivalent.
12888 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12889                                     SelectionDAG &DAG) const {
12890   if (Op.getValueType() == MVT::i1) {
12891     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12892     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12893                        DAG.getConstant(0, dl, MVT::i8));
12894   }
12895   // CF and OF aren't always set the way we want. Determine which
12896   // of these we need.
12897   bool NeedCF = false;
12898   bool NeedOF = false;
12899   switch (X86CC) {
12900   default: break;
12901   case X86::COND_A: case X86::COND_AE:
12902   case X86::COND_B: case X86::COND_BE:
12903     NeedCF = true;
12904     break;
12905   case X86::COND_G: case X86::COND_GE:
12906   case X86::COND_L: case X86::COND_LE:
12907   case X86::COND_O: case X86::COND_NO: {
12908     // Check if we really need to set the
12909     // Overflow flag. If NoSignedWrap is present
12910     // that is not actually needed.
12911     switch (Op->getOpcode()) {
12912     case ISD::ADD:
12913     case ISD::SUB:
12914     case ISD::MUL:
12915     case ISD::SHL: {
12916       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12917       if (BinNode->Flags.hasNoSignedWrap())
12918         break;
12919     }
12920     default:
12921       NeedOF = true;
12922       break;
12923     }
12924     break;
12925   }
12926   }
12927   // See if we can use the EFLAGS value from the operand instead of
12928   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12929   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12930   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12931     // Emit a CMP with 0, which is the TEST pattern.
12932     //if (Op.getValueType() == MVT::i1)
12933     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12934     //                     DAG.getConstant(0, MVT::i1));
12935     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12936                        DAG.getConstant(0, dl, Op.getValueType()));
12937   }
12938   unsigned Opcode = 0;
12939   unsigned NumOperands = 0;
12940
12941   // Truncate operations may prevent the merge of the SETCC instruction
12942   // and the arithmetic instruction before it. Attempt to truncate the operands
12943   // of the arithmetic instruction and use a reduced bit-width instruction.
12944   bool NeedTruncation = false;
12945   SDValue ArithOp = Op;
12946   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12947     SDValue Arith = Op->getOperand(0);
12948     // Both the trunc and the arithmetic op need to have one user each.
12949     if (Arith->hasOneUse())
12950       switch (Arith.getOpcode()) {
12951         default: break;
12952         case ISD::ADD:
12953         case ISD::SUB:
12954         case ISD::AND:
12955         case ISD::OR:
12956         case ISD::XOR: {
12957           NeedTruncation = true;
12958           ArithOp = Arith;
12959         }
12960       }
12961   }
12962
12963   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12964   // which may be the result of a CAST.  We use the variable 'Op', which is the
12965   // non-casted variable when we check for possible users.
12966   switch (ArithOp.getOpcode()) {
12967   case ISD::ADD:
12968     // Due to an isel shortcoming, be conservative if this add is likely to be
12969     // selected as part of a load-modify-store instruction. When the root node
12970     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12971     // uses of other nodes in the match, such as the ADD in this case. This
12972     // leads to the ADD being left around and reselected, with the result being
12973     // two adds in the output.  Alas, even if none our users are stores, that
12974     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12975     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12976     // climbing the DAG back to the root, and it doesn't seem to be worth the
12977     // effort.
12978     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12979          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12980       if (UI->getOpcode() != ISD::CopyToReg &&
12981           UI->getOpcode() != ISD::SETCC &&
12982           UI->getOpcode() != ISD::STORE)
12983         goto default_case;
12984
12985     if (ConstantSDNode *C =
12986         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12987       // An add of one will be selected as an INC.
12988       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12989         Opcode = X86ISD::INC;
12990         NumOperands = 1;
12991         break;
12992       }
12993
12994       // An add of negative one (subtract of one) will be selected as a DEC.
12995       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12996         Opcode = X86ISD::DEC;
12997         NumOperands = 1;
12998         break;
12999       }
13000     }
13001
13002     // Otherwise use a regular EFLAGS-setting add.
13003     Opcode = X86ISD::ADD;
13004     NumOperands = 2;
13005     break;
13006   case ISD::SHL:
13007   case ISD::SRL:
13008     // If we have a constant logical shift that's only used in a comparison
13009     // against zero turn it into an equivalent AND. This allows turning it into
13010     // a TEST instruction later.
13011     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
13012         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
13013       EVT VT = Op.getValueType();
13014       unsigned BitWidth = VT.getSizeInBits();
13015       unsigned ShAmt = Op->getConstantOperandVal(1);
13016       if (ShAmt >= BitWidth) // Avoid undefined shifts.
13017         break;
13018       APInt Mask = ArithOp.getOpcode() == ISD::SRL
13019                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
13020                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
13021       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
13022         break;
13023       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
13024                                 DAG.getConstant(Mask, dl, VT));
13025       DAG.ReplaceAllUsesWith(Op, New);
13026       Op = New;
13027     }
13028     break;
13029
13030   case ISD::AND:
13031     // If the primary and result isn't used, don't bother using X86ISD::AND,
13032     // because a TEST instruction will be better.
13033     if (!hasNonFlagsUse(Op))
13034       break;
13035     // FALL THROUGH
13036   case ISD::SUB:
13037   case ISD::OR:
13038   case ISD::XOR:
13039     // Due to the ISEL shortcoming noted above, be conservative if this op is
13040     // likely to be selected as part of a load-modify-store instruction.
13041     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
13042            UE = Op.getNode()->use_end(); UI != UE; ++UI)
13043       if (UI->getOpcode() == ISD::STORE)
13044         goto default_case;
13045
13046     // Otherwise use a regular EFLAGS-setting instruction.
13047     switch (ArithOp.getOpcode()) {
13048     default: llvm_unreachable("unexpected operator!");
13049     case ISD::SUB: Opcode = X86ISD::SUB; break;
13050     case ISD::XOR: Opcode = X86ISD::XOR; break;
13051     case ISD::AND: Opcode = X86ISD::AND; break;
13052     case ISD::OR: {
13053       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
13054         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
13055         if (EFLAGS.getNode())
13056           return EFLAGS;
13057       }
13058       Opcode = X86ISD::OR;
13059       break;
13060     }
13061     }
13062
13063     NumOperands = 2;
13064     break;
13065   case X86ISD::ADD:
13066   case X86ISD::SUB:
13067   case X86ISD::INC:
13068   case X86ISD::DEC:
13069   case X86ISD::OR:
13070   case X86ISD::XOR:
13071   case X86ISD::AND:
13072     return SDValue(Op.getNode(), 1);
13073   default:
13074   default_case:
13075     break;
13076   }
13077
13078   // If we found that truncation is beneficial, perform the truncation and
13079   // update 'Op'.
13080   if (NeedTruncation) {
13081     EVT VT = Op.getValueType();
13082     SDValue WideVal = Op->getOperand(0);
13083     EVT WideVT = WideVal.getValueType();
13084     unsigned ConvertedOp = 0;
13085     // Use a target machine opcode to prevent further DAGCombine
13086     // optimizations that may separate the arithmetic operations
13087     // from the setcc node.
13088     switch (WideVal.getOpcode()) {
13089       default: break;
13090       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
13091       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
13092       case ISD::AND: ConvertedOp = X86ISD::AND; break;
13093       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
13094       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
13095     }
13096
13097     if (ConvertedOp) {
13098       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
13099       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
13100         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
13101         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
13102         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
13103       }
13104     }
13105   }
13106
13107   if (Opcode == 0)
13108     // Emit a CMP with 0, which is the TEST pattern.
13109     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
13110                        DAG.getConstant(0, dl, Op.getValueType()));
13111
13112   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
13113   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
13114
13115   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
13116   DAG.ReplaceAllUsesWith(Op, New);
13117   return SDValue(New.getNode(), 1);
13118 }
13119
13120 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
13121 /// equivalent.
13122 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
13123                                    SDLoc dl, SelectionDAG &DAG) const {
13124   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
13125     if (C->getAPIntValue() == 0)
13126       return EmitTest(Op0, X86CC, dl, DAG);
13127
13128      if (Op0.getValueType() == MVT::i1)
13129        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
13130   }
13131
13132   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
13133        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
13134     // Do the comparison at i32 if it's smaller, besides the Atom case.
13135     // This avoids subregister aliasing issues. Keep the smaller reference
13136     // if we're optimizing for size, however, as that'll allow better folding
13137     // of memory operations.
13138     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
13139         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
13140             Attribute::MinSize) &&
13141         !Subtarget->isAtom()) {
13142       unsigned ExtendOp =
13143           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
13144       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
13145       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
13146     }
13147     // Use SUB instead of CMP to enable CSE between SUB and CMP.
13148     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
13149     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
13150                               Op0, Op1);
13151     return SDValue(Sub.getNode(), 1);
13152   }
13153   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
13154 }
13155
13156 /// Convert a comparison if required by the subtarget.
13157 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
13158                                                  SelectionDAG &DAG) const {
13159   // If the subtarget does not support the FUCOMI instruction, floating-point
13160   // comparisons have to be converted.
13161   if (Subtarget->hasCMov() ||
13162       Cmp.getOpcode() != X86ISD::CMP ||
13163       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
13164       !Cmp.getOperand(1).getValueType().isFloatingPoint())
13165     return Cmp;
13166
13167   // The instruction selector will select an FUCOM instruction instead of
13168   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
13169   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
13170   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
13171   SDLoc dl(Cmp);
13172   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
13173   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
13174   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
13175                             DAG.getConstant(8, dl, MVT::i8));
13176   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
13177   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
13178 }
13179
13180 /// The minimum architected relative accuracy is 2^-12. We need one
13181 /// Newton-Raphson step to have a good float result (24 bits of precision).
13182 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
13183                                             DAGCombinerInfo &DCI,
13184                                             unsigned &RefinementSteps,
13185                                             bool &UseOneConstNR) const {
13186   EVT VT = Op.getValueType();
13187   const char *RecipOp;
13188
13189   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
13190   // TODO: Add support for AVX512 (v16f32).
13191   // It is likely not profitable to do this for f64 because a double-precision
13192   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
13193   // instructions: convert to single, rsqrtss, convert back to double, refine
13194   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
13195   // along with FMA, this could be a throughput win.
13196   if (VT == MVT::f32 && Subtarget->hasSSE1())
13197     RecipOp = "sqrtf";
13198   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13199            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13200     RecipOp = "vec-sqrtf";
13201   else
13202     return SDValue();
13203
13204   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13205   if (!Recips.isEnabled(RecipOp))
13206     return SDValue();
13207
13208   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13209   UseOneConstNR = false;
13210   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13211 }
13212
13213 /// The minimum architected relative accuracy is 2^-12. We need one
13214 /// Newton-Raphson step to have a good float result (24 bits of precision).
13215 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13216                                             DAGCombinerInfo &DCI,
13217                                             unsigned &RefinementSteps) const {
13218   EVT VT = Op.getValueType();
13219   const char *RecipOp;
13220
13221   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13222   // TODO: Add support for AVX512 (v16f32).
13223   // It is likely not profitable to do this for f64 because a double-precision
13224   // reciprocal estimate with refinement on x86 prior to FMA requires
13225   // 15 instructions: convert to single, rcpss, convert back to double, refine
13226   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13227   // along with FMA, this could be a throughput win.
13228   if (VT == MVT::f32 && Subtarget->hasSSE1())
13229     RecipOp = "divf";
13230   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13231            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13232     RecipOp = "vec-divf";
13233   else
13234     return SDValue();
13235
13236   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13237   if (!Recips.isEnabled(RecipOp))
13238     return SDValue();
13239
13240   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13241   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13242 }
13243
13244 /// If we have at least two divisions that use the same divisor, convert to
13245 /// multplication by a reciprocal. This may need to be adjusted for a given
13246 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13247 /// This is because we still need one division to calculate the reciprocal and
13248 /// then we need two multiplies by that reciprocal as replacements for the
13249 /// original divisions.
13250 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13251   return NumUsers > 1;
13252 }
13253
13254 static bool isAllOnes(SDValue V) {
13255   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13256   return C && C->isAllOnesValue();
13257 }
13258
13259 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13260 /// if it's possible.
13261 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13262                                      SDLoc dl, SelectionDAG &DAG) const {
13263   SDValue Op0 = And.getOperand(0);
13264   SDValue Op1 = And.getOperand(1);
13265   if (Op0.getOpcode() == ISD::TRUNCATE)
13266     Op0 = Op0.getOperand(0);
13267   if (Op1.getOpcode() == ISD::TRUNCATE)
13268     Op1 = Op1.getOperand(0);
13269
13270   SDValue LHS, RHS;
13271   if (Op1.getOpcode() == ISD::SHL)
13272     std::swap(Op0, Op1);
13273   if (Op0.getOpcode() == ISD::SHL) {
13274     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13275       if (And00C->getZExtValue() == 1) {
13276         // If we looked past a truncate, check that it's only truncating away
13277         // known zeros.
13278         unsigned BitWidth = Op0.getValueSizeInBits();
13279         unsigned AndBitWidth = And.getValueSizeInBits();
13280         if (BitWidth > AndBitWidth) {
13281           APInt Zeros, Ones;
13282           DAG.computeKnownBits(Op0, Zeros, Ones);
13283           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13284             return SDValue();
13285         }
13286         LHS = Op1;
13287         RHS = Op0.getOperand(1);
13288       }
13289   } else if (Op1.getOpcode() == ISD::Constant) {
13290     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13291     uint64_t AndRHSVal = AndRHS->getZExtValue();
13292     SDValue AndLHS = Op0;
13293
13294     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13295       LHS = AndLHS.getOperand(0);
13296       RHS = AndLHS.getOperand(1);
13297     }
13298
13299     // Use BT if the immediate can't be encoded in a TEST instruction.
13300     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13301       LHS = AndLHS;
13302       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13303     }
13304   }
13305
13306   if (LHS.getNode()) {
13307     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13308     // instruction.  Since the shift amount is in-range-or-undefined, we know
13309     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13310     // the encoding for the i16 version is larger than the i32 version.
13311     // Also promote i16 to i32 for performance / code size reason.
13312     if (LHS.getValueType() == MVT::i8 ||
13313         LHS.getValueType() == MVT::i16)
13314       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13315
13316     // If the operand types disagree, extend the shift amount to match.  Since
13317     // BT ignores high bits (like shifts) we can use anyextend.
13318     if (LHS.getValueType() != RHS.getValueType())
13319       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13320
13321     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13322     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13323     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13324                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13325   }
13326
13327   return SDValue();
13328 }
13329
13330 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13331 /// mask CMPs.
13332 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13333                               SDValue &Op1) {
13334   unsigned SSECC;
13335   bool Swap = false;
13336
13337   // SSE Condition code mapping:
13338   //  0 - EQ
13339   //  1 - LT
13340   //  2 - LE
13341   //  3 - UNORD
13342   //  4 - NEQ
13343   //  5 - NLT
13344   //  6 - NLE
13345   //  7 - ORD
13346   switch (SetCCOpcode) {
13347   default: llvm_unreachable("Unexpected SETCC condition");
13348   case ISD::SETOEQ:
13349   case ISD::SETEQ:  SSECC = 0; break;
13350   case ISD::SETOGT:
13351   case ISD::SETGT:  Swap = true; // Fallthrough
13352   case ISD::SETLT:
13353   case ISD::SETOLT: SSECC = 1; break;
13354   case ISD::SETOGE:
13355   case ISD::SETGE:  Swap = true; // Fallthrough
13356   case ISD::SETLE:
13357   case ISD::SETOLE: SSECC = 2; break;
13358   case ISD::SETUO:  SSECC = 3; break;
13359   case ISD::SETUNE:
13360   case ISD::SETNE:  SSECC = 4; break;
13361   case ISD::SETULE: Swap = true; // Fallthrough
13362   case ISD::SETUGE: SSECC = 5; break;
13363   case ISD::SETULT: Swap = true; // Fallthrough
13364   case ISD::SETUGT: SSECC = 6; break;
13365   case ISD::SETO:   SSECC = 7; break;
13366   case ISD::SETUEQ:
13367   case ISD::SETONE: SSECC = 8; break;
13368   }
13369   if (Swap)
13370     std::swap(Op0, Op1);
13371
13372   return SSECC;
13373 }
13374
13375 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13376 // ones, and then concatenate the result back.
13377 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13378   MVT VT = Op.getSimpleValueType();
13379
13380   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13381          "Unsupported value type for operation");
13382
13383   unsigned NumElems = VT.getVectorNumElements();
13384   SDLoc dl(Op);
13385   SDValue CC = Op.getOperand(2);
13386
13387   // Extract the LHS vectors
13388   SDValue LHS = Op.getOperand(0);
13389   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13390   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13391
13392   // Extract the RHS vectors
13393   SDValue RHS = Op.getOperand(1);
13394   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13395   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13396
13397   // Issue the operation on the smaller types and concatenate the result back
13398   MVT EltVT = VT.getVectorElementType();
13399   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13400   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13401                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13402                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13403 }
13404
13405 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13406   SDValue Op0 = Op.getOperand(0);
13407   SDValue Op1 = Op.getOperand(1);
13408   SDValue CC = Op.getOperand(2);
13409   MVT VT = Op.getSimpleValueType();
13410   SDLoc dl(Op);
13411
13412   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13413          "Unexpected type for boolean compare operation");
13414   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13415   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13416                                DAG.getConstant(-1, dl, VT));
13417   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13418                                DAG.getConstant(-1, dl, VT));
13419   switch (SetCCOpcode) {
13420   default: llvm_unreachable("Unexpected SETCC condition");
13421   case ISD::SETEQ:
13422     // (x == y) -> ~(x ^ y)
13423     return DAG.getNode(ISD::XOR, dl, VT,
13424                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13425                        DAG.getConstant(-1, dl, VT));
13426   case ISD::SETNE:
13427     // (x != y) -> (x ^ y)
13428     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13429   case ISD::SETUGT:
13430   case ISD::SETGT:
13431     // (x > y) -> (x & ~y)
13432     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13433   case ISD::SETULT:
13434   case ISD::SETLT:
13435     // (x < y) -> (~x & y)
13436     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13437   case ISD::SETULE:
13438   case ISD::SETLE:
13439     // (x <= y) -> (~x | y)
13440     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13441   case ISD::SETUGE:
13442   case ISD::SETGE:
13443     // (x >=y) -> (x | ~y)
13444     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13445   }
13446 }
13447
13448 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13449                                      const X86Subtarget *Subtarget) {
13450   SDValue Op0 = Op.getOperand(0);
13451   SDValue Op1 = Op.getOperand(1);
13452   SDValue CC = Op.getOperand(2);
13453   MVT VT = Op.getSimpleValueType();
13454   SDLoc dl(Op);
13455
13456   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13457          Op.getValueType().getScalarType() == MVT::i1 &&
13458          "Cannot set masked compare for this operation");
13459
13460   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13461   unsigned  Opc = 0;
13462   bool Unsigned = false;
13463   bool Swap = false;
13464   unsigned SSECC;
13465   switch (SetCCOpcode) {
13466   default: llvm_unreachable("Unexpected SETCC condition");
13467   case ISD::SETNE:  SSECC = 4; break;
13468   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13469   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13470   case ISD::SETLT:  Swap = true; //fall-through
13471   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13472   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13473   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13474   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13475   case ISD::SETULE: Unsigned = true; //fall-through
13476   case ISD::SETLE:  SSECC = 2; break;
13477   }
13478
13479   if (Swap)
13480     std::swap(Op0, Op1);
13481   if (Opc)
13482     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13483   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13484   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13485                      DAG.getConstant(SSECC, dl, MVT::i8));
13486 }
13487
13488 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13489 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13490 /// return an empty value.
13491 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13492 {
13493   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13494   if (!BV)
13495     return SDValue();
13496
13497   MVT VT = Op1.getSimpleValueType();
13498   MVT EVT = VT.getVectorElementType();
13499   unsigned n = VT.getVectorNumElements();
13500   SmallVector<SDValue, 8> ULTOp1;
13501
13502   for (unsigned i = 0; i < n; ++i) {
13503     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13504     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13505       return SDValue();
13506
13507     // Avoid underflow.
13508     APInt Val = Elt->getAPIntValue();
13509     if (Val == 0)
13510       return SDValue();
13511
13512     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13513   }
13514
13515   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13516 }
13517
13518 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13519                            SelectionDAG &DAG) {
13520   SDValue Op0 = Op.getOperand(0);
13521   SDValue Op1 = Op.getOperand(1);
13522   SDValue CC = Op.getOperand(2);
13523   MVT VT = Op.getSimpleValueType();
13524   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13525   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13526   SDLoc dl(Op);
13527
13528   if (isFP) {
13529 #ifndef NDEBUG
13530     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13531     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13532 #endif
13533
13534     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13535     unsigned Opc = X86ISD::CMPP;
13536     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13537       assert(VT.getVectorNumElements() <= 16);
13538       Opc = X86ISD::CMPM;
13539     }
13540     // In the two special cases we can't handle, emit two comparisons.
13541     if (SSECC == 8) {
13542       unsigned CC0, CC1;
13543       unsigned CombineOpc;
13544       if (SetCCOpcode == ISD::SETUEQ) {
13545         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13546       } else {
13547         assert(SetCCOpcode == ISD::SETONE);
13548         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13549       }
13550
13551       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13552                                  DAG.getConstant(CC0, dl, MVT::i8));
13553       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13554                                  DAG.getConstant(CC1, dl, MVT::i8));
13555       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13556     }
13557     // Handle all other FP comparisons here.
13558     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13559                        DAG.getConstant(SSECC, dl, MVT::i8));
13560   }
13561
13562   // Break 256-bit integer vector compare into smaller ones.
13563   if (VT.is256BitVector() && !Subtarget->hasInt256())
13564     return Lower256IntVSETCC(Op, DAG);
13565
13566   EVT OpVT = Op1.getValueType();
13567   if (OpVT.getVectorElementType() == MVT::i1)
13568     return LowerBoolVSETCC_AVX512(Op, DAG);
13569
13570   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13571   if (Subtarget->hasAVX512()) {
13572     if (Op1.getValueType().is512BitVector() ||
13573         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13574         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13575       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13576
13577     // In AVX-512 architecture setcc returns mask with i1 elements,
13578     // But there is no compare instruction for i8 and i16 elements in KNL.
13579     // We are not talking about 512-bit operands in this case, these
13580     // types are illegal.
13581     if (MaskResult &&
13582         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13583          OpVT.getVectorElementType().getSizeInBits() >= 8))
13584       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13585                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13586   }
13587
13588   // We are handling one of the integer comparisons here.  Since SSE only has
13589   // GT and EQ comparisons for integer, swapping operands and multiple
13590   // operations may be required for some comparisons.
13591   unsigned Opc;
13592   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13593   bool Subus = false;
13594
13595   switch (SetCCOpcode) {
13596   default: llvm_unreachable("Unexpected SETCC condition");
13597   case ISD::SETNE:  Invert = true;
13598   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13599   case ISD::SETLT:  Swap = true;
13600   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13601   case ISD::SETGE:  Swap = true;
13602   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13603                     Invert = true; break;
13604   case ISD::SETULT: Swap = true;
13605   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13606                     FlipSigns = true; break;
13607   case ISD::SETUGE: Swap = true;
13608   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13609                     FlipSigns = true; Invert = true; break;
13610   }
13611
13612   // Special case: Use min/max operations for SETULE/SETUGE
13613   MVT VET = VT.getVectorElementType();
13614   bool hasMinMax =
13615        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13616     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13617
13618   if (hasMinMax) {
13619     switch (SetCCOpcode) {
13620     default: break;
13621     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13622     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13623     }
13624
13625     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13626   }
13627
13628   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13629   if (!MinMax && hasSubus) {
13630     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13631     // Op0 u<= Op1:
13632     //   t = psubus Op0, Op1
13633     //   pcmpeq t, <0..0>
13634     switch (SetCCOpcode) {
13635     default: break;
13636     case ISD::SETULT: {
13637       // If the comparison is against a constant we can turn this into a
13638       // setule.  With psubus, setule does not require a swap.  This is
13639       // beneficial because the constant in the register is no longer
13640       // destructed as the destination so it can be hoisted out of a loop.
13641       // Only do this pre-AVX since vpcmp* is no longer destructive.
13642       if (Subtarget->hasAVX())
13643         break;
13644       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13645       if (ULEOp1.getNode()) {
13646         Op1 = ULEOp1;
13647         Subus = true; Invert = false; Swap = false;
13648       }
13649       break;
13650     }
13651     // Psubus is better than flip-sign because it requires no inversion.
13652     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13653     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13654     }
13655
13656     if (Subus) {
13657       Opc = X86ISD::SUBUS;
13658       FlipSigns = false;
13659     }
13660   }
13661
13662   if (Swap)
13663     std::swap(Op0, Op1);
13664
13665   // Check that the operation in question is available (most are plain SSE2,
13666   // but PCMPGTQ and PCMPEQQ have different requirements).
13667   if (VT == MVT::v2i64) {
13668     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13669       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13670
13671       // First cast everything to the right type.
13672       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13673       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13674
13675       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13676       // bits of the inputs before performing those operations. The lower
13677       // compare is always unsigned.
13678       SDValue SB;
13679       if (FlipSigns) {
13680         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13681       } else {
13682         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13683         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13684         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13685                          Sign, Zero, Sign, Zero);
13686       }
13687       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13688       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13689
13690       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13691       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13692       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13693
13694       // Create masks for only the low parts/high parts of the 64 bit integers.
13695       static const int MaskHi[] = { 1, 1, 3, 3 };
13696       static const int MaskLo[] = { 0, 0, 2, 2 };
13697       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13698       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13699       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13700
13701       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13702       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13703
13704       if (Invert)
13705         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13706
13707       return DAG.getBitcast(VT, Result);
13708     }
13709
13710     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13711       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13712       // pcmpeqd + pshufd + pand.
13713       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13714
13715       // First cast everything to the right type.
13716       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13717       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13718
13719       // Do the compare.
13720       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13721
13722       // Make sure the lower and upper halves are both all-ones.
13723       static const int Mask[] = { 1, 0, 3, 2 };
13724       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13725       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13726
13727       if (Invert)
13728         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13729
13730       return DAG.getBitcast(VT, Result);
13731     }
13732   }
13733
13734   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13735   // bits of the inputs before performing those operations.
13736   if (FlipSigns) {
13737     EVT EltVT = VT.getVectorElementType();
13738     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13739                                  VT);
13740     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13741     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13742   }
13743
13744   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13745
13746   // If the logical-not of the result is required, perform that now.
13747   if (Invert)
13748     Result = DAG.getNOT(dl, Result, VT);
13749
13750   if (MinMax)
13751     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13752
13753   if (Subus)
13754     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13755                          getZeroVector(VT, Subtarget, DAG, dl));
13756
13757   return Result;
13758 }
13759
13760 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13761
13762   MVT VT = Op.getSimpleValueType();
13763
13764   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13765
13766   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13767          && "SetCC type must be 8-bit or 1-bit integer");
13768   SDValue Op0 = Op.getOperand(0);
13769   SDValue Op1 = Op.getOperand(1);
13770   SDLoc dl(Op);
13771   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13772
13773   // Optimize to BT if possible.
13774   // Lower (X & (1 << N)) == 0 to BT(X, N).
13775   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13776   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13777   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13778       Op1.getOpcode() == ISD::Constant &&
13779       cast<ConstantSDNode>(Op1)->isNullValue() &&
13780       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13781     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13782     if (NewSetCC.getNode()) {
13783       if (VT == MVT::i1)
13784         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13785       return NewSetCC;
13786     }
13787   }
13788
13789   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13790   // these.
13791   if (Op1.getOpcode() == ISD::Constant &&
13792       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13793        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13794       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13795
13796     // If the input is a setcc, then reuse the input setcc or use a new one with
13797     // the inverted condition.
13798     if (Op0.getOpcode() == X86ISD::SETCC) {
13799       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13800       bool Invert = (CC == ISD::SETNE) ^
13801         cast<ConstantSDNode>(Op1)->isNullValue();
13802       if (!Invert)
13803         return Op0;
13804
13805       CCode = X86::GetOppositeBranchCondition(CCode);
13806       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13807                                   DAG.getConstant(CCode, dl, MVT::i8),
13808                                   Op0.getOperand(1));
13809       if (VT == MVT::i1)
13810         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13811       return SetCC;
13812     }
13813   }
13814   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13815       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13816       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13817
13818     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13819     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13820   }
13821
13822   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13823   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13824   if (X86CC == X86::COND_INVALID)
13825     return SDValue();
13826
13827   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13828   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13829   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13830                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13831   if (VT == MVT::i1)
13832     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13833   return SetCC;
13834 }
13835
13836 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13837 static bool isX86LogicalCmp(SDValue Op) {
13838   unsigned Opc = Op.getNode()->getOpcode();
13839   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13840       Opc == X86ISD::SAHF)
13841     return true;
13842   if (Op.getResNo() == 1 &&
13843       (Opc == X86ISD::ADD ||
13844        Opc == X86ISD::SUB ||
13845        Opc == X86ISD::ADC ||
13846        Opc == X86ISD::SBB ||
13847        Opc == X86ISD::SMUL ||
13848        Opc == X86ISD::UMUL ||
13849        Opc == X86ISD::INC ||
13850        Opc == X86ISD::DEC ||
13851        Opc == X86ISD::OR ||
13852        Opc == X86ISD::XOR ||
13853        Opc == X86ISD::AND))
13854     return true;
13855
13856   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13857     return true;
13858
13859   return false;
13860 }
13861
13862 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13863   if (V.getOpcode() != ISD::TRUNCATE)
13864     return false;
13865
13866   SDValue VOp0 = V.getOperand(0);
13867   unsigned InBits = VOp0.getValueSizeInBits();
13868   unsigned Bits = V.getValueSizeInBits();
13869   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13870 }
13871
13872 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13873   bool addTest = true;
13874   SDValue Cond  = Op.getOperand(0);
13875   SDValue Op1 = Op.getOperand(1);
13876   SDValue Op2 = Op.getOperand(2);
13877   SDLoc DL(Op);
13878   EVT VT = Op1.getValueType();
13879   SDValue CC;
13880
13881   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13882   // are available or VBLENDV if AVX is available.
13883   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13884   if (Cond.getOpcode() == ISD::SETCC &&
13885       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13886        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13887       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13888     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13889     int SSECC = translateX86FSETCC(
13890         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13891
13892     if (SSECC != 8) {
13893       if (Subtarget->hasAVX512()) {
13894         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13895                                   DAG.getConstant(SSECC, DL, MVT::i8));
13896         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13897       }
13898
13899       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13900                                 DAG.getConstant(SSECC, DL, MVT::i8));
13901
13902       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13903       // of 3 logic instructions for size savings and potentially speed.
13904       // Unfortunately, there is no scalar form of VBLENDV.
13905
13906       // If either operand is a constant, don't try this. We can expect to
13907       // optimize away at least one of the logic instructions later in that
13908       // case, so that sequence would be faster than a variable blend.
13909
13910       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13911       // uses XMM0 as the selection register. That may need just as many
13912       // instructions as the AND/ANDN/OR sequence due to register moves, so
13913       // don't bother.
13914
13915       if (Subtarget->hasAVX() &&
13916           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13917
13918         // Convert to vectors, do a VSELECT, and convert back to scalar.
13919         // All of the conversions should be optimized away.
13920
13921         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13922         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13923         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13924         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13925
13926         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13927         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13928
13929         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13930
13931         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13932                            VSel, DAG.getIntPtrConstant(0, DL));
13933       }
13934       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13935       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13936       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13937     }
13938   }
13939
13940     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13941       SDValue Op1Scalar;
13942       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13943         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13944       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13945         Op1Scalar = Op1.getOperand(0);
13946       SDValue Op2Scalar;
13947       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13948         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13949       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13950         Op2Scalar = Op2.getOperand(0);
13951       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13952         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13953                                         Op1Scalar.getValueType(),
13954                                         Cond, Op1Scalar, Op2Scalar);
13955         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13956           return DAG.getBitcast(VT, newSelect);
13957         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13958         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13959                            DAG.getIntPtrConstant(0, DL));
13960     }
13961   }
13962
13963   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13964     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13965     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13966                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13967     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13968                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13969     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13970                                     Cond, Op1, Op2);
13971     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13972   }
13973
13974   if (Cond.getOpcode() == ISD::SETCC) {
13975     SDValue NewCond = LowerSETCC(Cond, DAG);
13976     if (NewCond.getNode())
13977       Cond = NewCond;
13978   }
13979
13980   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13981   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13982   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13983   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13984   if (Cond.getOpcode() == X86ISD::SETCC &&
13985       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13986       isZero(Cond.getOperand(1).getOperand(1))) {
13987     SDValue Cmp = Cond.getOperand(1);
13988
13989     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13990
13991     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13992         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13993       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13994
13995       SDValue CmpOp0 = Cmp.getOperand(0);
13996       // Apply further optimizations for special cases
13997       // (select (x != 0), -1, 0) -> neg & sbb
13998       // (select (x == 0), 0, -1) -> neg & sbb
13999       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
14000         if (YC->isNullValue() &&
14001             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
14002           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
14003           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
14004                                     DAG.getConstant(0, DL,
14005                                                     CmpOp0.getValueType()),
14006                                     CmpOp0);
14007           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14008                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
14009                                     SDValue(Neg.getNode(), 1));
14010           return Res;
14011         }
14012
14013       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
14014                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
14015       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14016
14017       SDValue Res =   // Res = 0 or -1.
14018         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14019                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
14020
14021       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
14022         Res = DAG.getNOT(DL, Res, Res.getValueType());
14023
14024       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
14025       if (!N2C || !N2C->isNullValue())
14026         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
14027       return Res;
14028     }
14029   }
14030
14031   // Look past (and (setcc_carry (cmp ...)), 1).
14032   if (Cond.getOpcode() == ISD::AND &&
14033       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14034     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14035     if (C && C->getAPIntValue() == 1)
14036       Cond = Cond.getOperand(0);
14037   }
14038
14039   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14040   // setting operand in place of the X86ISD::SETCC.
14041   unsigned CondOpcode = Cond.getOpcode();
14042   if (CondOpcode == X86ISD::SETCC ||
14043       CondOpcode == X86ISD::SETCC_CARRY) {
14044     CC = Cond.getOperand(0);
14045
14046     SDValue Cmp = Cond.getOperand(1);
14047     unsigned Opc = Cmp.getOpcode();
14048     MVT VT = Op.getSimpleValueType();
14049
14050     bool IllegalFPCMov = false;
14051     if (VT.isFloatingPoint() && !VT.isVector() &&
14052         !isScalarFPTypeInSSEReg(VT))  // FPStack?
14053       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
14054
14055     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
14056         Opc == X86ISD::BT) { // FIXME
14057       Cond = Cmp;
14058       addTest = false;
14059     }
14060   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14061              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14062              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14063               Cond.getOperand(0).getValueType() != MVT::i8)) {
14064     SDValue LHS = Cond.getOperand(0);
14065     SDValue RHS = Cond.getOperand(1);
14066     unsigned X86Opcode;
14067     unsigned X86Cond;
14068     SDVTList VTs;
14069     switch (CondOpcode) {
14070     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14071     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14072     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14073     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14074     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14075     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14076     default: llvm_unreachable("unexpected overflowing operator");
14077     }
14078     if (CondOpcode == ISD::UMULO)
14079       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14080                           MVT::i32);
14081     else
14082       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14083
14084     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
14085
14086     if (CondOpcode == ISD::UMULO)
14087       Cond = X86Op.getValue(2);
14088     else
14089       Cond = X86Op.getValue(1);
14090
14091     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
14092     addTest = false;
14093   }
14094
14095   if (addTest) {
14096     // Look pass the truncate if the high bits are known zero.
14097     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14098         Cond = Cond.getOperand(0);
14099
14100     // We know the result of AND is compared against zero. Try to match
14101     // it to BT.
14102     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14103       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
14104       if (NewSetCC.getNode()) {
14105         CC = NewSetCC.getOperand(0);
14106         Cond = NewSetCC.getOperand(1);
14107         addTest = false;
14108       }
14109     }
14110   }
14111
14112   if (addTest) {
14113     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
14114     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
14115   }
14116
14117   // a <  b ? -1 :  0 -> RES = ~setcc_carry
14118   // a <  b ?  0 : -1 -> RES = setcc_carry
14119   // a >= b ? -1 :  0 -> RES = setcc_carry
14120   // a >= b ?  0 : -1 -> RES = ~setcc_carry
14121   if (Cond.getOpcode() == X86ISD::SUB) {
14122     Cond = ConvertCmpIfNecessary(Cond, DAG);
14123     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
14124
14125     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
14126         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
14127       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
14128                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
14129                                 Cond);
14130       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
14131         return DAG.getNOT(DL, Res, Res.getValueType());
14132       return Res;
14133     }
14134   }
14135
14136   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
14137   // widen the cmov and push the truncate through. This avoids introducing a new
14138   // branch during isel and doesn't add any extensions.
14139   if (Op.getValueType() == MVT::i8 &&
14140       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
14141     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
14142     if (T1.getValueType() == T2.getValueType() &&
14143         // Blacklist CopyFromReg to avoid partial register stalls.
14144         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
14145       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
14146       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
14147       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
14148     }
14149   }
14150
14151   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
14152   // condition is true.
14153   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
14154   SDValue Ops[] = { Op2, Op1, CC, Cond };
14155   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
14156 }
14157
14158 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
14159                                        const X86Subtarget *Subtarget,
14160                                        SelectionDAG &DAG) {
14161   MVT VT = Op->getSimpleValueType(0);
14162   SDValue In = Op->getOperand(0);
14163   MVT InVT = In.getSimpleValueType();
14164   MVT VTElt = VT.getVectorElementType();
14165   MVT InVTElt = InVT.getVectorElementType();
14166   SDLoc dl(Op);
14167
14168   // SKX processor
14169   if ((InVTElt == MVT::i1) &&
14170       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
14171         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
14172
14173        ((Subtarget->hasBWI() && VT.is512BitVector() &&
14174         VTElt.getSizeInBits() <= 16)) ||
14175
14176        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
14177         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
14178
14179        ((Subtarget->hasDQI() && VT.is512BitVector() &&
14180         VTElt.getSizeInBits() >= 32))))
14181     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14182
14183   unsigned int NumElts = VT.getVectorNumElements();
14184
14185   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
14186     return SDValue();
14187
14188   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
14189     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
14190       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
14191     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14192   }
14193
14194   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
14195   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
14196   SDValue NegOne =
14197    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
14198                    ExtVT);
14199   SDValue Zero =
14200    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
14201
14202   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
14203   if (VT.is512BitVector())
14204     return V;
14205   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
14206 }
14207
14208 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14209                                              const X86Subtarget *Subtarget,
14210                                              SelectionDAG &DAG) {
14211   SDValue In = Op->getOperand(0);
14212   MVT VT = Op->getSimpleValueType(0);
14213   MVT InVT = In.getSimpleValueType();
14214   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14215
14216   MVT InSVT = InVT.getScalarType();
14217   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14218
14219   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14220     return SDValue();
14221   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14222     return SDValue();
14223
14224   SDLoc dl(Op);
14225
14226   // SSE41 targets can use the pmovsx* instructions directly.
14227   if (Subtarget->hasSSE41())
14228     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14229
14230   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14231   SDValue Curr = In;
14232   MVT CurrVT = InVT;
14233
14234   // As SRAI is only available on i16/i32 types, we expand only up to i32
14235   // and handle i64 separately.
14236   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14237     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14238     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14239     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14240     Curr = DAG.getBitcast(CurrVT, Curr);
14241   }
14242
14243   SDValue SignExt = Curr;
14244   if (CurrVT != InVT) {
14245     unsigned SignExtShift =
14246         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14247     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14248                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14249   }
14250
14251   if (CurrVT == VT)
14252     return SignExt;
14253
14254   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14255     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14256                                DAG.getConstant(31, dl, MVT::i8));
14257     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14258     return DAG.getBitcast(VT, Ext);
14259   }
14260
14261   return SDValue();
14262 }
14263
14264 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14265                                 SelectionDAG &DAG) {
14266   MVT VT = Op->getSimpleValueType(0);
14267   SDValue In = Op->getOperand(0);
14268   MVT InVT = In.getSimpleValueType();
14269   SDLoc dl(Op);
14270
14271   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14272     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14273
14274   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14275       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14276       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14277     return SDValue();
14278
14279   if (Subtarget->hasInt256())
14280     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14281
14282   // Optimize vectors in AVX mode
14283   // Sign extend  v8i16 to v8i32 and
14284   //              v4i32 to v4i64
14285   //
14286   // Divide input vector into two parts
14287   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14288   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14289   // concat the vectors to original VT
14290
14291   unsigned NumElems = InVT.getVectorNumElements();
14292   SDValue Undef = DAG.getUNDEF(InVT);
14293
14294   SmallVector<int,8> ShufMask1(NumElems, -1);
14295   for (unsigned i = 0; i != NumElems/2; ++i)
14296     ShufMask1[i] = i;
14297
14298   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14299
14300   SmallVector<int,8> ShufMask2(NumElems, -1);
14301   for (unsigned i = 0; i != NumElems/2; ++i)
14302     ShufMask2[i] = i + NumElems/2;
14303
14304   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14305
14306   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14307                                 VT.getVectorNumElements()/2);
14308
14309   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14310   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14311
14312   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14313 }
14314
14315 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14316 // may emit an illegal shuffle but the expansion is still better than scalar
14317 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14318 // we'll emit a shuffle and a arithmetic shift.
14319 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14320 // TODO: It is possible to support ZExt by zeroing the undef values during
14321 // the shuffle phase or after the shuffle.
14322 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14323                                  SelectionDAG &DAG) {
14324   MVT RegVT = Op.getSimpleValueType();
14325   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14326   assert(RegVT.isInteger() &&
14327          "We only custom lower integer vector sext loads.");
14328
14329   // Nothing useful we can do without SSE2 shuffles.
14330   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14331
14332   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14333   SDLoc dl(Ld);
14334   EVT MemVT = Ld->getMemoryVT();
14335   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14336   unsigned RegSz = RegVT.getSizeInBits();
14337
14338   ISD::LoadExtType Ext = Ld->getExtensionType();
14339
14340   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14341          && "Only anyext and sext are currently implemented.");
14342   assert(MemVT != RegVT && "Cannot extend to the same type");
14343   assert(MemVT.isVector() && "Must load a vector from memory");
14344
14345   unsigned NumElems = RegVT.getVectorNumElements();
14346   unsigned MemSz = MemVT.getSizeInBits();
14347   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14348
14349   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14350     // The only way in which we have a legal 256-bit vector result but not the
14351     // integer 256-bit operations needed to directly lower a sextload is if we
14352     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14353     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14354     // correctly legalized. We do this late to allow the canonical form of
14355     // sextload to persist throughout the rest of the DAG combiner -- it wants
14356     // to fold together any extensions it can, and so will fuse a sign_extend
14357     // of an sextload into a sextload targeting a wider value.
14358     SDValue Load;
14359     if (MemSz == 128) {
14360       // Just switch this to a normal load.
14361       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14362                                        "it must be a legal 128-bit vector "
14363                                        "type!");
14364       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14365                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14366                   Ld->isInvariant(), Ld->getAlignment());
14367     } else {
14368       assert(MemSz < 128 &&
14369              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14370       // Do an sext load to a 128-bit vector type. We want to use the same
14371       // number of elements, but elements half as wide. This will end up being
14372       // recursively lowered by this routine, but will succeed as we definitely
14373       // have all the necessary features if we're using AVX1.
14374       EVT HalfEltVT =
14375           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14376       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14377       Load =
14378           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14379                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14380                          Ld->isNonTemporal(), Ld->isInvariant(),
14381                          Ld->getAlignment());
14382     }
14383
14384     // Replace chain users with the new chain.
14385     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14386     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14387
14388     // Finally, do a normal sign-extend to the desired register.
14389     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14390   }
14391
14392   // All sizes must be a power of two.
14393   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14394          "Non-power-of-two elements are not custom lowered!");
14395
14396   // Attempt to load the original value using scalar loads.
14397   // Find the largest scalar type that divides the total loaded size.
14398   MVT SclrLoadTy = MVT::i8;
14399   for (MVT Tp : MVT::integer_valuetypes()) {
14400     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14401       SclrLoadTy = Tp;
14402     }
14403   }
14404
14405   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14406   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14407       (64 <= MemSz))
14408     SclrLoadTy = MVT::f64;
14409
14410   // Calculate the number of scalar loads that we need to perform
14411   // in order to load our vector from memory.
14412   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14413
14414   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14415          "Can only lower sext loads with a single scalar load!");
14416
14417   unsigned loadRegZize = RegSz;
14418   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14419     loadRegZize = 128;
14420
14421   // Represent our vector as a sequence of elements which are the
14422   // largest scalar that we can load.
14423   EVT LoadUnitVecVT = EVT::getVectorVT(
14424       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14425
14426   // Represent the data using the same element type that is stored in
14427   // memory. In practice, we ''widen'' MemVT.
14428   EVT WideVecVT =
14429       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14430                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14431
14432   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14433          "Invalid vector type");
14434
14435   // We can't shuffle using an illegal type.
14436   assert(TLI.isTypeLegal(WideVecVT) &&
14437          "We only lower types that form legal widened vector types");
14438
14439   SmallVector<SDValue, 8> Chains;
14440   SDValue Ptr = Ld->getBasePtr();
14441   SDValue Increment = DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl,
14442                                       TLI.getPointerTy(DAG.getDataLayout()));
14443   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14444
14445   for (unsigned i = 0; i < NumLoads; ++i) {
14446     // Perform a single load.
14447     SDValue ScalarLoad =
14448         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14449                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14450                     Ld->getAlignment());
14451     Chains.push_back(ScalarLoad.getValue(1));
14452     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14453     // another round of DAGCombining.
14454     if (i == 0)
14455       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14456     else
14457       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14458                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14459
14460     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14461   }
14462
14463   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14464
14465   // Bitcast the loaded value to a vector of the original element type, in
14466   // the size of the target vector type.
14467   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14468   unsigned SizeRatio = RegSz / MemSz;
14469
14470   if (Ext == ISD::SEXTLOAD) {
14471     // If we have SSE4.1, we can directly emit a VSEXT node.
14472     if (Subtarget->hasSSE41()) {
14473       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14474       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14475       return Sext;
14476     }
14477
14478     // Otherwise we'll shuffle the small elements in the high bits of the
14479     // larger type and perform an arithmetic shift. If the shift is not legal
14480     // it's better to scalarize.
14481     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14482            "We can't implement a sext load without an arithmetic right shift!");
14483
14484     // Redistribute the loaded elements into the different locations.
14485     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14486     for (unsigned i = 0; i != NumElems; ++i)
14487       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14488
14489     SDValue Shuff = DAG.getVectorShuffle(
14490         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14491
14492     Shuff = DAG.getBitcast(RegVT, Shuff);
14493
14494     // Build the arithmetic shift.
14495     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14496                    MemVT.getVectorElementType().getSizeInBits();
14497     Shuff =
14498         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14499                     DAG.getConstant(Amt, dl, RegVT));
14500
14501     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14502     return Shuff;
14503   }
14504
14505   // Redistribute the loaded elements into the different locations.
14506   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14507   for (unsigned i = 0; i != NumElems; ++i)
14508     ShuffleVec[i * SizeRatio] = i;
14509
14510   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14511                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14512
14513   // Bitcast to the requested type.
14514   Shuff = DAG.getBitcast(RegVT, Shuff);
14515   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14516   return Shuff;
14517 }
14518
14519 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14520 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14521 // from the AND / OR.
14522 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14523   Opc = Op.getOpcode();
14524   if (Opc != ISD::OR && Opc != ISD::AND)
14525     return false;
14526   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14527           Op.getOperand(0).hasOneUse() &&
14528           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14529           Op.getOperand(1).hasOneUse());
14530 }
14531
14532 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14533 // 1 and that the SETCC node has a single use.
14534 static bool isXor1OfSetCC(SDValue Op) {
14535   if (Op.getOpcode() != ISD::XOR)
14536     return false;
14537   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14538   if (N1C && N1C->getAPIntValue() == 1) {
14539     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14540       Op.getOperand(0).hasOneUse();
14541   }
14542   return false;
14543 }
14544
14545 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14546   bool addTest = true;
14547   SDValue Chain = Op.getOperand(0);
14548   SDValue Cond  = Op.getOperand(1);
14549   SDValue Dest  = Op.getOperand(2);
14550   SDLoc dl(Op);
14551   SDValue CC;
14552   bool Inverted = false;
14553
14554   if (Cond.getOpcode() == ISD::SETCC) {
14555     // Check for setcc([su]{add,sub,mul}o == 0).
14556     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14557         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14558         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14559         Cond.getOperand(0).getResNo() == 1 &&
14560         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14561          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14562          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14563          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14564          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14565          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14566       Inverted = true;
14567       Cond = Cond.getOperand(0);
14568     } else {
14569       SDValue NewCond = LowerSETCC(Cond, DAG);
14570       if (NewCond.getNode())
14571         Cond = NewCond;
14572     }
14573   }
14574 #if 0
14575   // FIXME: LowerXALUO doesn't handle these!!
14576   else if (Cond.getOpcode() == X86ISD::ADD  ||
14577            Cond.getOpcode() == X86ISD::SUB  ||
14578            Cond.getOpcode() == X86ISD::SMUL ||
14579            Cond.getOpcode() == X86ISD::UMUL)
14580     Cond = LowerXALUO(Cond, DAG);
14581 #endif
14582
14583   // Look pass (and (setcc_carry (cmp ...)), 1).
14584   if (Cond.getOpcode() == ISD::AND &&
14585       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14586     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14587     if (C && C->getAPIntValue() == 1)
14588       Cond = Cond.getOperand(0);
14589   }
14590
14591   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14592   // setting operand in place of the X86ISD::SETCC.
14593   unsigned CondOpcode = Cond.getOpcode();
14594   if (CondOpcode == X86ISD::SETCC ||
14595       CondOpcode == X86ISD::SETCC_CARRY) {
14596     CC = Cond.getOperand(0);
14597
14598     SDValue Cmp = Cond.getOperand(1);
14599     unsigned Opc = Cmp.getOpcode();
14600     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14601     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14602       Cond = Cmp;
14603       addTest = false;
14604     } else {
14605       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14606       default: break;
14607       case X86::COND_O:
14608       case X86::COND_B:
14609         // These can only come from an arithmetic instruction with overflow,
14610         // e.g. SADDO, UADDO.
14611         Cond = Cond.getNode()->getOperand(1);
14612         addTest = false;
14613         break;
14614       }
14615     }
14616   }
14617   CondOpcode = Cond.getOpcode();
14618   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14619       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14620       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14621        Cond.getOperand(0).getValueType() != MVT::i8)) {
14622     SDValue LHS = Cond.getOperand(0);
14623     SDValue RHS = Cond.getOperand(1);
14624     unsigned X86Opcode;
14625     unsigned X86Cond;
14626     SDVTList VTs;
14627     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14628     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14629     // X86ISD::INC).
14630     switch (CondOpcode) {
14631     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14632     case ISD::SADDO:
14633       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14634         if (C->isOne()) {
14635           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14636           break;
14637         }
14638       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14639     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14640     case ISD::SSUBO:
14641       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14642         if (C->isOne()) {
14643           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14644           break;
14645         }
14646       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14647     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14648     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14649     default: llvm_unreachable("unexpected overflowing operator");
14650     }
14651     if (Inverted)
14652       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14653     if (CondOpcode == ISD::UMULO)
14654       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14655                           MVT::i32);
14656     else
14657       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14658
14659     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14660
14661     if (CondOpcode == ISD::UMULO)
14662       Cond = X86Op.getValue(2);
14663     else
14664       Cond = X86Op.getValue(1);
14665
14666     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14667     addTest = false;
14668   } else {
14669     unsigned CondOpc;
14670     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14671       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14672       if (CondOpc == ISD::OR) {
14673         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14674         // two branches instead of an explicit OR instruction with a
14675         // separate test.
14676         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14677             isX86LogicalCmp(Cmp)) {
14678           CC = Cond.getOperand(0).getOperand(0);
14679           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14680                               Chain, Dest, CC, Cmp);
14681           CC = Cond.getOperand(1).getOperand(0);
14682           Cond = Cmp;
14683           addTest = false;
14684         }
14685       } else { // ISD::AND
14686         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14687         // two branches instead of an explicit AND instruction with a
14688         // separate test. However, we only do this if this block doesn't
14689         // have a fall-through edge, because this requires an explicit
14690         // jmp when the condition is false.
14691         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14692             isX86LogicalCmp(Cmp) &&
14693             Op.getNode()->hasOneUse()) {
14694           X86::CondCode CCode =
14695             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14696           CCode = X86::GetOppositeBranchCondition(CCode);
14697           CC = DAG.getConstant(CCode, dl, MVT::i8);
14698           SDNode *User = *Op.getNode()->use_begin();
14699           // Look for an unconditional branch following this conditional branch.
14700           // We need this because we need to reverse the successors in order
14701           // to implement FCMP_OEQ.
14702           if (User->getOpcode() == ISD::BR) {
14703             SDValue FalseBB = User->getOperand(1);
14704             SDNode *NewBR =
14705               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14706             assert(NewBR == User);
14707             (void)NewBR;
14708             Dest = FalseBB;
14709
14710             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14711                                 Chain, Dest, CC, Cmp);
14712             X86::CondCode CCode =
14713               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14714             CCode = X86::GetOppositeBranchCondition(CCode);
14715             CC = DAG.getConstant(CCode, dl, MVT::i8);
14716             Cond = Cmp;
14717             addTest = false;
14718           }
14719         }
14720       }
14721     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14722       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14723       // It should be transformed during dag combiner except when the condition
14724       // is set by a arithmetics with overflow node.
14725       X86::CondCode CCode =
14726         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14727       CCode = X86::GetOppositeBranchCondition(CCode);
14728       CC = DAG.getConstant(CCode, dl, MVT::i8);
14729       Cond = Cond.getOperand(0).getOperand(1);
14730       addTest = false;
14731     } else if (Cond.getOpcode() == ISD::SETCC &&
14732                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14733       // For FCMP_OEQ, we can emit
14734       // two branches instead of an explicit AND instruction with a
14735       // separate test. However, we only do this if this block doesn't
14736       // have a fall-through edge, because this requires an explicit
14737       // jmp when the condition is false.
14738       if (Op.getNode()->hasOneUse()) {
14739         SDNode *User = *Op.getNode()->use_begin();
14740         // Look for an unconditional branch following this conditional branch.
14741         // We need this because we need to reverse the successors in order
14742         // to implement FCMP_OEQ.
14743         if (User->getOpcode() == ISD::BR) {
14744           SDValue FalseBB = User->getOperand(1);
14745           SDNode *NewBR =
14746             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14747           assert(NewBR == User);
14748           (void)NewBR;
14749           Dest = FalseBB;
14750
14751           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14752                                     Cond.getOperand(0), Cond.getOperand(1));
14753           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14754           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14755           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14756                               Chain, Dest, CC, Cmp);
14757           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14758           Cond = Cmp;
14759           addTest = false;
14760         }
14761       }
14762     } else if (Cond.getOpcode() == ISD::SETCC &&
14763                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14764       // For FCMP_UNE, we can emit
14765       // two branches instead of an explicit AND instruction with a
14766       // separate test. However, we only do this if this block doesn't
14767       // have a fall-through edge, because this requires an explicit
14768       // jmp when the condition is false.
14769       if (Op.getNode()->hasOneUse()) {
14770         SDNode *User = *Op.getNode()->use_begin();
14771         // Look for an unconditional branch following this conditional branch.
14772         // We need this because we need to reverse the successors in order
14773         // to implement FCMP_UNE.
14774         if (User->getOpcode() == ISD::BR) {
14775           SDValue FalseBB = User->getOperand(1);
14776           SDNode *NewBR =
14777             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14778           assert(NewBR == User);
14779           (void)NewBR;
14780
14781           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14782                                     Cond.getOperand(0), Cond.getOperand(1));
14783           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14784           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14785           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14786                               Chain, Dest, CC, Cmp);
14787           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14788           Cond = Cmp;
14789           addTest = false;
14790           Dest = FalseBB;
14791         }
14792       }
14793     }
14794   }
14795
14796   if (addTest) {
14797     // Look pass the truncate if the high bits are known zero.
14798     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14799         Cond = Cond.getOperand(0);
14800
14801     // We know the result of AND is compared against zero. Try to match
14802     // it to BT.
14803     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14804       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14805       if (NewSetCC.getNode()) {
14806         CC = NewSetCC.getOperand(0);
14807         Cond = NewSetCC.getOperand(1);
14808         addTest = false;
14809       }
14810     }
14811   }
14812
14813   if (addTest) {
14814     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14815     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14816     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14817   }
14818   Cond = ConvertCmpIfNecessary(Cond, DAG);
14819   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14820                      Chain, Dest, CC, Cond);
14821 }
14822
14823 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14824 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14825 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14826 // that the guard pages used by the OS virtual memory manager are allocated in
14827 // correct sequence.
14828 SDValue
14829 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14830                                            SelectionDAG &DAG) const {
14831   MachineFunction &MF = DAG.getMachineFunction();
14832   bool SplitStack = MF.shouldSplitStack();
14833   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14834                SplitStack;
14835   SDLoc dl(Op);
14836
14837   if (!Lower) {
14838     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14839     SDNode* Node = Op.getNode();
14840
14841     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14842     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14843         " not tell us which reg is the stack pointer!");
14844     EVT VT = Node->getValueType(0);
14845     SDValue Tmp1 = SDValue(Node, 0);
14846     SDValue Tmp2 = SDValue(Node, 1);
14847     SDValue Tmp3 = Node->getOperand(2);
14848     SDValue Chain = Tmp1.getOperand(0);
14849
14850     // Chain the dynamic stack allocation so that it doesn't modify the stack
14851     // pointer when other instructions are using the stack.
14852     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14853         SDLoc(Node));
14854
14855     SDValue Size = Tmp2.getOperand(1);
14856     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14857     Chain = SP.getValue(1);
14858     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14859     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14860     unsigned StackAlign = TFI.getStackAlignment();
14861     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14862     if (Align > StackAlign)
14863       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14864           DAG.getConstant(-(uint64_t)Align, dl, VT));
14865     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14866
14867     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14868         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14869         SDLoc(Node));
14870
14871     SDValue Ops[2] = { Tmp1, Tmp2 };
14872     return DAG.getMergeValues(Ops, dl);
14873   }
14874
14875   // Get the inputs.
14876   SDValue Chain = Op.getOperand(0);
14877   SDValue Size  = Op.getOperand(1);
14878   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14879   EVT VT = Op.getNode()->getValueType(0);
14880
14881   bool Is64Bit = Subtarget->is64Bit();
14882   MVT SPTy = getPointerTy(DAG.getDataLayout());
14883
14884   if (SplitStack) {
14885     MachineRegisterInfo &MRI = MF.getRegInfo();
14886
14887     if (Is64Bit) {
14888       // The 64 bit implementation of segmented stacks needs to clobber both r10
14889       // r11. This makes it impossible to use it along with nested parameters.
14890       const Function *F = MF.getFunction();
14891
14892       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14893            I != E; ++I)
14894         if (I->hasNestAttr())
14895           report_fatal_error("Cannot use segmented stacks with functions that "
14896                              "have nested arguments.");
14897     }
14898
14899     const TargetRegisterClass *AddrRegClass = getRegClassFor(SPTy);
14900     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14901     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14902     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14903                                 DAG.getRegister(Vreg, SPTy));
14904     SDValue Ops1[2] = { Value, Chain };
14905     return DAG.getMergeValues(Ops1, dl);
14906   } else {
14907     SDValue Flag;
14908     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14909
14910     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14911     Flag = Chain.getValue(1);
14912     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14913
14914     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14915
14916     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14917     unsigned SPReg = RegInfo->getStackRegister();
14918     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14919     Chain = SP.getValue(1);
14920
14921     if (Align) {
14922       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14923                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14924       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14925     }
14926
14927     SDValue Ops1[2] = { SP, Chain };
14928     return DAG.getMergeValues(Ops1, dl);
14929   }
14930 }
14931
14932 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14933   MachineFunction &MF = DAG.getMachineFunction();
14934   auto PtrVT = getPointerTy(MF.getDataLayout());
14935   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14936
14937   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14938   SDLoc DL(Op);
14939
14940   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14941     // vastart just stores the address of the VarArgsFrameIndex slot into the
14942     // memory location argument.
14943     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14944     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14945                         MachinePointerInfo(SV), false, false, 0);
14946   }
14947
14948   // __va_list_tag:
14949   //   gp_offset         (0 - 6 * 8)
14950   //   fp_offset         (48 - 48 + 8 * 16)
14951   //   overflow_arg_area (point to parameters coming in memory).
14952   //   reg_save_area
14953   SmallVector<SDValue, 8> MemOps;
14954   SDValue FIN = Op.getOperand(1);
14955   // Store gp_offset
14956   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14957                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14958                                                DL, MVT::i32),
14959                                FIN, MachinePointerInfo(SV), false, false, 0);
14960   MemOps.push_back(Store);
14961
14962   // Store fp_offset
14963   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14964   Store = DAG.getStore(Op.getOperand(0), DL,
14965                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14966                                        MVT::i32),
14967                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14968   MemOps.push_back(Store);
14969
14970   // Store ptr to overflow_arg_area
14971   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(4, DL));
14972   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(), PtrVT);
14973   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14974                        MachinePointerInfo(SV, 8),
14975                        false, false, 0);
14976   MemOps.push_back(Store);
14977
14978   // Store ptr to reg_save_area.
14979   FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getIntPtrConstant(8, DL));
14980   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), PtrVT);
14981   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14982                        MachinePointerInfo(SV, 16), false, false, 0);
14983   MemOps.push_back(Store);
14984   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14985 }
14986
14987 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14988   assert(Subtarget->is64Bit() &&
14989          "LowerVAARG only handles 64-bit va_arg!");
14990   assert((Subtarget->isTargetLinux() ||
14991           Subtarget->isTargetDarwin()) &&
14992           "Unhandled target in LowerVAARG");
14993   assert(Op.getNode()->getNumOperands() == 4);
14994   SDValue Chain = Op.getOperand(0);
14995   SDValue SrcPtr = Op.getOperand(1);
14996   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14997   unsigned Align = Op.getConstantOperandVal(3);
14998   SDLoc dl(Op);
14999
15000   EVT ArgVT = Op.getNode()->getValueType(0);
15001   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
15002   uint32_t ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
15003   uint8_t ArgMode;
15004
15005   // Decide which area this value should be read from.
15006   // TODO: Implement the AMD64 ABI in its entirety. This simple
15007   // selection mechanism works only for the basic types.
15008   if (ArgVT == MVT::f80) {
15009     llvm_unreachable("va_arg for f80 not yet implemented");
15010   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
15011     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
15012   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
15013     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
15014   } else {
15015     llvm_unreachable("Unhandled argument type in LowerVAARG");
15016   }
15017
15018   if (ArgMode == 2) {
15019     // Sanity Check: Make sure using fp_offset makes sense.
15020     assert(!Subtarget->useSoftFloat() &&
15021            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
15022                Attribute::NoImplicitFloat)) &&
15023            Subtarget->hasSSE1());
15024   }
15025
15026   // Insert VAARG_64 node into the DAG
15027   // VAARG_64 returns two values: Variable Argument Address, Chain
15028   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
15029                        DAG.getConstant(ArgMode, dl, MVT::i8),
15030                        DAG.getConstant(Align, dl, MVT::i32)};
15031   SDVTList VTs = DAG.getVTList(getPointerTy(DAG.getDataLayout()), MVT::Other);
15032   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
15033                                           VTs, InstOps, MVT::i64,
15034                                           MachinePointerInfo(SV),
15035                                           /*Align=*/0,
15036                                           /*Volatile=*/false,
15037                                           /*ReadMem=*/true,
15038                                           /*WriteMem=*/true);
15039   Chain = VAARG.getValue(1);
15040
15041   // Load the next argument and return it
15042   return DAG.getLoad(ArgVT, dl,
15043                      Chain,
15044                      VAARG,
15045                      MachinePointerInfo(),
15046                      false, false, false, 0);
15047 }
15048
15049 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
15050                            SelectionDAG &DAG) {
15051   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
15052   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
15053   SDValue Chain = Op.getOperand(0);
15054   SDValue DstPtr = Op.getOperand(1);
15055   SDValue SrcPtr = Op.getOperand(2);
15056   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
15057   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
15058   SDLoc DL(Op);
15059
15060   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
15061                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
15062                        false, false,
15063                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
15064 }
15065
15066 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
15067 // amount is a constant. Takes immediate version of shift as input.
15068 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
15069                                           SDValue SrcOp, uint64_t ShiftAmt,
15070                                           SelectionDAG &DAG) {
15071   MVT ElementType = VT.getVectorElementType();
15072
15073   // Fold this packed shift into its first operand if ShiftAmt is 0.
15074   if (ShiftAmt == 0)
15075     return SrcOp;
15076
15077   // Check for ShiftAmt >= element width
15078   if (ShiftAmt >= ElementType.getSizeInBits()) {
15079     if (Opc == X86ISD::VSRAI)
15080       ShiftAmt = ElementType.getSizeInBits() - 1;
15081     else
15082       return DAG.getConstant(0, dl, VT);
15083   }
15084
15085   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
15086          && "Unknown target vector shift-by-constant node");
15087
15088   // Fold this packed vector shift into a build vector if SrcOp is a
15089   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
15090   if (VT == SrcOp.getSimpleValueType() &&
15091       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
15092     SmallVector<SDValue, 8> Elts;
15093     unsigned NumElts = SrcOp->getNumOperands();
15094     ConstantSDNode *ND;
15095
15096     switch(Opc) {
15097     default: llvm_unreachable(nullptr);
15098     case X86ISD::VSHLI:
15099       for (unsigned i=0; i!=NumElts; ++i) {
15100         SDValue CurrentOp = SrcOp->getOperand(i);
15101         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15102           Elts.push_back(CurrentOp);
15103           continue;
15104         }
15105         ND = cast<ConstantSDNode>(CurrentOp);
15106         const APInt &C = ND->getAPIntValue();
15107         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
15108       }
15109       break;
15110     case X86ISD::VSRLI:
15111       for (unsigned i=0; i!=NumElts; ++i) {
15112         SDValue CurrentOp = SrcOp->getOperand(i);
15113         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15114           Elts.push_back(CurrentOp);
15115           continue;
15116         }
15117         ND = cast<ConstantSDNode>(CurrentOp);
15118         const APInt &C = ND->getAPIntValue();
15119         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
15120       }
15121       break;
15122     case X86ISD::VSRAI:
15123       for (unsigned i=0; i!=NumElts; ++i) {
15124         SDValue CurrentOp = SrcOp->getOperand(i);
15125         if (CurrentOp->getOpcode() == ISD::UNDEF) {
15126           Elts.push_back(CurrentOp);
15127           continue;
15128         }
15129         ND = cast<ConstantSDNode>(CurrentOp);
15130         const APInt &C = ND->getAPIntValue();
15131         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
15132       }
15133       break;
15134     }
15135
15136     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
15137   }
15138
15139   return DAG.getNode(Opc, dl, VT, SrcOp,
15140                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
15141 }
15142
15143 // getTargetVShiftNode - Handle vector element shifts where the shift amount
15144 // may or may not be a constant. Takes immediate version of shift as input.
15145 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
15146                                    SDValue SrcOp, SDValue ShAmt,
15147                                    SelectionDAG &DAG) {
15148   MVT SVT = ShAmt.getSimpleValueType();
15149   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
15150
15151   // Catch shift-by-constant.
15152   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
15153     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
15154                                       CShAmt->getZExtValue(), DAG);
15155
15156   // Change opcode to non-immediate version
15157   switch (Opc) {
15158     default: llvm_unreachable("Unknown target vector shift node");
15159     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
15160     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
15161     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
15162   }
15163
15164   const X86Subtarget &Subtarget =
15165       static_cast<const X86Subtarget &>(DAG.getSubtarget());
15166   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
15167       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
15168     // Let the shuffle legalizer expand this shift amount node.
15169     SDValue Op0 = ShAmt.getOperand(0);
15170     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
15171     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
15172   } else {
15173     // Need to build a vector containing shift amount.
15174     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
15175     SmallVector<SDValue, 4> ShOps;
15176     ShOps.push_back(ShAmt);
15177     if (SVT == MVT::i32) {
15178       ShOps.push_back(DAG.getConstant(0, dl, SVT));
15179       ShOps.push_back(DAG.getUNDEF(SVT));
15180     }
15181     ShOps.push_back(DAG.getUNDEF(SVT));
15182
15183     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
15184     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
15185   }
15186
15187   // The return type has to be a 128-bit type with the same element
15188   // type as the input type.
15189   MVT EltVT = VT.getVectorElementType();
15190   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
15191
15192   ShAmt = DAG.getBitcast(ShVT, ShAmt);
15193   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
15194 }
15195
15196 /// \brief Return (and \p Op, \p Mask) for compare instructions or
15197 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
15198 /// necessary casting for \p Mask when lowering masking intrinsics.
15199 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
15200                                     SDValue PreservedSrc,
15201                                     const X86Subtarget *Subtarget,
15202                                     SelectionDAG &DAG) {
15203     EVT VT = Op.getValueType();
15204     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15205                                   MVT::i1, VT.getVectorNumElements());
15206     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15207                                      Mask.getValueType().getSizeInBits());
15208     SDLoc dl(Op);
15209
15210     assert(MaskVT.isSimple() && "invalid mask type");
15211
15212     if (isAllOnes(Mask))
15213       return Op;
15214
15215     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15216     // are extracted by EXTRACT_SUBVECTOR.
15217     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15218                                 DAG.getBitcast(BitcastVT, Mask),
15219                                 DAG.getIntPtrConstant(0, dl));
15220
15221     switch (Op.getOpcode()) {
15222       default: break;
15223       case X86ISD::PCMPEQM:
15224       case X86ISD::PCMPGTM:
15225       case X86ISD::CMPM:
15226       case X86ISD::CMPMU:
15227         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15228     }
15229     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15230       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15231     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15232 }
15233
15234 /// \brief Creates an SDNode for a predicated scalar operation.
15235 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15236 /// The mask is comming as MVT::i8 and it should be truncated
15237 /// to MVT::i1 while lowering masking intrinsics.
15238 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15239 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15240 /// a scalar instruction.
15241 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15242                                     SDValue PreservedSrc,
15243                                     const X86Subtarget *Subtarget,
15244                                     SelectionDAG &DAG) {
15245     if (isAllOnes(Mask))
15246       return Op;
15247
15248     EVT VT = Op.getValueType();
15249     SDLoc dl(Op);
15250     // The mask should be of type MVT::i1
15251     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15252
15253     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15254       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15255     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15256 }
15257
15258 static int getSEHRegistrationNodeSize(const Function *Fn) {
15259   if (!Fn->hasPersonalityFn())
15260     report_fatal_error(
15261         "querying registration node size for function without personality");
15262   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15263   // WinEHStatePass for the full struct definition.
15264   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15265   case EHPersonality::MSVC_X86SEH: return 24;
15266   case EHPersonality::MSVC_CXX: return 16;
15267   default: break;
15268   }
15269   report_fatal_error("can only recover FP for MSVC EH personality functions");
15270 }
15271
15272 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15273 /// function or when returning to a parent frame after catching an exception, we
15274 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15275 /// Here's the math:
15276 ///   RegNodeBase = EntryEBP - RegNodeSize
15277 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15278 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15279 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15280 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15281                                    SDValue EntryEBP) {
15282   MachineFunction &MF = DAG.getMachineFunction();
15283   SDLoc dl;
15284
15285   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15286   MVT PtrVT = TLI.getPointerTy(DAG.getDataLayout());
15287
15288   // It's possible that the parent function no longer has a personality function
15289   // if the exceptional code was optimized away, in which case we just return
15290   // the incoming EBP.
15291   if (!Fn->hasPersonalityFn())
15292     return EntryEBP;
15293
15294   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
15295
15296   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15297   // registration.
15298   MCSymbol *OffsetSym =
15299       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15300           GlobalValue::getRealLinkageName(Fn->getName()));
15301   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15302   SDValue RegNodeFrameOffset =
15303       DAG.getNode(ISD::LOCAL_RECOVER, dl, PtrVT, OffsetSymVal);
15304
15305   // RegNodeBase = EntryEBP - RegNodeSize
15306   // ParentFP = RegNodeBase - RegNodeFrameOffset
15307   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15308                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15309   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15310 }
15311
15312 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15313                                        SelectionDAG &DAG) {
15314   SDLoc dl(Op);
15315   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15316   EVT VT = Op.getValueType();
15317   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15318   if (IntrData) {
15319     switch(IntrData->Type) {
15320     case INTR_TYPE_1OP:
15321       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15322     case INTR_TYPE_2OP:
15323       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15324         Op.getOperand(2));
15325     case INTR_TYPE_3OP:
15326       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15327         Op.getOperand(2), Op.getOperand(3));
15328     case INTR_TYPE_4OP:
15329       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15330         Op.getOperand(2), Op.getOperand(3), Op.getOperand(4));
15331     case INTR_TYPE_1OP_MASK_RM: {
15332       SDValue Src = Op.getOperand(1);
15333       SDValue PassThru = Op.getOperand(2);
15334       SDValue Mask = Op.getOperand(3);
15335       SDValue RoundingMode;
15336       if (Op.getNumOperands() == 4)
15337         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15338       else
15339         RoundingMode = Op.getOperand(4);
15340       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15341       if (IntrWithRoundingModeOpcode != 0) {
15342         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15343         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15344           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15345                                       dl, Op.getValueType(), Src, RoundingMode),
15346                                       Mask, PassThru, Subtarget, DAG);
15347       }
15348       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15349                                               RoundingMode),
15350                                   Mask, PassThru, Subtarget, DAG);
15351     }
15352     case INTR_TYPE_1OP_MASK: {
15353       SDValue Src = Op.getOperand(1);
15354       SDValue Passthru = Op.getOperand(2);
15355       SDValue Mask = Op.getOperand(3);
15356       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15357                                   Mask, Passthru, Subtarget, DAG);
15358     }
15359     case INTR_TYPE_SCALAR_MASK_RM: {
15360       SDValue Src1 = Op.getOperand(1);
15361       SDValue Src2 = Op.getOperand(2);
15362       SDValue Src0 = Op.getOperand(3);
15363       SDValue Mask = Op.getOperand(4);
15364       // There are 2 kinds of intrinsics in this group:
15365       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15366       // (2) With rounding mode and sae - 7 operands.
15367       if (Op.getNumOperands() == 6) {
15368         SDValue Sae  = Op.getOperand(5);
15369         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15370         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15371                                                 Sae),
15372                                     Mask, Src0, Subtarget, DAG);
15373       }
15374       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15375       SDValue RoundingMode  = Op.getOperand(5);
15376       SDValue Sae  = Op.getOperand(6);
15377       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15378                                               RoundingMode, Sae),
15379                                   Mask, Src0, Subtarget, DAG);
15380     }
15381     case INTR_TYPE_2OP_MASK: {
15382       SDValue Src1 = Op.getOperand(1);
15383       SDValue Src2 = Op.getOperand(2);
15384       SDValue PassThru = Op.getOperand(3);
15385       SDValue Mask = Op.getOperand(4);
15386       // We specify 2 possible opcodes for intrinsics with rounding modes.
15387       // First, we check if the intrinsic may have non-default rounding mode,
15388       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15389       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15390       if (IntrWithRoundingModeOpcode != 0) {
15391         SDValue Rnd = Op.getOperand(5);
15392         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15393         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15394           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15395                                       dl, Op.getValueType(),
15396                                       Src1, Src2, Rnd),
15397                                       Mask, PassThru, Subtarget, DAG);
15398         }
15399       }
15400       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15401                                               Src1,Src2),
15402                                   Mask, PassThru, Subtarget, DAG);
15403     }
15404     case INTR_TYPE_2OP_MASK_RM: {
15405       SDValue Src1 = Op.getOperand(1);
15406       SDValue Src2 = Op.getOperand(2);
15407       SDValue PassThru = Op.getOperand(3);
15408       SDValue Mask = Op.getOperand(4);
15409       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15410       // First, we check if the intrinsic have rounding mode (6 operands),
15411       // if not, we set rounding mode to "current".
15412       SDValue Rnd;
15413       if (Op.getNumOperands() == 6)
15414         Rnd = Op.getOperand(5);
15415       else
15416         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15417       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15418                                               Src1, Src2, Rnd),
15419                                   Mask, PassThru, Subtarget, DAG);
15420     }
15421     case INTR_TYPE_3OP_MASK: {
15422       SDValue Src1 = Op.getOperand(1);
15423       SDValue Src2 = Op.getOperand(2);
15424       SDValue Src3 = Op.getOperand(3);
15425       SDValue PassThru = Op.getOperand(4);
15426       SDValue Mask = Op.getOperand(5);
15427       // We specify 2 possible opcodes for intrinsics with rounding modes.
15428       // First, we check if the intrinsic may have non-default rounding mode,
15429       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15430       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15431       if (IntrWithRoundingModeOpcode != 0) {
15432         SDValue Rnd = Op.getOperand(6);
15433         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15434         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15435           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15436                                       dl, Op.getValueType(),
15437                                       Src1, Src2, Src3, Rnd),
15438                                       Mask, PassThru, Subtarget, DAG);
15439         }
15440       }
15441       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15442                                               Src1, Src2, Src3),
15443                                   Mask, PassThru, Subtarget, DAG);
15444     }
15445     case VPERM_3OP_MASKZ:
15446     case VPERM_3OP_MASK:
15447     case FMA_OP_MASK3:
15448     case FMA_OP_MASKZ:
15449     case FMA_OP_MASK: {
15450       SDValue Src1 = Op.getOperand(1);
15451       SDValue Src2 = Op.getOperand(2);
15452       SDValue Src3 = Op.getOperand(3);
15453       SDValue Mask = Op.getOperand(4);
15454       EVT VT = Op.getValueType();
15455       SDValue PassThru = SDValue();
15456
15457       // set PassThru element
15458       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15459         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15460       else if (IntrData->Type == FMA_OP_MASK3)
15461         PassThru = Src3;
15462       else
15463         PassThru = Src1;
15464
15465       // We specify 2 possible opcodes for intrinsics with rounding modes.
15466       // First, we check if the intrinsic may have non-default rounding mode,
15467       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15468       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15469       if (IntrWithRoundingModeOpcode != 0) {
15470         SDValue Rnd = Op.getOperand(5);
15471         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15472             X86::STATIC_ROUNDING::CUR_DIRECTION)
15473           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15474                                                   dl, Op.getValueType(),
15475                                                   Src1, Src2, Src3, Rnd),
15476                                       Mask, PassThru, Subtarget, DAG);
15477       }
15478       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15479                                               dl, Op.getValueType(),
15480                                               Src1, Src2, Src3),
15481                                   Mask, PassThru, Subtarget, DAG);
15482     }
15483     case CMP_MASK:
15484     case CMP_MASK_CC: {
15485       // Comparison intrinsics with masks.
15486       // Example of transformation:
15487       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15488       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15489       // (i8 (bitcast
15490       //   (v8i1 (insert_subvector undef,
15491       //           (v2i1 (and (PCMPEQM %a, %b),
15492       //                      (extract_subvector
15493       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15494       EVT VT = Op.getOperand(1).getValueType();
15495       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15496                                     VT.getVectorNumElements());
15497       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15498       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15499                                        Mask.getValueType().getSizeInBits());
15500       SDValue Cmp;
15501       if (IntrData->Type == CMP_MASK_CC) {
15502         SDValue CC = Op.getOperand(3);
15503         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15504         // We specify 2 possible opcodes for intrinsics with rounding modes.
15505         // First, we check if the intrinsic may have non-default rounding mode,
15506         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15507         if (IntrData->Opc1 != 0) {
15508           SDValue Rnd = Op.getOperand(5);
15509           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15510               X86::STATIC_ROUNDING::CUR_DIRECTION)
15511             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15512                               Op.getOperand(2), CC, Rnd);
15513         }
15514         //default rounding mode
15515         if(!Cmp.getNode())
15516             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15517                               Op.getOperand(2), CC);
15518
15519       } else {
15520         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15521         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15522                           Op.getOperand(2));
15523       }
15524       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15525                                              DAG.getTargetConstant(0, dl,
15526                                                                    MaskVT),
15527                                              Subtarget, DAG);
15528       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15529                                 DAG.getUNDEF(BitcastVT), CmpMask,
15530                                 DAG.getIntPtrConstant(0, dl));
15531       return DAG.getBitcast(Op.getValueType(), Res);
15532     }
15533     case COMI: { // Comparison intrinsics
15534       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15535       SDValue LHS = Op.getOperand(1);
15536       SDValue RHS = Op.getOperand(2);
15537       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15538       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15539       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15540       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15541                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15542       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15543     }
15544     case VSHIFT:
15545       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15546                                  Op.getOperand(1), Op.getOperand(2), DAG);
15547     case VSHIFT_MASK:
15548       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15549                                                       Op.getSimpleValueType(),
15550                                                       Op.getOperand(1),
15551                                                       Op.getOperand(2), DAG),
15552                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15553                                   DAG);
15554     case COMPRESS_EXPAND_IN_REG: {
15555       SDValue Mask = Op.getOperand(3);
15556       SDValue DataToCompress = Op.getOperand(1);
15557       SDValue PassThru = Op.getOperand(2);
15558       if (isAllOnes(Mask)) // return data as is
15559         return Op.getOperand(1);
15560
15561       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15562                                               DataToCompress),
15563                                   Mask, PassThru, Subtarget, DAG);
15564     }
15565     case BLEND: {
15566       SDValue Mask = Op.getOperand(3);
15567       EVT VT = Op.getValueType();
15568       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15569                                     VT.getVectorNumElements());
15570       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15571                                        Mask.getValueType().getSizeInBits());
15572       SDLoc dl(Op);
15573       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15574                                   DAG.getBitcast(BitcastVT, Mask),
15575                                   DAG.getIntPtrConstant(0, dl));
15576       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15577                          Op.getOperand(2));
15578     }
15579     default:
15580       break;
15581     }
15582   }
15583
15584   switch (IntNo) {
15585   default: return SDValue();    // Don't custom lower most intrinsics.
15586
15587   case Intrinsic::x86_avx2_permd:
15588   case Intrinsic::x86_avx2_permps:
15589     // Operands intentionally swapped. Mask is last operand to intrinsic,
15590     // but second operand for node/instruction.
15591     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15592                        Op.getOperand(2), Op.getOperand(1));
15593
15594   // ptest and testp intrinsics. The intrinsic these come from are designed to
15595   // return an integer value, not just an instruction so lower it to the ptest
15596   // or testp pattern and a setcc for the result.
15597   case Intrinsic::x86_sse41_ptestz:
15598   case Intrinsic::x86_sse41_ptestc:
15599   case Intrinsic::x86_sse41_ptestnzc:
15600   case Intrinsic::x86_avx_ptestz_256:
15601   case Intrinsic::x86_avx_ptestc_256:
15602   case Intrinsic::x86_avx_ptestnzc_256:
15603   case Intrinsic::x86_avx_vtestz_ps:
15604   case Intrinsic::x86_avx_vtestc_ps:
15605   case Intrinsic::x86_avx_vtestnzc_ps:
15606   case Intrinsic::x86_avx_vtestz_pd:
15607   case Intrinsic::x86_avx_vtestc_pd:
15608   case Intrinsic::x86_avx_vtestnzc_pd:
15609   case Intrinsic::x86_avx_vtestz_ps_256:
15610   case Intrinsic::x86_avx_vtestc_ps_256:
15611   case Intrinsic::x86_avx_vtestnzc_ps_256:
15612   case Intrinsic::x86_avx_vtestz_pd_256:
15613   case Intrinsic::x86_avx_vtestc_pd_256:
15614   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15615     bool IsTestPacked = false;
15616     unsigned X86CC;
15617     switch (IntNo) {
15618     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15619     case Intrinsic::x86_avx_vtestz_ps:
15620     case Intrinsic::x86_avx_vtestz_pd:
15621     case Intrinsic::x86_avx_vtestz_ps_256:
15622     case Intrinsic::x86_avx_vtestz_pd_256:
15623       IsTestPacked = true; // Fallthrough
15624     case Intrinsic::x86_sse41_ptestz:
15625     case Intrinsic::x86_avx_ptestz_256:
15626       // ZF = 1
15627       X86CC = X86::COND_E;
15628       break;
15629     case Intrinsic::x86_avx_vtestc_ps:
15630     case Intrinsic::x86_avx_vtestc_pd:
15631     case Intrinsic::x86_avx_vtestc_ps_256:
15632     case Intrinsic::x86_avx_vtestc_pd_256:
15633       IsTestPacked = true; // Fallthrough
15634     case Intrinsic::x86_sse41_ptestc:
15635     case Intrinsic::x86_avx_ptestc_256:
15636       // CF = 1
15637       X86CC = X86::COND_B;
15638       break;
15639     case Intrinsic::x86_avx_vtestnzc_ps:
15640     case Intrinsic::x86_avx_vtestnzc_pd:
15641     case Intrinsic::x86_avx_vtestnzc_ps_256:
15642     case Intrinsic::x86_avx_vtestnzc_pd_256:
15643       IsTestPacked = true; // Fallthrough
15644     case Intrinsic::x86_sse41_ptestnzc:
15645     case Intrinsic::x86_avx_ptestnzc_256:
15646       // ZF and CF = 0
15647       X86CC = X86::COND_A;
15648       break;
15649     }
15650
15651     SDValue LHS = Op.getOperand(1);
15652     SDValue RHS = Op.getOperand(2);
15653     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15654     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15655     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15656     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15657     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15658   }
15659   case Intrinsic::x86_avx512_kortestz_w:
15660   case Intrinsic::x86_avx512_kortestc_w: {
15661     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15662     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15663     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15664     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15665     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15666     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15667     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15668   }
15669
15670   case Intrinsic::x86_sse42_pcmpistria128:
15671   case Intrinsic::x86_sse42_pcmpestria128:
15672   case Intrinsic::x86_sse42_pcmpistric128:
15673   case Intrinsic::x86_sse42_pcmpestric128:
15674   case Intrinsic::x86_sse42_pcmpistrio128:
15675   case Intrinsic::x86_sse42_pcmpestrio128:
15676   case Intrinsic::x86_sse42_pcmpistris128:
15677   case Intrinsic::x86_sse42_pcmpestris128:
15678   case Intrinsic::x86_sse42_pcmpistriz128:
15679   case Intrinsic::x86_sse42_pcmpestriz128: {
15680     unsigned Opcode;
15681     unsigned X86CC;
15682     switch (IntNo) {
15683     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15684     case Intrinsic::x86_sse42_pcmpistria128:
15685       Opcode = X86ISD::PCMPISTRI;
15686       X86CC = X86::COND_A;
15687       break;
15688     case Intrinsic::x86_sse42_pcmpestria128:
15689       Opcode = X86ISD::PCMPESTRI;
15690       X86CC = X86::COND_A;
15691       break;
15692     case Intrinsic::x86_sse42_pcmpistric128:
15693       Opcode = X86ISD::PCMPISTRI;
15694       X86CC = X86::COND_B;
15695       break;
15696     case Intrinsic::x86_sse42_pcmpestric128:
15697       Opcode = X86ISD::PCMPESTRI;
15698       X86CC = X86::COND_B;
15699       break;
15700     case Intrinsic::x86_sse42_pcmpistrio128:
15701       Opcode = X86ISD::PCMPISTRI;
15702       X86CC = X86::COND_O;
15703       break;
15704     case Intrinsic::x86_sse42_pcmpestrio128:
15705       Opcode = X86ISD::PCMPESTRI;
15706       X86CC = X86::COND_O;
15707       break;
15708     case Intrinsic::x86_sse42_pcmpistris128:
15709       Opcode = X86ISD::PCMPISTRI;
15710       X86CC = X86::COND_S;
15711       break;
15712     case Intrinsic::x86_sse42_pcmpestris128:
15713       Opcode = X86ISD::PCMPESTRI;
15714       X86CC = X86::COND_S;
15715       break;
15716     case Intrinsic::x86_sse42_pcmpistriz128:
15717       Opcode = X86ISD::PCMPISTRI;
15718       X86CC = X86::COND_E;
15719       break;
15720     case Intrinsic::x86_sse42_pcmpestriz128:
15721       Opcode = X86ISD::PCMPESTRI;
15722       X86CC = X86::COND_E;
15723       break;
15724     }
15725     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15726     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15727     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15728     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15729                                 DAG.getConstant(X86CC, dl, MVT::i8),
15730                                 SDValue(PCMP.getNode(), 1));
15731     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15732   }
15733
15734   case Intrinsic::x86_sse42_pcmpistri128:
15735   case Intrinsic::x86_sse42_pcmpestri128: {
15736     unsigned Opcode;
15737     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15738       Opcode = X86ISD::PCMPISTRI;
15739     else
15740       Opcode = X86ISD::PCMPESTRI;
15741
15742     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15743     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15744     return DAG.getNode(Opcode, dl, VTs, NewOps);
15745   }
15746
15747   case Intrinsic::x86_seh_lsda: {
15748     // Compute the symbol for the LSDA. We know it'll get emitted later.
15749     MachineFunction &MF = DAG.getMachineFunction();
15750     SDValue Op1 = Op.getOperand(1);
15751     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15752     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15753         GlobalValue::getRealLinkageName(Fn->getName()));
15754
15755     // Generate a simple absolute symbol reference. This intrinsic is only
15756     // supported on 32-bit Windows, which isn't PIC.
15757     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15758     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15759   }
15760
15761   case Intrinsic::x86_seh_recoverfp: {
15762     SDValue FnOp = Op.getOperand(1);
15763     SDValue IncomingFPOp = Op.getOperand(2);
15764     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15765     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15766     if (!Fn)
15767       report_fatal_error(
15768           "llvm.x86.seh.recoverfp must take a function as the first argument");
15769     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15770   }
15771
15772   case Intrinsic::localaddress: {
15773     // Returns one of the stack, base, or frame pointer registers, depending on
15774     // which is used to reference local variables.
15775     MachineFunction &MF = DAG.getMachineFunction();
15776     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15777     unsigned Reg;
15778     if (RegInfo->hasBasePointer(MF))
15779       Reg = RegInfo->getBaseRegister();
15780     else // This function handles the SP or FP case.
15781       Reg = RegInfo->getPtrSizedFrameRegister(MF);
15782     return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg, VT);
15783   }
15784   }
15785 }
15786
15787 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15788                               SDValue Src, SDValue Mask, SDValue Base,
15789                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15790                               const X86Subtarget * Subtarget) {
15791   SDLoc dl(Op);
15792   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15793   if (!C)
15794     llvm_unreachable("Invalid scale type");
15795   unsigned ScaleVal = C->getZExtValue();
15796   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15797     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15798
15799   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15800   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15801                              Index.getSimpleValueType().getVectorNumElements());
15802   SDValue MaskInReg;
15803   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15804   if (MaskC)
15805     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15806   else {
15807     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15808                                      Mask.getValueType().getSizeInBits());
15809
15810     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15811     // are extracted by EXTRACT_SUBVECTOR.
15812     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15813                             DAG.getBitcast(BitcastVT, Mask),
15814                             DAG.getIntPtrConstant(0, dl));
15815   }
15816   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15817   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15818   SDValue Segment = DAG.getRegister(0, MVT::i32);
15819   if (Src.getOpcode() == ISD::UNDEF)
15820     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15821   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15822   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15823   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15824   return DAG.getMergeValues(RetOps, dl);
15825 }
15826
15827 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15828                                SDValue Src, SDValue Mask, SDValue Base,
15829                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15830   SDLoc dl(Op);
15831   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15832   if (!C)
15833     llvm_unreachable("Invalid scale type");
15834   unsigned ScaleVal = C->getZExtValue();
15835   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15836     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15837
15838   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15839   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15840   SDValue Segment = DAG.getRegister(0, MVT::i32);
15841   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15842                              Index.getSimpleValueType().getVectorNumElements());
15843   SDValue MaskInReg;
15844   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15845   if (MaskC)
15846     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15847   else {
15848     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15849                                      Mask.getValueType().getSizeInBits());
15850
15851     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15852     // are extracted by EXTRACT_SUBVECTOR.
15853     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15854                             DAG.getBitcast(BitcastVT, Mask),
15855                             DAG.getIntPtrConstant(0, dl));
15856   }
15857   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15858   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15859   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15860   return SDValue(Res, 1);
15861 }
15862
15863 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15864                                SDValue Mask, SDValue Base, SDValue Index,
15865                                SDValue ScaleOp, SDValue Chain) {
15866   SDLoc dl(Op);
15867   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15868   assert(C && "Invalid scale type");
15869   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15870   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15871   SDValue Segment = DAG.getRegister(0, MVT::i32);
15872   EVT MaskVT =
15873     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15874   SDValue MaskInReg;
15875   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15876   if (MaskC)
15877     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15878   else
15879     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15880   //SDVTList VTs = DAG.getVTList(MVT::Other);
15881   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15882   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15883   return SDValue(Res, 0);
15884 }
15885
15886 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15887 // read performance monitor counters (x86_rdpmc).
15888 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15889                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15890                               SmallVectorImpl<SDValue> &Results) {
15891   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15892   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15893   SDValue LO, HI;
15894
15895   // The ECX register is used to select the index of the performance counter
15896   // to read.
15897   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15898                                    N->getOperand(2));
15899   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15900
15901   // Reads the content of a 64-bit performance counter and returns it in the
15902   // registers EDX:EAX.
15903   if (Subtarget->is64Bit()) {
15904     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15905     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15906                             LO.getValue(2));
15907   } else {
15908     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15909     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15910                             LO.getValue(2));
15911   }
15912   Chain = HI.getValue(1);
15913
15914   if (Subtarget->is64Bit()) {
15915     // The EAX register is loaded with the low-order 32 bits. The EDX register
15916     // is loaded with the supported high-order bits of the counter.
15917     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15918                               DAG.getConstant(32, DL, MVT::i8));
15919     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15920     Results.push_back(Chain);
15921     return;
15922   }
15923
15924   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15925   SDValue Ops[] = { LO, HI };
15926   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15927   Results.push_back(Pair);
15928   Results.push_back(Chain);
15929 }
15930
15931 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15932 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15933 // also used to custom lower READCYCLECOUNTER nodes.
15934 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15935                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15936                               SmallVectorImpl<SDValue> &Results) {
15937   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15938   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15939   SDValue LO, HI;
15940
15941   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15942   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15943   // and the EAX register is loaded with the low-order 32 bits.
15944   if (Subtarget->is64Bit()) {
15945     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15946     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15947                             LO.getValue(2));
15948   } else {
15949     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15950     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15951                             LO.getValue(2));
15952   }
15953   SDValue Chain = HI.getValue(1);
15954
15955   if (Opcode == X86ISD::RDTSCP_DAG) {
15956     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15957
15958     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15959     // the ECX register. Add 'ecx' explicitly to the chain.
15960     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15961                                      HI.getValue(2));
15962     // Explicitly store the content of ECX at the location passed in input
15963     // to the 'rdtscp' intrinsic.
15964     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15965                          MachinePointerInfo(), false, false, 0);
15966   }
15967
15968   if (Subtarget->is64Bit()) {
15969     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15970     // the EAX register is loaded with the low-order 32 bits.
15971     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15972                               DAG.getConstant(32, DL, MVT::i8));
15973     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15974     Results.push_back(Chain);
15975     return;
15976   }
15977
15978   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15979   SDValue Ops[] = { LO, HI };
15980   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15981   Results.push_back(Pair);
15982   Results.push_back(Chain);
15983 }
15984
15985 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15986                                      SelectionDAG &DAG) {
15987   SmallVector<SDValue, 2> Results;
15988   SDLoc DL(Op);
15989   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15990                           Results);
15991   return DAG.getMergeValues(Results, DL);
15992 }
15993
15994 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15995                                     SelectionDAG &DAG) {
15996   MachineFunction &MF = DAG.getMachineFunction();
15997   const Function *Fn = MF.getFunction();
15998   SDLoc dl(Op);
15999   SDValue Chain = Op.getOperand(0);
16000
16001   assert(Subtarget->getFrameLowering()->hasFP(MF) &&
16002          "using llvm.x86.seh.restoreframe requires a frame pointer");
16003
16004   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
16005   MVT VT = TLI.getPointerTy(DAG.getDataLayout());
16006
16007   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16008   unsigned FrameReg =
16009       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16010   unsigned SPReg = RegInfo->getStackRegister();
16011   unsigned SlotSize = RegInfo->getSlotSize();
16012
16013   // Get incoming EBP.
16014   SDValue IncomingEBP =
16015       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
16016
16017   // SP is saved in the first field of every registration node, so load
16018   // [EBP-RegNodeSize] into SP.
16019   int RegNodeSize = getSEHRegistrationNodeSize(Fn);
16020   SDValue SPAddr = DAG.getNode(ISD::ADD, dl, VT, IncomingEBP,
16021                                DAG.getConstant(-RegNodeSize, dl, VT));
16022   SDValue NewSP =
16023       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
16024                   false, VT.getScalarSizeInBits() / 8);
16025   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
16026
16027   if (!RegInfo->needsStackRealignment(MF)) {
16028     // Adjust EBP to point back to the original frame position.
16029     SDValue NewFP = recoverFramePointer(DAG, Fn, IncomingEBP);
16030     Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
16031   } else {
16032     assert(RegInfo->hasBasePointer(MF) &&
16033            "functions with Win32 EH must use frame or base pointer register");
16034
16035     // Reload the base pointer (ESI) with the adjusted incoming EBP.
16036     SDValue NewBP = recoverFramePointer(DAG, Fn, IncomingEBP);
16037     Chain = DAG.getCopyToReg(Chain, dl, RegInfo->getBaseRegister(), NewBP);
16038
16039     // Reload the spilled EBP value, now that the stack and base pointers are
16040     // set up.
16041     X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
16042     X86FI->setHasSEHFramePtrSave(true);
16043     int FI = MF.getFrameInfo()->CreateSpillStackObject(SlotSize, SlotSize);
16044     X86FI->setSEHFramePtrSaveIndex(FI);
16045     SDValue NewFP = DAG.getLoad(VT, dl, Chain, DAG.getFrameIndex(FI, VT),
16046                                 MachinePointerInfo(), false, false, false,
16047                                 VT.getScalarSizeInBits() / 8);
16048     Chain = DAG.getCopyToReg(NewFP, dl, FrameReg, NewFP);
16049   }
16050
16051   return Chain;
16052 }
16053
16054 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
16055                                       SelectionDAG &DAG) {
16056   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
16057
16058   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
16059   if (!IntrData) {
16060     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
16061       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
16062     return SDValue();
16063   }
16064
16065   SDLoc dl(Op);
16066   switch(IntrData->Type) {
16067   default:
16068     llvm_unreachable("Unknown Intrinsic Type");
16069     break;
16070   case RDSEED:
16071   case RDRAND: {
16072     // Emit the node with the right value type.
16073     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
16074     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16075
16076     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
16077     // Otherwise return the value from Rand, which is always 0, casted to i32.
16078     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
16079                       DAG.getConstant(1, dl, Op->getValueType(1)),
16080                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
16081                       SDValue(Result.getNode(), 1) };
16082     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
16083                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
16084                                   Ops);
16085
16086     // Return { result, isValid, chain }.
16087     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
16088                        SDValue(Result.getNode(), 2));
16089   }
16090   case GATHER: {
16091   //gather(v1, mask, index, base, scale);
16092     SDValue Chain = Op.getOperand(0);
16093     SDValue Src   = Op.getOperand(2);
16094     SDValue Base  = Op.getOperand(3);
16095     SDValue Index = Op.getOperand(4);
16096     SDValue Mask  = Op.getOperand(5);
16097     SDValue Scale = Op.getOperand(6);
16098     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
16099                          Chain, Subtarget);
16100   }
16101   case SCATTER: {
16102   //scatter(base, mask, index, v1, scale);
16103     SDValue Chain = Op.getOperand(0);
16104     SDValue Base  = Op.getOperand(2);
16105     SDValue Mask  = Op.getOperand(3);
16106     SDValue Index = Op.getOperand(4);
16107     SDValue Src   = Op.getOperand(5);
16108     SDValue Scale = Op.getOperand(6);
16109     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
16110                           Scale, Chain);
16111   }
16112   case PREFETCH: {
16113     SDValue Hint = Op.getOperand(6);
16114     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
16115     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
16116     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
16117     SDValue Chain = Op.getOperand(0);
16118     SDValue Mask  = Op.getOperand(2);
16119     SDValue Index = Op.getOperand(3);
16120     SDValue Base  = Op.getOperand(4);
16121     SDValue Scale = Op.getOperand(5);
16122     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
16123   }
16124   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
16125   case RDTSC: {
16126     SmallVector<SDValue, 2> Results;
16127     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
16128                             Results);
16129     return DAG.getMergeValues(Results, dl);
16130   }
16131   // Read Performance Monitoring Counters.
16132   case RDPMC: {
16133     SmallVector<SDValue, 2> Results;
16134     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
16135     return DAG.getMergeValues(Results, dl);
16136   }
16137   // XTEST intrinsics.
16138   case XTEST: {
16139     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16140     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
16141     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16142                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
16143                                 InTrans);
16144     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
16145     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
16146                        Ret, SDValue(InTrans.getNode(), 1));
16147   }
16148   // ADC/ADCX/SBB
16149   case ADX: {
16150     SmallVector<SDValue, 2> Results;
16151     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
16152     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
16153     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
16154                                 DAG.getConstant(-1, dl, MVT::i8));
16155     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
16156                               Op.getOperand(4), GenCF.getValue(1));
16157     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
16158                                  Op.getOperand(5), MachinePointerInfo(),
16159                                  false, false, 0);
16160     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
16161                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
16162                                 Res.getValue(1));
16163     Results.push_back(SetCC);
16164     Results.push_back(Store);
16165     return DAG.getMergeValues(Results, dl);
16166   }
16167   case COMPRESS_TO_MEM: {
16168     SDLoc dl(Op);
16169     SDValue Mask = Op.getOperand(4);
16170     SDValue DataToCompress = Op.getOperand(3);
16171     SDValue Addr = Op.getOperand(2);
16172     SDValue Chain = Op.getOperand(0);
16173
16174     EVT VT = DataToCompress.getValueType();
16175     if (isAllOnes(Mask)) // return just a store
16176       return DAG.getStore(Chain, dl, DataToCompress, Addr,
16177                           MachinePointerInfo(), false, false,
16178                           VT.getScalarSizeInBits()/8);
16179
16180     SDValue Compressed =
16181       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
16182                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
16183     return DAG.getStore(Chain, dl, Compressed, Addr,
16184                         MachinePointerInfo(), false, false,
16185                         VT.getScalarSizeInBits()/8);
16186   }
16187   case EXPAND_FROM_MEM: {
16188     SDLoc dl(Op);
16189     SDValue Mask = Op.getOperand(4);
16190     SDValue PassThru = Op.getOperand(3);
16191     SDValue Addr = Op.getOperand(2);
16192     SDValue Chain = Op.getOperand(0);
16193     EVT VT = Op.getValueType();
16194
16195     if (isAllOnes(Mask)) // return just a load
16196       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
16197                          false, VT.getScalarSizeInBits()/8);
16198
16199     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
16200                                        false, false, false,
16201                                        VT.getScalarSizeInBits()/8);
16202
16203     SDValue Results[] = {
16204       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
16205                            Mask, PassThru, Subtarget, DAG), Chain};
16206     return DAG.getMergeValues(Results, dl);
16207   }
16208   }
16209 }
16210
16211 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
16212                                            SelectionDAG &DAG) const {
16213   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
16214   MFI->setReturnAddressIsTaken(true);
16215
16216   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
16217     return SDValue();
16218
16219   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16220   SDLoc dl(Op);
16221   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16222
16223   if (Depth > 0) {
16224     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
16225     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16226     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
16227     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16228                        DAG.getNode(ISD::ADD, dl, PtrVT,
16229                                    FrameAddr, Offset),
16230                        MachinePointerInfo(), false, false, false, 0);
16231   }
16232
16233   // Just load the return address.
16234   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
16235   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
16236                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
16237 }
16238
16239 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
16240   MachineFunction &MF = DAG.getMachineFunction();
16241   MachineFrameInfo *MFI = MF.getFrameInfo();
16242   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
16243   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16244   EVT VT = Op.getValueType();
16245
16246   MFI->setFrameAddressIsTaken(true);
16247
16248   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
16249     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
16250     // is not possible to crawl up the stack without looking at the unwind codes
16251     // simultaneously.
16252     int FrameAddrIndex = FuncInfo->getFAIndex();
16253     if (!FrameAddrIndex) {
16254       // Set up a frame object for the return address.
16255       unsigned SlotSize = RegInfo->getSlotSize();
16256       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16257           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16258       FuncInfo->setFAIndex(FrameAddrIndex);
16259     }
16260     return DAG.getFrameIndex(FrameAddrIndex, VT);
16261   }
16262
16263   unsigned FrameReg =
16264       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16265   SDLoc dl(Op);  // FIXME probably not meaningful
16266   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16267   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16268           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16269          "Invalid Frame Register!");
16270   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16271   while (Depth--)
16272     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16273                             MachinePointerInfo(),
16274                             false, false, false, 0);
16275   return FrameAddr;
16276 }
16277
16278 // FIXME? Maybe this could be a TableGen attribute on some registers and
16279 // this table could be generated automatically from RegInfo.
16280 unsigned X86TargetLowering::getRegisterByName(const char* RegName, EVT VT,
16281                                               SelectionDAG &DAG) const {
16282   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16283   const MachineFunction &MF = DAG.getMachineFunction();
16284
16285   unsigned Reg = StringSwitch<unsigned>(RegName)
16286                        .Case("esp", X86::ESP)
16287                        .Case("rsp", X86::RSP)
16288                        .Case("ebp", X86::EBP)
16289                        .Case("rbp", X86::RBP)
16290                        .Default(0);
16291
16292   if (Reg == X86::EBP || Reg == X86::RBP) {
16293     if (!TFI.hasFP(MF))
16294       report_fatal_error("register " + StringRef(RegName) +
16295                          " is allocatable: function has no frame pointer");
16296 #ifndef NDEBUG
16297     else {
16298       const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16299       unsigned FrameReg =
16300           RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16301       assert((FrameReg == X86::EBP || FrameReg == X86::RBP) &&
16302              "Invalid Frame Register!");
16303     }
16304 #endif
16305   }
16306
16307   if (Reg)
16308     return Reg;
16309
16310   report_fatal_error("Invalid register name global variable");
16311 }
16312
16313 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16314                                                      SelectionDAG &DAG) const {
16315   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16316   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16317 }
16318
16319 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16320   SDValue Chain     = Op.getOperand(0);
16321   SDValue Offset    = Op.getOperand(1);
16322   SDValue Handler   = Op.getOperand(2);
16323   SDLoc dl      (Op);
16324
16325   EVT PtrVT = getPointerTy(DAG.getDataLayout());
16326   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16327   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16328   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16329           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16330          "Invalid Frame Register!");
16331   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16332   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16333
16334   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16335                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16336                                                        dl));
16337   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16338   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16339                        false, false, 0);
16340   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16341
16342   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16343                      DAG.getRegister(StoreAddrReg, PtrVT));
16344 }
16345
16346 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16347                                                SelectionDAG &DAG) const {
16348   SDLoc DL(Op);
16349   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16350                      DAG.getVTList(MVT::i32, MVT::Other),
16351                      Op.getOperand(0), Op.getOperand(1));
16352 }
16353
16354 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16355                                                 SelectionDAG &DAG) const {
16356   SDLoc DL(Op);
16357   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16358                      Op.getOperand(0), Op.getOperand(1));
16359 }
16360
16361 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16362   return Op.getOperand(0);
16363 }
16364
16365 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16366                                                 SelectionDAG &DAG) const {
16367   SDValue Root = Op.getOperand(0);
16368   SDValue Trmp = Op.getOperand(1); // trampoline
16369   SDValue FPtr = Op.getOperand(2); // nested function
16370   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16371   SDLoc dl (Op);
16372
16373   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16374   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16375
16376   if (Subtarget->is64Bit()) {
16377     SDValue OutChains[6];
16378
16379     // Large code-model.
16380     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16381     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16382
16383     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16384     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16385
16386     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16387
16388     // Load the pointer to the nested function into R11.
16389     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16390     SDValue Addr = Trmp;
16391     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16392                                 Addr, MachinePointerInfo(TrmpAddr),
16393                                 false, false, 0);
16394
16395     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16396                        DAG.getConstant(2, dl, MVT::i64));
16397     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16398                                 MachinePointerInfo(TrmpAddr, 2),
16399                                 false, false, 2);
16400
16401     // Load the 'nest' parameter value into R10.
16402     // R10 is specified in X86CallingConv.td
16403     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16404     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16405                        DAG.getConstant(10, dl, MVT::i64));
16406     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16407                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16408                                 false, false, 0);
16409
16410     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16411                        DAG.getConstant(12, dl, MVT::i64));
16412     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16413                                 MachinePointerInfo(TrmpAddr, 12),
16414                                 false, false, 2);
16415
16416     // Jump to the nested function.
16417     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16418     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16419                        DAG.getConstant(20, dl, MVT::i64));
16420     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16421                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16422                                 false, false, 0);
16423
16424     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16425     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16426                        DAG.getConstant(22, dl, MVT::i64));
16427     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16428                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16429                                 false, false, 0);
16430
16431     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16432   } else {
16433     const Function *Func =
16434       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16435     CallingConv::ID CC = Func->getCallingConv();
16436     unsigned NestReg;
16437
16438     switch (CC) {
16439     default:
16440       llvm_unreachable("Unsupported calling convention");
16441     case CallingConv::C:
16442     case CallingConv::X86_StdCall: {
16443       // Pass 'nest' parameter in ECX.
16444       // Must be kept in sync with X86CallingConv.td
16445       NestReg = X86::ECX;
16446
16447       // Check that ECX wasn't needed by an 'inreg' parameter.
16448       FunctionType *FTy = Func->getFunctionType();
16449       const AttributeSet &Attrs = Func->getAttributes();
16450
16451       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16452         unsigned InRegCount = 0;
16453         unsigned Idx = 1;
16454
16455         for (FunctionType::param_iterator I = FTy->param_begin(),
16456              E = FTy->param_end(); I != E; ++I, ++Idx)
16457           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16458             // FIXME: should only count parameters that are lowered to integers.
16459             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16460
16461         if (InRegCount > 2) {
16462           report_fatal_error("Nest register in use - reduce number of inreg"
16463                              " parameters!");
16464         }
16465       }
16466       break;
16467     }
16468     case CallingConv::X86_FastCall:
16469     case CallingConv::X86_ThisCall:
16470     case CallingConv::Fast:
16471       // Pass 'nest' parameter in EAX.
16472       // Must be kept in sync with X86CallingConv.td
16473       NestReg = X86::EAX;
16474       break;
16475     }
16476
16477     SDValue OutChains[4];
16478     SDValue Addr, Disp;
16479
16480     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16481                        DAG.getConstant(10, dl, MVT::i32));
16482     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16483
16484     // This is storing the opcode for MOV32ri.
16485     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16486     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16487     OutChains[0] = DAG.getStore(Root, dl,
16488                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16489                                 Trmp, MachinePointerInfo(TrmpAddr),
16490                                 false, false, 0);
16491
16492     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16493                        DAG.getConstant(1, dl, MVT::i32));
16494     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16495                                 MachinePointerInfo(TrmpAddr, 1),
16496                                 false, false, 1);
16497
16498     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16499     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16500                        DAG.getConstant(5, dl, MVT::i32));
16501     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16502                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16503                                 false, false, 1);
16504
16505     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16506                        DAG.getConstant(6, dl, MVT::i32));
16507     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16508                                 MachinePointerInfo(TrmpAddr, 6),
16509                                 false, false, 1);
16510
16511     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16512   }
16513 }
16514
16515 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16516                                             SelectionDAG &DAG) const {
16517   /*
16518    The rounding mode is in bits 11:10 of FPSR, and has the following
16519    settings:
16520      00 Round to nearest
16521      01 Round to -inf
16522      10 Round to +inf
16523      11 Round to 0
16524
16525   FLT_ROUNDS, on the other hand, expects the following:
16526     -1 Undefined
16527      0 Round to 0
16528      1 Round to nearest
16529      2 Round to +inf
16530      3 Round to -inf
16531
16532   To perform the conversion, we do:
16533     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16534   */
16535
16536   MachineFunction &MF = DAG.getMachineFunction();
16537   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16538   unsigned StackAlignment = TFI.getStackAlignment();
16539   MVT VT = Op.getSimpleValueType();
16540   SDLoc DL(Op);
16541
16542   // Save FP Control Word to stack slot
16543   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16544   SDValue StackSlot =
16545       DAG.getFrameIndex(SSFI, getPointerTy(DAG.getDataLayout()));
16546
16547   MachineMemOperand *MMO =
16548    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16549                            MachineMemOperand::MOStore, 2, 2);
16550
16551   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16552   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16553                                           DAG.getVTList(MVT::Other),
16554                                           Ops, MVT::i16, MMO);
16555
16556   // Load FP Control Word from stack slot
16557   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16558                             MachinePointerInfo(), false, false, false, 0);
16559
16560   // Transform as necessary
16561   SDValue CWD1 =
16562     DAG.getNode(ISD::SRL, DL, MVT::i16,
16563                 DAG.getNode(ISD::AND, DL, MVT::i16,
16564                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16565                 DAG.getConstant(11, DL, MVT::i8));
16566   SDValue CWD2 =
16567     DAG.getNode(ISD::SRL, DL, MVT::i16,
16568                 DAG.getNode(ISD::AND, DL, MVT::i16,
16569                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16570                 DAG.getConstant(9, DL, MVT::i8));
16571
16572   SDValue RetVal =
16573     DAG.getNode(ISD::AND, DL, MVT::i16,
16574                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16575                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16576                             DAG.getConstant(1, DL, MVT::i16)),
16577                 DAG.getConstant(3, DL, MVT::i16));
16578
16579   return DAG.getNode((VT.getSizeInBits() < 16 ?
16580                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16581 }
16582
16583 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16584   MVT VT = Op.getSimpleValueType();
16585   EVT OpVT = VT;
16586   unsigned NumBits = VT.getSizeInBits();
16587   SDLoc dl(Op);
16588
16589   Op = Op.getOperand(0);
16590   if (VT == MVT::i8) {
16591     // Zero extend to i32 since there is not an i8 bsr.
16592     OpVT = MVT::i32;
16593     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16594   }
16595
16596   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16597   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16598   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16599
16600   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16601   SDValue Ops[] = {
16602     Op,
16603     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16604     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16605     Op.getValue(1)
16606   };
16607   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16608
16609   // Finally xor with NumBits-1.
16610   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16611                    DAG.getConstant(NumBits - 1, dl, OpVT));
16612
16613   if (VT == MVT::i8)
16614     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16615   return Op;
16616 }
16617
16618 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16619   MVT VT = Op.getSimpleValueType();
16620   EVT OpVT = VT;
16621   unsigned NumBits = VT.getSizeInBits();
16622   SDLoc dl(Op);
16623
16624   Op = Op.getOperand(0);
16625   if (VT == MVT::i8) {
16626     // Zero extend to i32 since there is not an i8 bsr.
16627     OpVT = MVT::i32;
16628     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16629   }
16630
16631   // Issue a bsr (scan bits in reverse).
16632   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16633   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16634
16635   // And xor with NumBits-1.
16636   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16637                    DAG.getConstant(NumBits - 1, dl, OpVT));
16638
16639   if (VT == MVT::i8)
16640     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16641   return Op;
16642 }
16643
16644 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16645   MVT VT = Op.getSimpleValueType();
16646   unsigned NumBits = VT.getSizeInBits();
16647   SDLoc dl(Op);
16648   Op = Op.getOperand(0);
16649
16650   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16651   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16652   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16653
16654   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16655   SDValue Ops[] = {
16656     Op,
16657     DAG.getConstant(NumBits, dl, VT),
16658     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16659     Op.getValue(1)
16660   };
16661   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16662 }
16663
16664 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16665 // ones, and then concatenate the result back.
16666 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16667   MVT VT = Op.getSimpleValueType();
16668
16669   assert(VT.is256BitVector() && VT.isInteger() &&
16670          "Unsupported value type for operation");
16671
16672   unsigned NumElems = VT.getVectorNumElements();
16673   SDLoc dl(Op);
16674
16675   // Extract the LHS vectors
16676   SDValue LHS = Op.getOperand(0);
16677   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16678   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16679
16680   // Extract the RHS vectors
16681   SDValue RHS = Op.getOperand(1);
16682   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16683   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16684
16685   MVT EltVT = VT.getVectorElementType();
16686   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16687
16688   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16689                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16690                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16691 }
16692
16693 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16694   if (Op.getValueType() == MVT::i1)
16695     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16696                        Op.getOperand(0), Op.getOperand(1));
16697   assert(Op.getSimpleValueType().is256BitVector() &&
16698          Op.getSimpleValueType().isInteger() &&
16699          "Only handle AVX 256-bit vector integer operation");
16700   return Lower256IntArith(Op, DAG);
16701 }
16702
16703 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16704   if (Op.getValueType() == MVT::i1)
16705     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16706                        Op.getOperand(0), Op.getOperand(1));
16707   assert(Op.getSimpleValueType().is256BitVector() &&
16708          Op.getSimpleValueType().isInteger() &&
16709          "Only handle AVX 256-bit vector integer operation");
16710   return Lower256IntArith(Op, DAG);
16711 }
16712
16713 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16714                         SelectionDAG &DAG) {
16715   SDLoc dl(Op);
16716   MVT VT = Op.getSimpleValueType();
16717
16718   if (VT == MVT::i1)
16719     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16720
16721   // Decompose 256-bit ops into smaller 128-bit ops.
16722   if (VT.is256BitVector() && !Subtarget->hasInt256())
16723     return Lower256IntArith(Op, DAG);
16724
16725   SDValue A = Op.getOperand(0);
16726   SDValue B = Op.getOperand(1);
16727
16728   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16729   // pairs, multiply and truncate.
16730   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16731     if (Subtarget->hasInt256()) {
16732       if (VT == MVT::v32i8) {
16733         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16734         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16735         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16736         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16737         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16738         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16739         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16740         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16741                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16742                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16743       }
16744
16745       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16746       return DAG.getNode(
16747           ISD::TRUNCATE, dl, VT,
16748           DAG.getNode(ISD::MUL, dl, ExVT,
16749                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16750                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16751     }
16752
16753     assert(VT == MVT::v16i8 &&
16754            "Pre-AVX2 support only supports v16i8 multiplication");
16755     MVT ExVT = MVT::v8i16;
16756
16757     // Extract the lo parts and sign extend to i16
16758     SDValue ALo, BLo;
16759     if (Subtarget->hasSSE41()) {
16760       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16761       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16762     } else {
16763       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16764                               -1, 4, -1, 5, -1, 6, -1, 7};
16765       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16766       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16767       ALo = DAG.getBitcast(ExVT, ALo);
16768       BLo = DAG.getBitcast(ExVT, BLo);
16769       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16770       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16771     }
16772
16773     // Extract the hi parts and sign extend to i16
16774     SDValue AHi, BHi;
16775     if (Subtarget->hasSSE41()) {
16776       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16777                               -1, -1, -1, -1, -1, -1, -1, -1};
16778       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16779       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16780       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16781       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16782     } else {
16783       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16784                               -1, 12, -1, 13, -1, 14, -1, 15};
16785       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16786       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16787       AHi = DAG.getBitcast(ExVT, AHi);
16788       BHi = DAG.getBitcast(ExVT, BHi);
16789       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16790       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16791     }
16792
16793     // Multiply, mask the lower 8bits of the lo/hi results and pack
16794     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16795     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16796     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16797     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16798     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16799   }
16800
16801   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16802   if (VT == MVT::v4i32) {
16803     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16804            "Should not custom lower when pmuldq is available!");
16805
16806     // Extract the odd parts.
16807     static const int UnpackMask[] = { 1, -1, 3, -1 };
16808     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16809     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16810
16811     // Multiply the even parts.
16812     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16813     // Now multiply odd parts.
16814     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16815
16816     Evens = DAG.getBitcast(VT, Evens);
16817     Odds = DAG.getBitcast(VT, Odds);
16818
16819     // Merge the two vectors back together with a shuffle. This expands into 2
16820     // shuffles.
16821     static const int ShufMask[] = { 0, 4, 2, 6 };
16822     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16823   }
16824
16825   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16826          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16827
16828   //  Ahi = psrlqi(a, 32);
16829   //  Bhi = psrlqi(b, 32);
16830   //
16831   //  AloBlo = pmuludq(a, b);
16832   //  AloBhi = pmuludq(a, Bhi);
16833   //  AhiBlo = pmuludq(Ahi, b);
16834
16835   //  AloBhi = psllqi(AloBhi, 32);
16836   //  AhiBlo = psllqi(AhiBlo, 32);
16837   //  return AloBlo + AloBhi + AhiBlo;
16838
16839   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16840   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16841
16842   SDValue AhiBlo = Ahi;
16843   SDValue AloBhi = Bhi;
16844   // Bit cast to 32-bit vectors for MULUDQ
16845   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16846                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16847   A = DAG.getBitcast(MulVT, A);
16848   B = DAG.getBitcast(MulVT, B);
16849   Ahi = DAG.getBitcast(MulVT, Ahi);
16850   Bhi = DAG.getBitcast(MulVT, Bhi);
16851
16852   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16853   // After shifting right const values the result may be all-zero.
16854   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16855     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16856     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16857   }
16858   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16859     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16860     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16861   }
16862
16863   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16864   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16865 }
16866
16867 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16868   assert(Subtarget->isTargetWin64() && "Unexpected target");
16869   EVT VT = Op.getValueType();
16870   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16871          "Unexpected return type for lowering");
16872
16873   RTLIB::Libcall LC;
16874   bool isSigned;
16875   switch (Op->getOpcode()) {
16876   default: llvm_unreachable("Unexpected request for libcall!");
16877   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16878   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16879   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16880   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16881   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16882   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16883   }
16884
16885   SDLoc dl(Op);
16886   SDValue InChain = DAG.getEntryNode();
16887
16888   TargetLowering::ArgListTy Args;
16889   TargetLowering::ArgListEntry Entry;
16890   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16891     EVT ArgVT = Op->getOperand(i).getValueType();
16892     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16893            "Unexpected argument type for lowering");
16894     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16895     Entry.Node = StackPtr;
16896     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16897                            false, false, 16);
16898     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16899     Entry.Ty = PointerType::get(ArgTy,0);
16900     Entry.isSExt = false;
16901     Entry.isZExt = false;
16902     Args.push_back(Entry);
16903   }
16904
16905   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16906                                          getPointerTy(DAG.getDataLayout()));
16907
16908   TargetLowering::CallLoweringInfo CLI(DAG);
16909   CLI.setDebugLoc(dl).setChain(InChain)
16910     .setCallee(getLibcallCallingConv(LC),
16911                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16912                Callee, std::move(Args), 0)
16913     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16914
16915   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16916   return DAG.getBitcast(VT, CallInfo.first);
16917 }
16918
16919 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16920                              SelectionDAG &DAG) {
16921   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16922   EVT VT = Op0.getValueType();
16923   SDLoc dl(Op);
16924
16925   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16926          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16927
16928   // PMULxD operations multiply each even value (starting at 0) of LHS with
16929   // the related value of RHS and produce a widen result.
16930   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16931   // => <2 x i64> <ae|cg>
16932   //
16933   // In other word, to have all the results, we need to perform two PMULxD:
16934   // 1. one with the even values.
16935   // 2. one with the odd values.
16936   // To achieve #2, with need to place the odd values at an even position.
16937   //
16938   // Place the odd value at an even position (basically, shift all values 1
16939   // step to the left):
16940   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16941   // <a|b|c|d> => <b|undef|d|undef>
16942   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16943   // <e|f|g|h> => <f|undef|h|undef>
16944   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16945
16946   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16947   // ints.
16948   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16949   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16950   unsigned Opcode =
16951       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16952   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16953   // => <2 x i64> <ae|cg>
16954   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16955   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16956   // => <2 x i64> <bf|dh>
16957   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16958
16959   // Shuffle it back into the right order.
16960   SDValue Highs, Lows;
16961   if (VT == MVT::v8i32) {
16962     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16963     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16964     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16965     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16966   } else {
16967     const int HighMask[] = {1, 5, 3, 7};
16968     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16969     const int LowMask[] = {0, 4, 2, 6};
16970     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16971   }
16972
16973   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16974   // unsigned multiply.
16975   if (IsSigned && !Subtarget->hasSSE41()) {
16976     SDValue ShAmt = DAG.getConstant(
16977         31, dl,
16978         DAG.getTargetLoweringInfo().getShiftAmountTy(VT, DAG.getDataLayout()));
16979     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16980                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16981     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16982                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16983
16984     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16985     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16986   }
16987
16988   // The first result of MUL_LOHI is actually the low value, followed by the
16989   // high value.
16990   SDValue Ops[] = {Lows, Highs};
16991   return DAG.getMergeValues(Ops, dl);
16992 }
16993
16994 // Return true if the required (according to Opcode) shift-imm form is natively
16995 // supported by the Subtarget
16996 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16997                                         unsigned Opcode) {
16998   if (VT.getScalarSizeInBits() < 16)
16999     return false;
17000
17001   if (VT.is512BitVector() &&
17002       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
17003     return true;
17004
17005   bool LShift = VT.is128BitVector() ||
17006     (VT.is256BitVector() && Subtarget->hasInt256());
17007
17008   bool AShift = LShift && (Subtarget->hasVLX() ||
17009     (VT != MVT::v2i64 && VT != MVT::v4i64));
17010   return (Opcode == ISD::SRA) ? AShift : LShift;
17011 }
17012
17013 // The shift amount is a variable, but it is the same for all vector lanes.
17014 // These instructions are defined together with shift-immediate.
17015 static
17016 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
17017                                       unsigned Opcode) {
17018   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
17019 }
17020
17021 // Return true if the required (according to Opcode) variable-shift form is
17022 // natively supported by the Subtarget
17023 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
17024                                     unsigned Opcode) {
17025
17026   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
17027     return false;
17028
17029   // vXi16 supported only on AVX-512, BWI
17030   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
17031     return false;
17032
17033   if (VT.is512BitVector() || Subtarget->hasVLX())
17034     return true;
17035
17036   bool LShift = VT.is128BitVector() || VT.is256BitVector();
17037   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
17038   return (Opcode == ISD::SRA) ? AShift : LShift;
17039 }
17040
17041 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
17042                                          const X86Subtarget *Subtarget) {
17043   MVT VT = Op.getSimpleValueType();
17044   SDLoc dl(Op);
17045   SDValue R = Op.getOperand(0);
17046   SDValue Amt = Op.getOperand(1);
17047
17048   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17049     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17050
17051   auto ArithmeticShiftRight64 = [&](uint64_t ShiftAmt) {
17052     assert((VT == MVT::v2i64 || VT == MVT::v4i64) && "Unexpected SRA type");
17053     MVT ExVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() * 2);
17054     SDValue Ex = DAG.getBitcast(ExVT, R);
17055
17056     if (ShiftAmt >= 32) {
17057       // Splat sign to upper i32 dst, and SRA upper i32 src to lower i32.
17058       SDValue Upper =
17059           getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex, 31, DAG);
17060       SDValue Lower = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17061                                                  ShiftAmt - 32, DAG);
17062       if (VT == MVT::v2i64)
17063         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {5, 1, 7, 3});
17064       if (VT == MVT::v4i64)
17065         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17066                                   {9, 1, 11, 3, 13, 5, 15, 7});
17067     } else {
17068       // SRA upper i32, SHL whole i64 and select lower i32.
17069       SDValue Upper = getTargetVShiftByConstNode(X86ISD::VSRAI, dl, ExVT, Ex,
17070                                                  ShiftAmt, DAG);
17071       SDValue Lower =
17072           getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, R, ShiftAmt, DAG);
17073       Lower = DAG.getBitcast(ExVT, Lower);
17074       if (VT == MVT::v2i64)
17075         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower, {4, 1, 6, 3});
17076       if (VT == MVT::v4i64)
17077         Ex = DAG.getVectorShuffle(ExVT, dl, Upper, Lower,
17078                                   {8, 1, 10, 3, 12, 5, 14, 7});
17079     }
17080     return DAG.getBitcast(VT, Ex);
17081   };
17082
17083   // Optimize shl/srl/sra with constant shift amount.
17084   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
17085     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
17086       uint64_t ShiftAmt = ShiftConst->getZExtValue();
17087
17088       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17089         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17090
17091       // i64 SRA needs to be performed as partial shifts.
17092       if ((VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17093           Op.getOpcode() == ISD::SRA)
17094         return ArithmeticShiftRight64(ShiftAmt);
17095
17096       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
17097         unsigned NumElts = VT.getVectorNumElements();
17098         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
17099
17100         if (Op.getOpcode() == ISD::SHL) {
17101           // Simple i8 add case
17102           if (ShiftAmt == 1)
17103             return DAG.getNode(ISD::ADD, dl, VT, R, R);
17104
17105           // Make a large shift.
17106           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
17107                                                    R, ShiftAmt, DAG);
17108           SHL = DAG.getBitcast(VT, SHL);
17109           // Zero out the rightmost bits.
17110           SmallVector<SDValue, 32> V(
17111               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
17112           return DAG.getNode(ISD::AND, dl, VT, SHL,
17113                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17114         }
17115         if (Op.getOpcode() == ISD::SRL) {
17116           // Make a large shift.
17117           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
17118                                                    R, ShiftAmt, DAG);
17119           SRL = DAG.getBitcast(VT, SRL);
17120           // Zero out the leftmost bits.
17121           SmallVector<SDValue, 32> V(
17122               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
17123           return DAG.getNode(ISD::AND, dl, VT, SRL,
17124                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
17125         }
17126         if (Op.getOpcode() == ISD::SRA) {
17127           if (ShiftAmt == 7) {
17128             // R s>> 7  ===  R s< 0
17129             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
17130             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
17131           }
17132
17133           // R s>> a === ((R u>> a) ^ m) - m
17134           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
17135           SmallVector<SDValue, 32> V(NumElts,
17136                                      DAG.getConstant(128 >> ShiftAmt, dl,
17137                                                      MVT::i8));
17138           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
17139           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
17140           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
17141           return Res;
17142         }
17143         llvm_unreachable("Unknown shift opcode.");
17144       }
17145     }
17146   }
17147
17148   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17149   if (!Subtarget->is64Bit() &&
17150       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
17151       Amt.getOpcode() == ISD::BITCAST &&
17152       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17153     Amt = Amt.getOperand(0);
17154     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17155                      VT.getVectorNumElements();
17156     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
17157     uint64_t ShiftAmt = 0;
17158     for (unsigned i = 0; i != Ratio; ++i) {
17159       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
17160       if (!C)
17161         return SDValue();
17162       // 6 == Log2(64)
17163       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
17164     }
17165     // Check remaining shift amounts.
17166     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17167       uint64_t ShAmt = 0;
17168       for (unsigned j = 0; j != Ratio; ++j) {
17169         ConstantSDNode *C =
17170           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
17171         if (!C)
17172           return SDValue();
17173         // 6 == Log2(64)
17174         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
17175       }
17176       if (ShAmt != ShiftAmt)
17177         return SDValue();
17178     }
17179
17180     if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
17181       return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
17182
17183     if (Op.getOpcode() == ISD::SRA)
17184       return ArithmeticShiftRight64(ShiftAmt);
17185   }
17186
17187   return SDValue();
17188 }
17189
17190 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
17191                                         const X86Subtarget* Subtarget) {
17192   MVT VT = Op.getSimpleValueType();
17193   SDLoc dl(Op);
17194   SDValue R = Op.getOperand(0);
17195   SDValue Amt = Op.getOperand(1);
17196
17197   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
17198     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
17199
17200   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
17201     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
17202
17203   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
17204     SDValue BaseShAmt;
17205     EVT EltVT = VT.getVectorElementType();
17206
17207     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
17208       // Check if this build_vector node is doing a splat.
17209       // If so, then set BaseShAmt equal to the splat value.
17210       BaseShAmt = BV->getSplatValue();
17211       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
17212         BaseShAmt = SDValue();
17213     } else {
17214       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
17215         Amt = Amt.getOperand(0);
17216
17217       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
17218       if (SVN && SVN->isSplat()) {
17219         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
17220         SDValue InVec = Amt.getOperand(0);
17221         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
17222           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
17223                  "Unexpected shuffle index found!");
17224           BaseShAmt = InVec.getOperand(SplatIdx);
17225         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
17226            if (ConstantSDNode *C =
17227                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
17228              if (C->getZExtValue() == SplatIdx)
17229                BaseShAmt = InVec.getOperand(1);
17230            }
17231         }
17232
17233         if (!BaseShAmt)
17234           // Avoid introducing an extract element from a shuffle.
17235           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
17236                                   DAG.getIntPtrConstant(SplatIdx, dl));
17237       }
17238     }
17239
17240     if (BaseShAmt.getNode()) {
17241       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
17242       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
17243         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
17244       else if (EltVT.bitsLT(MVT::i32))
17245         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
17246
17247       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
17248     }
17249   }
17250
17251   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
17252   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
17253       Amt.getOpcode() == ISD::BITCAST &&
17254       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
17255     Amt = Amt.getOperand(0);
17256     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
17257                      VT.getVectorNumElements();
17258     std::vector<SDValue> Vals(Ratio);
17259     for (unsigned i = 0; i != Ratio; ++i)
17260       Vals[i] = Amt.getOperand(i);
17261     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
17262       for (unsigned j = 0; j != Ratio; ++j)
17263         if (Vals[j] != Amt.getOperand(i + j))
17264           return SDValue();
17265     }
17266
17267     if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode()))
17268       return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
17269   }
17270   return SDValue();
17271 }
17272
17273 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
17274                           SelectionDAG &DAG) {
17275   MVT VT = Op.getSimpleValueType();
17276   SDLoc dl(Op);
17277   SDValue R = Op.getOperand(0);
17278   SDValue Amt = Op.getOperand(1);
17279
17280   assert(VT.isVector() && "Custom lowering only for vector shifts!");
17281   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
17282
17283   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
17284     return V;
17285
17286   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
17287       return V;
17288
17289   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
17290     return Op;
17291
17292   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
17293   // shifts per-lane and then shuffle the partial results back together.
17294   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
17295     // Splat the shift amounts so the scalar shifts above will catch it.
17296     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
17297     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
17298     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
17299     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
17300     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
17301   }
17302
17303   // If possible, lower this packed shift into a vector multiply instead of
17304   // expanding it into a sequence of scalar shifts.
17305   // Do this only if the vector shift count is a constant build_vector.
17306   if (Op.getOpcode() == ISD::SHL &&
17307       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
17308        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
17309       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17310     SmallVector<SDValue, 8> Elts;
17311     EVT SVT = VT.getScalarType();
17312     unsigned SVTBits = SVT.getSizeInBits();
17313     const APInt &One = APInt(SVTBits, 1);
17314     unsigned NumElems = VT.getVectorNumElements();
17315
17316     for (unsigned i=0; i !=NumElems; ++i) {
17317       SDValue Op = Amt->getOperand(i);
17318       if (Op->getOpcode() == ISD::UNDEF) {
17319         Elts.push_back(Op);
17320         continue;
17321       }
17322
17323       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17324       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17325       uint64_t ShAmt = C.getZExtValue();
17326       if (ShAmt >= SVTBits) {
17327         Elts.push_back(DAG.getUNDEF(SVT));
17328         continue;
17329       }
17330       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17331     }
17332     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17333     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17334   }
17335
17336   // Lower SHL with variable shift amount.
17337   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17338     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17339
17340     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17341                      DAG.getConstant(0x3f800000U, dl, VT));
17342     Op = DAG.getBitcast(MVT::v4f32, Op);
17343     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17344     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17345   }
17346
17347   // If possible, lower this shift as a sequence of two shifts by
17348   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17349   // Example:
17350   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17351   //
17352   // Could be rewritten as:
17353   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17354   //
17355   // The advantage is that the two shifts from the example would be
17356   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17357   // the vector shift into four scalar shifts plus four pairs of vector
17358   // insert/extract.
17359   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17360       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17361     unsigned TargetOpcode = X86ISD::MOVSS;
17362     bool CanBeSimplified;
17363     // The splat value for the first packed shift (the 'X' from the example).
17364     SDValue Amt1 = Amt->getOperand(0);
17365     // The splat value for the second packed shift (the 'Y' from the example).
17366     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17367                                         Amt->getOperand(2);
17368
17369     // See if it is possible to replace this node with a sequence of
17370     // two shifts followed by a MOVSS/MOVSD
17371     if (VT == MVT::v4i32) {
17372       // Check if it is legal to use a MOVSS.
17373       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17374                         Amt2 == Amt->getOperand(3);
17375       if (!CanBeSimplified) {
17376         // Otherwise, check if we can still simplify this node using a MOVSD.
17377         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17378                           Amt->getOperand(2) == Amt->getOperand(3);
17379         TargetOpcode = X86ISD::MOVSD;
17380         Amt2 = Amt->getOperand(2);
17381       }
17382     } else {
17383       // Do similar checks for the case where the machine value type
17384       // is MVT::v8i16.
17385       CanBeSimplified = Amt1 == Amt->getOperand(1);
17386       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17387         CanBeSimplified = Amt2 == Amt->getOperand(i);
17388
17389       if (!CanBeSimplified) {
17390         TargetOpcode = X86ISD::MOVSD;
17391         CanBeSimplified = true;
17392         Amt2 = Amt->getOperand(4);
17393         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17394           CanBeSimplified = Amt1 == Amt->getOperand(i);
17395         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17396           CanBeSimplified = Amt2 == Amt->getOperand(j);
17397       }
17398     }
17399
17400     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17401         isa<ConstantSDNode>(Amt2)) {
17402       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17403       EVT CastVT = MVT::v4i32;
17404       SDValue Splat1 =
17405         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17406       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17407       SDValue Splat2 =
17408         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17409       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17410       if (TargetOpcode == X86ISD::MOVSD)
17411         CastVT = MVT::v2i64;
17412       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17413       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17414       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17415                                             BitCast1, DAG);
17416       return DAG.getBitcast(VT, Result);
17417     }
17418   }
17419
17420   // v4i32 Non Uniform Shifts.
17421   // If the shift amount is constant we can shift each lane using the SSE2
17422   // immediate shifts, else we need to zero-extend each lane to the lower i64
17423   // and shift using the SSE2 variable shifts.
17424   // The separate results can then be blended together.
17425   if (VT == MVT::v4i32) {
17426     unsigned Opc = Op.getOpcode();
17427     SDValue Amt0, Amt1, Amt2, Amt3;
17428     if (ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17429       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {0, 0, 0, 0});
17430       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {1, 1, 1, 1});
17431       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {2, 2, 2, 2});
17432       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, DAG.getUNDEF(VT), {3, 3, 3, 3});
17433     } else {
17434       // ISD::SHL is handled above but we include it here for completeness.
17435       switch (Opc) {
17436       default:
17437         llvm_unreachable("Unknown target vector shift node");
17438       case ISD::SHL:
17439         Opc = X86ISD::VSHL;
17440         break;
17441       case ISD::SRL:
17442         Opc = X86ISD::VSRL;
17443         break;
17444       case ISD::SRA:
17445         Opc = X86ISD::VSRA;
17446         break;
17447       }
17448       // The SSE2 shifts use the lower i64 as the same shift amount for
17449       // all lanes and the upper i64 is ignored. These shuffle masks
17450       // optimally zero-extend each lanes on SSE2/SSE41/AVX targets.
17451       SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17452       Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Z, {0, 4, -1, -1});
17453       Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Z, {1, 5, -1, -1});
17454       Amt2 = DAG.getVectorShuffle(VT, dl, Amt, Z, {2, 6, -1, -1});
17455       Amt3 = DAG.getVectorShuffle(VT, dl, Amt, Z, {3, 7, -1, -1});
17456     }
17457
17458     SDValue R0 = DAG.getNode(Opc, dl, VT, R, Amt0);
17459     SDValue R1 = DAG.getNode(Opc, dl, VT, R, Amt1);
17460     SDValue R2 = DAG.getNode(Opc, dl, VT, R, Amt2);
17461     SDValue R3 = DAG.getNode(Opc, dl, VT, R, Amt3);
17462     SDValue R02 = DAG.getVectorShuffle(VT, dl, R0, R2, {0, -1, 6, -1});
17463     SDValue R13 = DAG.getVectorShuffle(VT, dl, R1, R3, {-1, 1, -1, 7});
17464     return DAG.getVectorShuffle(VT, dl, R02, R13, {0, 5, 2, 7});
17465   }
17466
17467   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17468     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17469     unsigned ShiftOpcode = Op->getOpcode();
17470
17471     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17472       // On SSE41 targets we make use of the fact that VSELECT lowers
17473       // to PBLENDVB which selects bytes based just on the sign bit.
17474       if (Subtarget->hasSSE41()) {
17475         V0 = DAG.getBitcast(VT, V0);
17476         V1 = DAG.getBitcast(VT, V1);
17477         Sel = DAG.getBitcast(VT, Sel);
17478         return DAG.getBitcast(SelVT,
17479                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17480       }
17481       // On pre-SSE41 targets we test for the sign bit by comparing to
17482       // zero - a negative value will set all bits of the lanes to true
17483       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17484       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17485       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17486       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17487     };
17488
17489     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17490     // We can safely do this using i16 shifts as we're only interested in
17491     // the 3 lower bits of each byte.
17492     Amt = DAG.getBitcast(ExtVT, Amt);
17493     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17494     Amt = DAG.getBitcast(VT, Amt);
17495
17496     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17497       // r = VSELECT(r, shift(r, 4), a);
17498       SDValue M =
17499           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17500       R = SignBitSelect(VT, Amt, M, R);
17501
17502       // a += a
17503       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17504
17505       // r = VSELECT(r, shift(r, 2), a);
17506       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17507       R = SignBitSelect(VT, Amt, M, R);
17508
17509       // a += a
17510       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17511
17512       // return VSELECT(r, shift(r, 1), a);
17513       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17514       R = SignBitSelect(VT, Amt, M, R);
17515       return R;
17516     }
17517
17518     if (Op->getOpcode() == ISD::SRA) {
17519       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17520       // so we can correctly sign extend. We don't care what happens to the
17521       // lower byte.
17522       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17523       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17524       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17525       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17526       ALo = DAG.getBitcast(ExtVT, ALo);
17527       AHi = DAG.getBitcast(ExtVT, AHi);
17528       RLo = DAG.getBitcast(ExtVT, RLo);
17529       RHi = DAG.getBitcast(ExtVT, RHi);
17530
17531       // r = VSELECT(r, shift(r, 4), a);
17532       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17533                                 DAG.getConstant(4, dl, ExtVT));
17534       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17535                                 DAG.getConstant(4, dl, ExtVT));
17536       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17537       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17538
17539       // a += a
17540       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17541       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17542
17543       // r = VSELECT(r, shift(r, 2), a);
17544       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17545                         DAG.getConstant(2, dl, ExtVT));
17546       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17547                         DAG.getConstant(2, dl, ExtVT));
17548       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17549       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17550
17551       // a += a
17552       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17553       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17554
17555       // r = VSELECT(r, shift(r, 1), a);
17556       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17557                         DAG.getConstant(1, dl, ExtVT));
17558       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17559                         DAG.getConstant(1, dl, ExtVT));
17560       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17561       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17562
17563       // Logical shift the result back to the lower byte, leaving a zero upper
17564       // byte
17565       // meaning that we can safely pack with PACKUSWB.
17566       RLo =
17567           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17568       RHi =
17569           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17570       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17571     }
17572   }
17573
17574   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17575   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17576   // solution better.
17577   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17578     MVT ExtVT = MVT::v8i32;
17579     unsigned ExtOpc =
17580         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17581     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17582     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17583     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17584                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17585   }
17586
17587   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17588     MVT ExtVT = MVT::v8i32;
17589     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17590     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17591     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17592     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17593     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17594     ALo = DAG.getBitcast(ExtVT, ALo);
17595     AHi = DAG.getBitcast(ExtVT, AHi);
17596     RLo = DAG.getBitcast(ExtVT, RLo);
17597     RHi = DAG.getBitcast(ExtVT, RHi);
17598     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17599     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17600     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17601     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17602     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17603   }
17604
17605   if (VT == MVT::v8i16) {
17606     unsigned ShiftOpcode = Op->getOpcode();
17607
17608     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17609       // On SSE41 targets we make use of the fact that VSELECT lowers
17610       // to PBLENDVB which selects bytes based just on the sign bit.
17611       if (Subtarget->hasSSE41()) {
17612         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17613         V0 = DAG.getBitcast(ExtVT, V0);
17614         V1 = DAG.getBitcast(ExtVT, V1);
17615         Sel = DAG.getBitcast(ExtVT, Sel);
17616         return DAG.getBitcast(
17617             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17618       }
17619       // On pre-SSE41 targets we splat the sign bit - a negative value will
17620       // set all bits of the lanes to true and VSELECT uses that in
17621       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17622       SDValue C =
17623           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17624       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17625     };
17626
17627     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17628     if (Subtarget->hasSSE41()) {
17629       // On SSE41 targets we need to replicate the shift mask in both
17630       // bytes for PBLENDVB.
17631       Amt = DAG.getNode(
17632           ISD::OR, dl, VT,
17633           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17634           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17635     } else {
17636       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17637     }
17638
17639     // r = VSELECT(r, shift(r, 8), a);
17640     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17641     R = SignBitSelect(Amt, M, R);
17642
17643     // a += a
17644     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17645
17646     // r = VSELECT(r, shift(r, 4), a);
17647     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17648     R = SignBitSelect(Amt, M, R);
17649
17650     // a += a
17651     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17652
17653     // r = VSELECT(r, shift(r, 2), a);
17654     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17655     R = SignBitSelect(Amt, M, R);
17656
17657     // a += a
17658     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17659
17660     // return VSELECT(r, shift(r, 1), a);
17661     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17662     R = SignBitSelect(Amt, M, R);
17663     return R;
17664   }
17665
17666   // Decompose 256-bit shifts into smaller 128-bit shifts.
17667   if (VT.is256BitVector()) {
17668     unsigned NumElems = VT.getVectorNumElements();
17669     MVT EltVT = VT.getVectorElementType();
17670     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17671
17672     // Extract the two vectors
17673     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17674     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17675
17676     // Recreate the shift amount vectors
17677     SDValue Amt1, Amt2;
17678     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17679       // Constant shift amount
17680       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17681       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17682       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17683
17684       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17685       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17686     } else {
17687       // Variable shift amount
17688       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17689       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17690     }
17691
17692     // Issue new vector shifts for the smaller types
17693     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17694     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17695
17696     // Concatenate the result back
17697     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17698   }
17699
17700   return SDValue();
17701 }
17702
17703 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17704   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17705   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17706   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17707   // has only one use.
17708   SDNode *N = Op.getNode();
17709   SDValue LHS = N->getOperand(0);
17710   SDValue RHS = N->getOperand(1);
17711   unsigned BaseOp = 0;
17712   unsigned Cond = 0;
17713   SDLoc DL(Op);
17714   switch (Op.getOpcode()) {
17715   default: llvm_unreachable("Unknown ovf instruction!");
17716   case ISD::SADDO:
17717     // A subtract of one will be selected as a INC. Note that INC doesn't
17718     // set CF, so we can't do this for UADDO.
17719     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17720       if (C->isOne()) {
17721         BaseOp = X86ISD::INC;
17722         Cond = X86::COND_O;
17723         break;
17724       }
17725     BaseOp = X86ISD::ADD;
17726     Cond = X86::COND_O;
17727     break;
17728   case ISD::UADDO:
17729     BaseOp = X86ISD::ADD;
17730     Cond = X86::COND_B;
17731     break;
17732   case ISD::SSUBO:
17733     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17734     // set CF, so we can't do this for USUBO.
17735     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17736       if (C->isOne()) {
17737         BaseOp = X86ISD::DEC;
17738         Cond = X86::COND_O;
17739         break;
17740       }
17741     BaseOp = X86ISD::SUB;
17742     Cond = X86::COND_O;
17743     break;
17744   case ISD::USUBO:
17745     BaseOp = X86ISD::SUB;
17746     Cond = X86::COND_B;
17747     break;
17748   case ISD::SMULO:
17749     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17750     Cond = X86::COND_O;
17751     break;
17752   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17753     if (N->getValueType(0) == MVT::i8) {
17754       BaseOp = X86ISD::UMUL8;
17755       Cond = X86::COND_O;
17756       break;
17757     }
17758     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17759                                  MVT::i32);
17760     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17761
17762     SDValue SetCC =
17763       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17764                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17765                   SDValue(Sum.getNode(), 2));
17766
17767     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17768   }
17769   }
17770
17771   // Also sets EFLAGS.
17772   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17773   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17774
17775   SDValue SetCC =
17776     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17777                 DAG.getConstant(Cond, DL, MVT::i32),
17778                 SDValue(Sum.getNode(), 1));
17779
17780   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17781 }
17782
17783 /// Returns true if the operand type is exactly twice the native width, and
17784 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17785 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17786 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17787 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17788   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17789
17790   if (OpWidth == 64)
17791     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17792   else if (OpWidth == 128)
17793     return Subtarget->hasCmpxchg16b();
17794   else
17795     return false;
17796 }
17797
17798 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17799   return needsCmpXchgNb(SI->getValueOperand()->getType());
17800 }
17801
17802 // Note: this turns large loads into lock cmpxchg8b/16b.
17803 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17804 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17805   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17806   return needsCmpXchgNb(PTy->getElementType());
17807 }
17808
17809 TargetLoweringBase::AtomicRMWExpansionKind
17810 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17811   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17812   const Type *MemType = AI->getType();
17813
17814   // If the operand is too big, we must see if cmpxchg8/16b is available
17815   // and default to library calls otherwise.
17816   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17817     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17818                                    : AtomicRMWExpansionKind::None;
17819   }
17820
17821   AtomicRMWInst::BinOp Op = AI->getOperation();
17822   switch (Op) {
17823   default:
17824     llvm_unreachable("Unknown atomic operation");
17825   case AtomicRMWInst::Xchg:
17826   case AtomicRMWInst::Add:
17827   case AtomicRMWInst::Sub:
17828     // It's better to use xadd, xsub or xchg for these in all cases.
17829     return AtomicRMWExpansionKind::None;
17830   case AtomicRMWInst::Or:
17831   case AtomicRMWInst::And:
17832   case AtomicRMWInst::Xor:
17833     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17834     // prefix to a normal instruction for these operations.
17835     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17836                             : AtomicRMWExpansionKind::None;
17837   case AtomicRMWInst::Nand:
17838   case AtomicRMWInst::Max:
17839   case AtomicRMWInst::Min:
17840   case AtomicRMWInst::UMax:
17841   case AtomicRMWInst::UMin:
17842     // These always require a non-trivial set of data operations on x86. We must
17843     // use a cmpxchg loop.
17844     return AtomicRMWExpansionKind::CmpXChg;
17845   }
17846 }
17847
17848 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17849   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17850   // no-sse2). There isn't any reason to disable it if the target processor
17851   // supports it.
17852   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17853 }
17854
17855 LoadInst *
17856 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17857   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17858   const Type *MemType = AI->getType();
17859   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17860   // there is no benefit in turning such RMWs into loads, and it is actually
17861   // harmful as it introduces a mfence.
17862   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17863     return nullptr;
17864
17865   auto Builder = IRBuilder<>(AI);
17866   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17867   auto SynchScope = AI->getSynchScope();
17868   // We must restrict the ordering to avoid generating loads with Release or
17869   // ReleaseAcquire orderings.
17870   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17871   auto Ptr = AI->getPointerOperand();
17872
17873   // Before the load we need a fence. Here is an example lifted from
17874   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17875   // is required:
17876   // Thread 0:
17877   //   x.store(1, relaxed);
17878   //   r1 = y.fetch_add(0, release);
17879   // Thread 1:
17880   //   y.fetch_add(42, acquire);
17881   //   r2 = x.load(relaxed);
17882   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17883   // lowered to just a load without a fence. A mfence flushes the store buffer,
17884   // making the optimization clearly correct.
17885   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17886   // otherwise, we might be able to be more agressive on relaxed idempotent
17887   // rmw. In practice, they do not look useful, so we don't try to be
17888   // especially clever.
17889   if (SynchScope == SingleThread)
17890     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17891     // the IR level, so we must wrap it in an intrinsic.
17892     return nullptr;
17893
17894   if (!hasMFENCE(*Subtarget))
17895     // FIXME: it might make sense to use a locked operation here but on a
17896     // different cache-line to prevent cache-line bouncing. In practice it
17897     // is probably a small win, and x86 processors without mfence are rare
17898     // enough that we do not bother.
17899     return nullptr;
17900
17901   Function *MFence =
17902       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17903   Builder.CreateCall(MFence, {});
17904
17905   // Finally we can emit the atomic load.
17906   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17907           AI->getType()->getPrimitiveSizeInBits());
17908   Loaded->setAtomic(Order, SynchScope);
17909   AI->replaceAllUsesWith(Loaded);
17910   AI->eraseFromParent();
17911   return Loaded;
17912 }
17913
17914 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17915                                  SelectionDAG &DAG) {
17916   SDLoc dl(Op);
17917   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17918     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17919   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17920     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17921
17922   // The only fence that needs an instruction is a sequentially-consistent
17923   // cross-thread fence.
17924   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17925     if (hasMFENCE(*Subtarget))
17926       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17927
17928     SDValue Chain = Op.getOperand(0);
17929     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17930     SDValue Ops[] = {
17931       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17932       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17933       DAG.getRegister(0, MVT::i32),            // Index
17934       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17935       DAG.getRegister(0, MVT::i32),            // Segment.
17936       Zero,
17937       Chain
17938     };
17939     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17940     return SDValue(Res, 0);
17941   }
17942
17943   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17944   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17945 }
17946
17947 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17948                              SelectionDAG &DAG) {
17949   MVT T = Op.getSimpleValueType();
17950   SDLoc DL(Op);
17951   unsigned Reg = 0;
17952   unsigned size = 0;
17953   switch(T.SimpleTy) {
17954   default: llvm_unreachable("Invalid value type!");
17955   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17956   case MVT::i16: Reg = X86::AX;  size = 2; break;
17957   case MVT::i32: Reg = X86::EAX; size = 4; break;
17958   case MVT::i64:
17959     assert(Subtarget->is64Bit() && "Node not type legal!");
17960     Reg = X86::RAX; size = 8;
17961     break;
17962   }
17963   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17964                                   Op.getOperand(2), SDValue());
17965   SDValue Ops[] = { cpIn.getValue(0),
17966                     Op.getOperand(1),
17967                     Op.getOperand(3),
17968                     DAG.getTargetConstant(size, DL, MVT::i8),
17969                     cpIn.getValue(1) };
17970   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17971   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17972   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17973                                            Ops, T, MMO);
17974
17975   SDValue cpOut =
17976     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17977   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17978                                       MVT::i32, cpOut.getValue(2));
17979   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17980                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17981                                 EFLAGS);
17982
17983   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17984   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17985   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17986   return SDValue();
17987 }
17988
17989 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17990                             SelectionDAG &DAG) {
17991   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17992   MVT DstVT = Op.getSimpleValueType();
17993
17994   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17995     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17996     if (DstVT != MVT::f64)
17997       // This conversion needs to be expanded.
17998       return SDValue();
17999
18000     SDValue InVec = Op->getOperand(0);
18001     SDLoc dl(Op);
18002     unsigned NumElts = SrcVT.getVectorNumElements();
18003     EVT SVT = SrcVT.getVectorElementType();
18004
18005     // Widen the vector in input in the case of MVT::v2i32.
18006     // Example: from MVT::v2i32 to MVT::v4i32.
18007     SmallVector<SDValue, 16> Elts;
18008     for (unsigned i = 0, e = NumElts; i != e; ++i)
18009       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
18010                                  DAG.getIntPtrConstant(i, dl)));
18011
18012     // Explicitly mark the extra elements as Undef.
18013     Elts.append(NumElts, DAG.getUNDEF(SVT));
18014
18015     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18016     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
18017     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
18018     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
18019                        DAG.getIntPtrConstant(0, dl));
18020   }
18021
18022   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
18023          Subtarget->hasMMX() && "Unexpected custom BITCAST");
18024   assert((DstVT == MVT::i64 ||
18025           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
18026          "Unexpected custom BITCAST");
18027   // i64 <=> MMX conversions are Legal.
18028   if (SrcVT==MVT::i64 && DstVT.isVector())
18029     return Op;
18030   if (DstVT==MVT::i64 && SrcVT.isVector())
18031     return Op;
18032   // MMX <=> MMX conversions are Legal.
18033   if (SrcVT.isVector() && DstVT.isVector())
18034     return Op;
18035   // All other conversions need to be expanded.
18036   return SDValue();
18037 }
18038
18039 /// Compute the horizontal sum of bytes in V for the elements of VT.
18040 ///
18041 /// Requires V to be a byte vector and VT to be an integer vector type with
18042 /// wider elements than V's type. The width of the elements of VT determines
18043 /// how many bytes of V are summed horizontally to produce each element of the
18044 /// result.
18045 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
18046                                       const X86Subtarget *Subtarget,
18047                                       SelectionDAG &DAG) {
18048   SDLoc DL(V);
18049   MVT ByteVecVT = V.getSimpleValueType();
18050   MVT EltVT = VT.getVectorElementType();
18051   int NumElts = VT.getVectorNumElements();
18052   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
18053          "Expected value to have byte element type.");
18054   assert(EltVT != MVT::i8 &&
18055          "Horizontal byte sum only makes sense for wider elements!");
18056   unsigned VecSize = VT.getSizeInBits();
18057   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
18058
18059   // PSADBW instruction horizontally add all bytes and leave the result in i64
18060   // chunks, thus directly computes the pop count for v2i64 and v4i64.
18061   if (EltVT == MVT::i64) {
18062     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18063     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
18064     return DAG.getBitcast(VT, V);
18065   }
18066
18067   if (EltVT == MVT::i32) {
18068     // We unpack the low half and high half into i32s interleaved with zeros so
18069     // that we can use PSADBW to horizontally sum them. The most useful part of
18070     // this is that it lines up the results of two PSADBW instructions to be
18071     // two v2i64 vectors which concatenated are the 4 population counts. We can
18072     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
18073     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
18074     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
18075     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
18076
18077     // Do the horizontal sums into two v2i64s.
18078     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
18079     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18080                       DAG.getBitcast(ByteVecVT, Low), Zeros);
18081     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
18082                        DAG.getBitcast(ByteVecVT, High), Zeros);
18083
18084     // Merge them together.
18085     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
18086     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
18087                     DAG.getBitcast(ShortVecVT, Low),
18088                     DAG.getBitcast(ShortVecVT, High));
18089
18090     return DAG.getBitcast(VT, V);
18091   }
18092
18093   // The only element type left is i16.
18094   assert(EltVT == MVT::i16 && "Unknown how to handle type");
18095
18096   // To obtain pop count for each i16 element starting from the pop count for
18097   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
18098   // right by 8. It is important to shift as i16s as i8 vector shift isn't
18099   // directly supported.
18100   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
18101   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
18102   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18103   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
18104                   DAG.getBitcast(ByteVecVT, V));
18105   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
18106 }
18107
18108 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
18109                                         const X86Subtarget *Subtarget,
18110                                         SelectionDAG &DAG) {
18111   MVT VT = Op.getSimpleValueType();
18112   MVT EltVT = VT.getVectorElementType();
18113   unsigned VecSize = VT.getSizeInBits();
18114
18115   // Implement a lookup table in register by using an algorithm based on:
18116   // http://wm.ite.pl/articles/sse-popcount.html
18117   //
18118   // The general idea is that every lower byte nibble in the input vector is an
18119   // index into a in-register pre-computed pop count table. We then split up the
18120   // input vector in two new ones: (1) a vector with only the shifted-right
18121   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
18122   // masked out higher ones) for each byte. PSHUB is used separately with both
18123   // to index the in-register table. Next, both are added and the result is a
18124   // i8 vector where each element contains the pop count for input byte.
18125   //
18126   // To obtain the pop count for elements != i8, we follow up with the same
18127   // approach and use additional tricks as described below.
18128   //
18129   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
18130                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
18131                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
18132                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
18133
18134   int NumByteElts = VecSize / 8;
18135   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
18136   SDValue In = DAG.getBitcast(ByteVecVT, Op);
18137   SmallVector<SDValue, 16> LUTVec;
18138   for (int i = 0; i < NumByteElts; ++i)
18139     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
18140   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
18141   SmallVector<SDValue, 16> Mask0F(NumByteElts,
18142                                   DAG.getConstant(0x0F, DL, MVT::i8));
18143   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
18144
18145   // High nibbles
18146   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
18147   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
18148   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
18149
18150   // Low nibbles
18151   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
18152
18153   // The input vector is used as the shuffle mask that index elements into the
18154   // LUT. After counting low and high nibbles, add the vector to obtain the
18155   // final pop count per i8 element.
18156   SDValue HighPopCnt =
18157       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
18158   SDValue LowPopCnt =
18159       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
18160   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
18161
18162   if (EltVT == MVT::i8)
18163     return PopCnt;
18164
18165   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
18166 }
18167
18168 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
18169                                        const X86Subtarget *Subtarget,
18170                                        SelectionDAG &DAG) {
18171   MVT VT = Op.getSimpleValueType();
18172   assert(VT.is128BitVector() &&
18173          "Only 128-bit vector bitmath lowering supported.");
18174
18175   int VecSize = VT.getSizeInBits();
18176   MVT EltVT = VT.getVectorElementType();
18177   int Len = EltVT.getSizeInBits();
18178
18179   // This is the vectorized version of the "best" algorithm from
18180   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
18181   // with a minor tweak to use a series of adds + shifts instead of vector
18182   // multiplications. Implemented for all integer vector types. We only use
18183   // this when we don't have SSSE3 which allows a LUT-based lowering that is
18184   // much faster, even faster than using native popcnt instructions.
18185
18186   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
18187     MVT VT = V.getSimpleValueType();
18188     SmallVector<SDValue, 32> Shifters(
18189         VT.getVectorNumElements(),
18190         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
18191     return DAG.getNode(OpCode, DL, VT, V,
18192                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
18193   };
18194   auto GetMask = [&](SDValue V, APInt Mask) {
18195     MVT VT = V.getSimpleValueType();
18196     SmallVector<SDValue, 32> Masks(
18197         VT.getVectorNumElements(),
18198         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
18199     return DAG.getNode(ISD::AND, DL, VT, V,
18200                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
18201   };
18202
18203   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
18204   // x86, so set the SRL type to have elements at least i16 wide. This is
18205   // correct because all of our SRLs are followed immediately by a mask anyways
18206   // that handles any bits that sneak into the high bits of the byte elements.
18207   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
18208
18209   SDValue V = Op;
18210
18211   // v = v - ((v >> 1) & 0x55555555...)
18212   SDValue Srl =
18213       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
18214   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
18215   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
18216
18217   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
18218   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
18219   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
18220   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
18221   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
18222
18223   // v = (v + (v >> 4)) & 0x0F0F0F0F...
18224   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
18225   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
18226   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
18227
18228   // At this point, V contains the byte-wise population count, and we are
18229   // merely doing a horizontal sum if necessary to get the wider element
18230   // counts.
18231   if (EltVT == MVT::i8)
18232     return V;
18233
18234   return LowerHorizontalByteSum(
18235       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
18236       DAG);
18237 }
18238
18239 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18240                                 SelectionDAG &DAG) {
18241   MVT VT = Op.getSimpleValueType();
18242   // FIXME: Need to add AVX-512 support here!
18243   assert((VT.is256BitVector() || VT.is128BitVector()) &&
18244          "Unknown CTPOP type to handle");
18245   SDLoc DL(Op.getNode());
18246   SDValue Op0 = Op.getOperand(0);
18247
18248   if (!Subtarget->hasSSSE3()) {
18249     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
18250     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
18251     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
18252   }
18253
18254   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
18255     unsigned NumElems = VT.getVectorNumElements();
18256
18257     // Extract each 128-bit vector, compute pop count and concat the result.
18258     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
18259     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
18260
18261     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
18262                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
18263                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
18264   }
18265
18266   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
18267 }
18268
18269 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
18270                           SelectionDAG &DAG) {
18271   assert(Op.getValueType().isVector() &&
18272          "We only do custom lowering for vector population count.");
18273   return LowerVectorCTPOP(Op, Subtarget, DAG);
18274 }
18275
18276 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
18277   SDNode *Node = Op.getNode();
18278   SDLoc dl(Node);
18279   EVT T = Node->getValueType(0);
18280   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
18281                               DAG.getConstant(0, dl, T), Node->getOperand(2));
18282   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
18283                        cast<AtomicSDNode>(Node)->getMemoryVT(),
18284                        Node->getOperand(0),
18285                        Node->getOperand(1), negOp,
18286                        cast<AtomicSDNode>(Node)->getMemOperand(),
18287                        cast<AtomicSDNode>(Node)->getOrdering(),
18288                        cast<AtomicSDNode>(Node)->getSynchScope());
18289 }
18290
18291 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
18292   SDNode *Node = Op.getNode();
18293   SDLoc dl(Node);
18294   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
18295
18296   // Convert seq_cst store -> xchg
18297   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
18298   // FIXME: On 32-bit, store -> fist or movq would be more efficient
18299   //        (The only way to get a 16-byte store is cmpxchg16b)
18300   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
18301   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
18302       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
18303     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
18304                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
18305                                  Node->getOperand(0),
18306                                  Node->getOperand(1), Node->getOperand(2),
18307                                  cast<AtomicSDNode>(Node)->getMemOperand(),
18308                                  cast<AtomicSDNode>(Node)->getOrdering(),
18309                                  cast<AtomicSDNode>(Node)->getSynchScope());
18310     return Swap.getValue(1);
18311   }
18312   // Other atomic stores have a simple pattern.
18313   return Op;
18314 }
18315
18316 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
18317   EVT VT = Op.getNode()->getSimpleValueType(0);
18318
18319   // Let legalize expand this if it isn't a legal type yet.
18320   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
18321     return SDValue();
18322
18323   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
18324
18325   unsigned Opc;
18326   bool ExtraOp = false;
18327   switch (Op.getOpcode()) {
18328   default: llvm_unreachable("Invalid code");
18329   case ISD::ADDC: Opc = X86ISD::ADD; break;
18330   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
18331   case ISD::SUBC: Opc = X86ISD::SUB; break;
18332   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
18333   }
18334
18335   if (!ExtraOp)
18336     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18337                        Op.getOperand(1));
18338   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
18339                      Op.getOperand(1), Op.getOperand(2));
18340 }
18341
18342 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
18343                             SelectionDAG &DAG) {
18344   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
18345
18346   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
18347   // which returns the values as { float, float } (in XMM0) or
18348   // { double, double } (which is returned in XMM0, XMM1).
18349   SDLoc dl(Op);
18350   SDValue Arg = Op.getOperand(0);
18351   EVT ArgVT = Arg.getValueType();
18352   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
18353
18354   TargetLowering::ArgListTy Args;
18355   TargetLowering::ArgListEntry Entry;
18356
18357   Entry.Node = Arg;
18358   Entry.Ty = ArgTy;
18359   Entry.isSExt = false;
18360   Entry.isZExt = false;
18361   Args.push_back(Entry);
18362
18363   bool isF64 = ArgVT == MVT::f64;
18364   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18365   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18366   // the results are returned via SRet in memory.
18367   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18368   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18369   SDValue Callee =
18370       DAG.getExternalSymbol(LibcallName, TLI.getPointerTy(DAG.getDataLayout()));
18371
18372   Type *RetTy = isF64
18373     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18374     : (Type*)VectorType::get(ArgTy, 4);
18375
18376   TargetLowering::CallLoweringInfo CLI(DAG);
18377   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18378     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18379
18380   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18381
18382   if (isF64)
18383     // Returned in xmm0 and xmm1.
18384     return CallResult.first;
18385
18386   // Returned in bits 0:31 and 32:64 xmm0.
18387   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18388                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18389   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18390                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18391   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18392   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18393 }
18394
18395 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18396                              SelectionDAG &DAG) {
18397   assert(Subtarget->hasAVX512() &&
18398          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18399
18400   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18401   EVT VT = N->getValue().getValueType();
18402   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18403   SDLoc dl(Op);
18404
18405   // X86 scatter kills mask register, so its type should be added to
18406   // the list of return values
18407   if (N->getNumValues() == 1) {
18408     SDValue Index = N->getIndex();
18409     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18410         !Index.getValueType().is512BitVector())
18411       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18412
18413     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18414     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18415                       N->getOperand(3), Index };
18416
18417     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18418     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18419     return SDValue(NewScatter.getNode(), 0);
18420   }
18421   return Op;
18422 }
18423
18424 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18425                             SelectionDAG &DAG) {
18426   assert(Subtarget->hasAVX512() &&
18427          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18428
18429   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18430   EVT VT = Op.getValueType();
18431   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18432   SDLoc dl(Op);
18433
18434   SDValue Index = N->getIndex();
18435   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18436       !Index.getValueType().is512BitVector()) {
18437     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18438     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18439                       N->getOperand(3), Index };
18440     DAG.UpdateNodeOperands(N, Ops);
18441   }
18442   return Op;
18443 }
18444
18445 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18446                                                     SelectionDAG &DAG) const {
18447   // TODO: Eventually, the lowering of these nodes should be informed by or
18448   // deferred to the GC strategy for the function in which they appear. For
18449   // now, however, they must be lowered to something. Since they are logically
18450   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18451   // require special handling for these nodes), lower them as literal NOOPs for
18452   // the time being.
18453   SmallVector<SDValue, 2> Ops;
18454
18455   Ops.push_back(Op.getOperand(0));
18456   if (Op->getGluedNode())
18457     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18458
18459   SDLoc OpDL(Op);
18460   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18461   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18462
18463   return NOOP;
18464 }
18465
18466 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18467                                                   SelectionDAG &DAG) const {
18468   // TODO: Eventually, the lowering of these nodes should be informed by or
18469   // deferred to the GC strategy for the function in which they appear. For
18470   // now, however, they must be lowered to something. Since they are logically
18471   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18472   // require special handling for these nodes), lower them as literal NOOPs for
18473   // the time being.
18474   SmallVector<SDValue, 2> Ops;
18475
18476   Ops.push_back(Op.getOperand(0));
18477   if (Op->getGluedNode())
18478     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18479
18480   SDLoc OpDL(Op);
18481   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18482   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18483
18484   return NOOP;
18485 }
18486
18487 /// LowerOperation - Provide custom lowering hooks for some operations.
18488 ///
18489 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18490   switch (Op.getOpcode()) {
18491   default: llvm_unreachable("Should not custom lower this!");
18492   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18493   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18494     return LowerCMP_SWAP(Op, Subtarget, DAG);
18495   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18496   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18497   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18498   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18499   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18500   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18501   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18502   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18503   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18504   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18505   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18506   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18507   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18508   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18509   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18510   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18511   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18512   case ISD::SHL_PARTS:
18513   case ISD::SRA_PARTS:
18514   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18515   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18516   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18517   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18518   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18519   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18520   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18521   case ISD::SIGN_EXTEND_VECTOR_INREG:
18522     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18523   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18524   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18525   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18526   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18527   case ISD::FABS:
18528   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18529   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18530   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18531   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18532   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18533   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18534   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18535   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18536   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18537   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18538   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18539   case ISD::INTRINSIC_VOID:
18540   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18541   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18542   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18543   case ISD::FRAME_TO_ARGS_OFFSET:
18544                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18545   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18546   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18547   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18548   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18549   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18550   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18551   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18552   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18553   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18554   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18555   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18556   case ISD::UMUL_LOHI:
18557   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18558   case ISD::SRA:
18559   case ISD::SRL:
18560   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18561   case ISD::SADDO:
18562   case ISD::UADDO:
18563   case ISD::SSUBO:
18564   case ISD::USUBO:
18565   case ISD::SMULO:
18566   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18567   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18568   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18569   case ISD::ADDC:
18570   case ISD::ADDE:
18571   case ISD::SUBC:
18572   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18573   case ISD::ADD:                return LowerADD(Op, DAG);
18574   case ISD::SUB:                return LowerSUB(Op, DAG);
18575   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18576   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18577   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18578   case ISD::GC_TRANSITION_START:
18579                                 return LowerGC_TRANSITION_START(Op, DAG);
18580   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18581   }
18582 }
18583
18584 /// ReplaceNodeResults - Replace a node with an illegal result type
18585 /// with a new node built out of custom code.
18586 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18587                                            SmallVectorImpl<SDValue>&Results,
18588                                            SelectionDAG &DAG) const {
18589   SDLoc dl(N);
18590   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18591   switch (N->getOpcode()) {
18592   default:
18593     llvm_unreachable("Do not know how to custom type legalize this operation!");
18594   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18595   case X86ISD::FMINC:
18596   case X86ISD::FMIN:
18597   case X86ISD::FMAXC:
18598   case X86ISD::FMAX: {
18599     EVT VT = N->getValueType(0);
18600     if (VT != MVT::v2f32)
18601       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18602     SDValue UNDEF = DAG.getUNDEF(VT);
18603     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18604                               N->getOperand(0), UNDEF);
18605     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18606                               N->getOperand(1), UNDEF);
18607     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18608     return;
18609   }
18610   case ISD::SIGN_EXTEND_INREG:
18611   case ISD::ADDC:
18612   case ISD::ADDE:
18613   case ISD::SUBC:
18614   case ISD::SUBE:
18615     // We don't want to expand or promote these.
18616     return;
18617   case ISD::SDIV:
18618   case ISD::UDIV:
18619   case ISD::SREM:
18620   case ISD::UREM:
18621   case ISD::SDIVREM:
18622   case ISD::UDIVREM: {
18623     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18624     Results.push_back(V);
18625     return;
18626   }
18627   case ISD::FP_TO_SINT:
18628     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18629     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18630     if (N->getOperand(0).getValueType() == MVT::f16)
18631       break;
18632     // fallthrough
18633   case ISD::FP_TO_UINT: {
18634     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18635
18636     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18637       return;
18638
18639     std::pair<SDValue,SDValue> Vals =
18640         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18641     SDValue FIST = Vals.first, StackSlot = Vals.second;
18642     if (FIST.getNode()) {
18643       EVT VT = N->getValueType(0);
18644       // Return a load from the stack slot.
18645       if (StackSlot.getNode())
18646         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18647                                       MachinePointerInfo(),
18648                                       false, false, false, 0));
18649       else
18650         Results.push_back(FIST);
18651     }
18652     return;
18653   }
18654   case ISD::UINT_TO_FP: {
18655     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18656     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18657         N->getValueType(0) != MVT::v2f32)
18658       return;
18659     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18660                                  N->getOperand(0));
18661     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18662                                      MVT::f64);
18663     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18664     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18665                              DAG.getBitcast(MVT::v2i64, VBias));
18666     Or = DAG.getBitcast(MVT::v2f64, Or);
18667     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18668     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18669     return;
18670   }
18671   case ISD::FP_ROUND: {
18672     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18673         return;
18674     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18675     Results.push_back(V);
18676     return;
18677   }
18678   case ISD::FP_EXTEND: {
18679     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18680     // No other ValueType for FP_EXTEND should reach this point.
18681     assert(N->getValueType(0) == MVT::v2f32 &&
18682            "Do not know how to legalize this Node");
18683     return;
18684   }
18685   case ISD::INTRINSIC_W_CHAIN: {
18686     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18687     switch (IntNo) {
18688     default : llvm_unreachable("Do not know how to custom type "
18689                                "legalize this intrinsic operation!");
18690     case Intrinsic::x86_rdtsc:
18691       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18692                                      Results);
18693     case Intrinsic::x86_rdtscp:
18694       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18695                                      Results);
18696     case Intrinsic::x86_rdpmc:
18697       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18698     }
18699   }
18700   case ISD::READCYCLECOUNTER: {
18701     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18702                                    Results);
18703   }
18704   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18705     EVT T = N->getValueType(0);
18706     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18707     bool Regs64bit = T == MVT::i128;
18708     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18709     SDValue cpInL, cpInH;
18710     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18711                         DAG.getConstant(0, dl, HalfT));
18712     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18713                         DAG.getConstant(1, dl, HalfT));
18714     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18715                              Regs64bit ? X86::RAX : X86::EAX,
18716                              cpInL, SDValue());
18717     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18718                              Regs64bit ? X86::RDX : X86::EDX,
18719                              cpInH, cpInL.getValue(1));
18720     SDValue swapInL, swapInH;
18721     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18722                           DAG.getConstant(0, dl, HalfT));
18723     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18724                           DAG.getConstant(1, dl, HalfT));
18725     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18726                                Regs64bit ? X86::RBX : X86::EBX,
18727                                swapInL, cpInH.getValue(1));
18728     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18729                                Regs64bit ? X86::RCX : X86::ECX,
18730                                swapInH, swapInL.getValue(1));
18731     SDValue Ops[] = { swapInH.getValue(0),
18732                       N->getOperand(1),
18733                       swapInH.getValue(1) };
18734     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18735     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18736     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18737                                   X86ISD::LCMPXCHG8_DAG;
18738     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18739     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18740                                         Regs64bit ? X86::RAX : X86::EAX,
18741                                         HalfT, Result.getValue(1));
18742     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18743                                         Regs64bit ? X86::RDX : X86::EDX,
18744                                         HalfT, cpOutL.getValue(2));
18745     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18746
18747     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18748                                         MVT::i32, cpOutH.getValue(2));
18749     SDValue Success =
18750         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18751                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18752     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18753
18754     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18755     Results.push_back(Success);
18756     Results.push_back(EFLAGS.getValue(1));
18757     return;
18758   }
18759   case ISD::ATOMIC_SWAP:
18760   case ISD::ATOMIC_LOAD_ADD:
18761   case ISD::ATOMIC_LOAD_SUB:
18762   case ISD::ATOMIC_LOAD_AND:
18763   case ISD::ATOMIC_LOAD_OR:
18764   case ISD::ATOMIC_LOAD_XOR:
18765   case ISD::ATOMIC_LOAD_NAND:
18766   case ISD::ATOMIC_LOAD_MIN:
18767   case ISD::ATOMIC_LOAD_MAX:
18768   case ISD::ATOMIC_LOAD_UMIN:
18769   case ISD::ATOMIC_LOAD_UMAX:
18770   case ISD::ATOMIC_LOAD: {
18771     // Delegate to generic TypeLegalization. Situations we can really handle
18772     // should have already been dealt with by AtomicExpandPass.cpp.
18773     break;
18774   }
18775   case ISD::BITCAST: {
18776     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18777     EVT DstVT = N->getValueType(0);
18778     EVT SrcVT = N->getOperand(0)->getValueType(0);
18779
18780     if (SrcVT != MVT::f64 ||
18781         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18782       return;
18783
18784     unsigned NumElts = DstVT.getVectorNumElements();
18785     EVT SVT = DstVT.getVectorElementType();
18786     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18787     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18788                                    MVT::v2f64, N->getOperand(0));
18789     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18790
18791     if (ExperimentalVectorWideningLegalization) {
18792       // If we are legalizing vectors by widening, we already have the desired
18793       // legal vector type, just return it.
18794       Results.push_back(ToVecInt);
18795       return;
18796     }
18797
18798     SmallVector<SDValue, 8> Elts;
18799     for (unsigned i = 0, e = NumElts; i != e; ++i)
18800       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18801                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18802
18803     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18804   }
18805   }
18806 }
18807
18808 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18809   switch ((X86ISD::NodeType)Opcode) {
18810   case X86ISD::FIRST_NUMBER:       break;
18811   case X86ISD::BSF:                return "X86ISD::BSF";
18812   case X86ISD::BSR:                return "X86ISD::BSR";
18813   case X86ISD::SHLD:               return "X86ISD::SHLD";
18814   case X86ISD::SHRD:               return "X86ISD::SHRD";
18815   case X86ISD::FAND:               return "X86ISD::FAND";
18816   case X86ISD::FANDN:              return "X86ISD::FANDN";
18817   case X86ISD::FOR:                return "X86ISD::FOR";
18818   case X86ISD::FXOR:               return "X86ISD::FXOR";
18819   case X86ISD::FILD:               return "X86ISD::FILD";
18820   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18821   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18822   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18823   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18824   case X86ISD::FLD:                return "X86ISD::FLD";
18825   case X86ISD::FST:                return "X86ISD::FST";
18826   case X86ISD::CALL:               return "X86ISD::CALL";
18827   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18828   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18829   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18830   case X86ISD::BT:                 return "X86ISD::BT";
18831   case X86ISD::CMP:                return "X86ISD::CMP";
18832   case X86ISD::COMI:               return "X86ISD::COMI";
18833   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18834   case X86ISD::CMPM:               return "X86ISD::CMPM";
18835   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18836   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18837   case X86ISD::SETCC:              return "X86ISD::SETCC";
18838   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18839   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18840   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18841   case X86ISD::CMOV:               return "X86ISD::CMOV";
18842   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18843   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18844   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18845   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18846   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18847   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18848   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18849   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18850   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18851   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18852   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18853   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18854   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18855   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18856   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18857   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18858   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18859   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18860   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18861   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18862   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18863   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18864   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18865   case X86ISD::HADD:               return "X86ISD::HADD";
18866   case X86ISD::HSUB:               return "X86ISD::HSUB";
18867   case X86ISD::FHADD:              return "X86ISD::FHADD";
18868   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18869   case X86ISD::ABS:                return "X86ISD::ABS";
18870   case X86ISD::FMAX:               return "X86ISD::FMAX";
18871   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18872   case X86ISD::FMIN:               return "X86ISD::FMIN";
18873   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18874   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18875   case X86ISD::FMINC:              return "X86ISD::FMINC";
18876   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18877   case X86ISD::FRCP:               return "X86ISD::FRCP";
18878   case X86ISD::EXTRQI:             return "X86ISD::EXTRQI";
18879   case X86ISD::INSERTQI:           return "X86ISD::INSERTQI";
18880   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18881   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18882   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18883   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18884   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18885   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18886   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18887   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18888   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18889   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18890   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18891   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18892   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18893   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18894   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18895   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18896   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18897   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18898   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18899   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18900   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18901   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18902   case X86ISD::CVTUDQ2PD:          return "X86ISD::CVTUDQ2PD";
18903   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18904   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18905   case X86ISD::VSHL:               return "X86ISD::VSHL";
18906   case X86ISD::VSRL:               return "X86ISD::VSRL";
18907   case X86ISD::VSRA:               return "X86ISD::VSRA";
18908   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18909   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18910   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18911   case X86ISD::CMPP:               return "X86ISD::CMPP";
18912   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18913   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18914   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18915   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18916   case X86ISD::ADD:                return "X86ISD::ADD";
18917   case X86ISD::SUB:                return "X86ISD::SUB";
18918   case X86ISD::ADC:                return "X86ISD::ADC";
18919   case X86ISD::SBB:                return "X86ISD::SBB";
18920   case X86ISD::SMUL:               return "X86ISD::SMUL";
18921   case X86ISD::UMUL:               return "X86ISD::UMUL";
18922   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18923   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18924   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18925   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18926   case X86ISD::INC:                return "X86ISD::INC";
18927   case X86ISD::DEC:                return "X86ISD::DEC";
18928   case X86ISD::OR:                 return "X86ISD::OR";
18929   case X86ISD::XOR:                return "X86ISD::XOR";
18930   case X86ISD::AND:                return "X86ISD::AND";
18931   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18932   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18933   case X86ISD::PTEST:              return "X86ISD::PTEST";
18934   case X86ISD::TESTP:              return "X86ISD::TESTP";
18935   case X86ISD::TESTM:              return "X86ISD::TESTM";
18936   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18937   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18938   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18939   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18940   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18941   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18942   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18943   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18944   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18945   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18946   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18947   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18948   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18949   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18950   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18951   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18952   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18953   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18954   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18955   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18956   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18957   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18958   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18959   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18960   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18961   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18962   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18963   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18964   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18965   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18966   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18967   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18968   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18969   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18970   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18971   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18972   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18973   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18974   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18975   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18976   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18977   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18978   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18979   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18980   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18981   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18982   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18983   case X86ISD::SAHF:               return "X86ISD::SAHF";
18984   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18985   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18986   case X86ISD::FMADD:              return "X86ISD::FMADD";
18987   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18988   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18989   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18990   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18991   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18992   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18993   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18994   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18995   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18996   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18997   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18998   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18999   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
19000   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
19001   case X86ISD::XTEST:              return "X86ISD::XTEST";
19002   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
19003   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
19004   case X86ISD::SELECT:             return "X86ISD::SELECT";
19005   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
19006   case X86ISD::RCP28:              return "X86ISD::RCP28";
19007   case X86ISD::EXP2:               return "X86ISD::EXP2";
19008   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
19009   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
19010   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
19011   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
19012   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
19013   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
19014   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
19015   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
19016   case X86ISD::ADDS:               return "X86ISD::ADDS";
19017   case X86ISD::SUBS:               return "X86ISD::SUBS";
19018   case X86ISD::AVG:                return "X86ISD::AVG";
19019   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
19020   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
19021   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
19022   case X86ISD::FP_TO_SINT_RND:     return "X86ISD::FP_TO_SINT_RND";
19023   case X86ISD::FP_TO_UINT_RND:     return "X86ISD::FP_TO_UINT_RND";
19024   }
19025   return nullptr;
19026 }
19027
19028 // isLegalAddressingMode - Return true if the addressing mode represented
19029 // by AM is legal for this target, for a load/store of the specified type.
19030 bool X86TargetLowering::isLegalAddressingMode(const DataLayout &DL,
19031                                               const AddrMode &AM, Type *Ty,
19032                                               unsigned AS) const {
19033   // X86 supports extremely general addressing modes.
19034   CodeModel::Model M = getTargetMachine().getCodeModel();
19035   Reloc::Model R = getTargetMachine().getRelocationModel();
19036
19037   // X86 allows a sign-extended 32-bit immediate field as a displacement.
19038   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
19039     return false;
19040
19041   if (AM.BaseGV) {
19042     unsigned GVFlags =
19043       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
19044
19045     // If a reference to this global requires an extra load, we can't fold it.
19046     if (isGlobalStubReference(GVFlags))
19047       return false;
19048
19049     // If BaseGV requires a register for the PIC base, we cannot also have a
19050     // BaseReg specified.
19051     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
19052       return false;
19053
19054     // If lower 4G is not available, then we must use rip-relative addressing.
19055     if ((M != CodeModel::Small || R != Reloc::Static) &&
19056         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
19057       return false;
19058   }
19059
19060   switch (AM.Scale) {
19061   case 0:
19062   case 1:
19063   case 2:
19064   case 4:
19065   case 8:
19066     // These scales always work.
19067     break;
19068   case 3:
19069   case 5:
19070   case 9:
19071     // These scales are formed with basereg+scalereg.  Only accept if there is
19072     // no basereg yet.
19073     if (AM.HasBaseReg)
19074       return false;
19075     break;
19076   default:  // Other stuff never works.
19077     return false;
19078   }
19079
19080   return true;
19081 }
19082
19083 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
19084   unsigned Bits = Ty->getScalarSizeInBits();
19085
19086   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
19087   // particularly cheaper than those without.
19088   if (Bits == 8)
19089     return false;
19090
19091   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
19092   // variable shifts just as cheap as scalar ones.
19093   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
19094     return false;
19095
19096   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
19097   // fully general vector.
19098   return true;
19099 }
19100
19101 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
19102   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19103     return false;
19104   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
19105   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
19106   return NumBits1 > NumBits2;
19107 }
19108
19109 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
19110   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
19111     return false;
19112
19113   if (!isTypeLegal(EVT::getEVT(Ty1)))
19114     return false;
19115
19116   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
19117
19118   // Assuming the caller doesn't have a zeroext or signext return parameter,
19119   // truncation all the way down to i1 is valid.
19120   return true;
19121 }
19122
19123 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
19124   return isInt<32>(Imm);
19125 }
19126
19127 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
19128   // Can also use sub to handle negated immediates.
19129   return isInt<32>(Imm);
19130 }
19131
19132 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
19133   if (!VT1.isInteger() || !VT2.isInteger())
19134     return false;
19135   unsigned NumBits1 = VT1.getSizeInBits();
19136   unsigned NumBits2 = VT2.getSizeInBits();
19137   return NumBits1 > NumBits2;
19138 }
19139
19140 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
19141   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19142   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
19143 }
19144
19145 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
19146   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
19147   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
19148 }
19149
19150 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
19151   EVT VT1 = Val.getValueType();
19152   if (isZExtFree(VT1, VT2))
19153     return true;
19154
19155   if (Val.getOpcode() != ISD::LOAD)
19156     return false;
19157
19158   if (!VT1.isSimple() || !VT1.isInteger() ||
19159       !VT2.isSimple() || !VT2.isInteger())
19160     return false;
19161
19162   switch (VT1.getSimpleVT().SimpleTy) {
19163   default: break;
19164   case MVT::i8:
19165   case MVT::i16:
19166   case MVT::i32:
19167     // X86 has 8, 16, and 32-bit zero-extending loads.
19168     return true;
19169   }
19170
19171   return false;
19172 }
19173
19174 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
19175
19176 bool
19177 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
19178   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
19179     return false;
19180
19181   VT = VT.getScalarType();
19182
19183   if (!VT.isSimple())
19184     return false;
19185
19186   switch (VT.getSimpleVT().SimpleTy) {
19187   case MVT::f32:
19188   case MVT::f64:
19189     return true;
19190   default:
19191     break;
19192   }
19193
19194   return false;
19195 }
19196
19197 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
19198   // i16 instructions are longer (0x66 prefix) and potentially slower.
19199   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
19200 }
19201
19202 /// isShuffleMaskLegal - Targets can use this to indicate that they only
19203 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
19204 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
19205 /// are assumed to be legal.
19206 bool
19207 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
19208                                       EVT VT) const {
19209   if (!VT.isSimple())
19210     return false;
19211
19212   // Not for i1 vectors
19213   if (VT.getScalarType() == MVT::i1)
19214     return false;
19215
19216   // Very little shuffling can be done for 64-bit vectors right now.
19217   if (VT.getSizeInBits() == 64)
19218     return false;
19219
19220   // We only care that the types being shuffled are legal. The lowering can
19221   // handle any possible shuffle mask that results.
19222   return isTypeLegal(VT.getSimpleVT());
19223 }
19224
19225 bool
19226 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
19227                                           EVT VT) const {
19228   // Just delegate to the generic legality, clear masks aren't special.
19229   return isShuffleMaskLegal(Mask, VT);
19230 }
19231
19232 //===----------------------------------------------------------------------===//
19233 //                           X86 Scheduler Hooks
19234 //===----------------------------------------------------------------------===//
19235
19236 /// Utility function to emit xbegin specifying the start of an RTM region.
19237 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
19238                                      const TargetInstrInfo *TII) {
19239   DebugLoc DL = MI->getDebugLoc();
19240
19241   const BasicBlock *BB = MBB->getBasicBlock();
19242   MachineFunction::iterator I = MBB;
19243   ++I;
19244
19245   // For the v = xbegin(), we generate
19246   //
19247   // thisMBB:
19248   //  xbegin sinkMBB
19249   //
19250   // mainMBB:
19251   //  eax = -1
19252   //
19253   // sinkMBB:
19254   //  v = eax
19255
19256   MachineBasicBlock *thisMBB = MBB;
19257   MachineFunction *MF = MBB->getParent();
19258   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19259   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19260   MF->insert(I, mainMBB);
19261   MF->insert(I, sinkMBB);
19262
19263   // Transfer the remainder of BB and its successor edges to sinkMBB.
19264   sinkMBB->splice(sinkMBB->begin(), MBB,
19265                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19266   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19267
19268   // thisMBB:
19269   //  xbegin sinkMBB
19270   //  # fallthrough to mainMBB
19271   //  # abortion to sinkMBB
19272   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
19273   thisMBB->addSuccessor(mainMBB);
19274   thisMBB->addSuccessor(sinkMBB);
19275
19276   // mainMBB:
19277   //  EAX = -1
19278   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
19279   mainMBB->addSuccessor(sinkMBB);
19280
19281   // sinkMBB:
19282   // EAX is live into the sinkMBB
19283   sinkMBB->addLiveIn(X86::EAX);
19284   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19285           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19286     .addReg(X86::EAX);
19287
19288   MI->eraseFromParent();
19289   return sinkMBB;
19290 }
19291
19292 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
19293 // or XMM0_V32I8 in AVX all of this code can be replaced with that
19294 // in the .td file.
19295 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
19296                                        const TargetInstrInfo *TII) {
19297   unsigned Opc;
19298   switch (MI->getOpcode()) {
19299   default: llvm_unreachable("illegal opcode!");
19300   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
19301   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
19302   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
19303   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
19304   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
19305   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
19306   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
19307   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
19308   }
19309
19310   DebugLoc dl = MI->getDebugLoc();
19311   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19312
19313   unsigned NumArgs = MI->getNumOperands();
19314   for (unsigned i = 1; i < NumArgs; ++i) {
19315     MachineOperand &Op = MI->getOperand(i);
19316     if (!(Op.isReg() && Op.isImplicit()))
19317       MIB.addOperand(Op);
19318   }
19319   if (MI->hasOneMemOperand())
19320     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19321
19322   BuildMI(*BB, MI, dl,
19323     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19324     .addReg(X86::XMM0);
19325
19326   MI->eraseFromParent();
19327   return BB;
19328 }
19329
19330 // FIXME: Custom handling because TableGen doesn't support multiple implicit
19331 // defs in an instruction pattern
19332 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
19333                                        const TargetInstrInfo *TII) {
19334   unsigned Opc;
19335   switch (MI->getOpcode()) {
19336   default: llvm_unreachable("illegal opcode!");
19337   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
19338   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
19339   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
19340   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
19341   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
19342   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
19343   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
19344   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
19345   }
19346
19347   DebugLoc dl = MI->getDebugLoc();
19348   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
19349
19350   unsigned NumArgs = MI->getNumOperands(); // remove the results
19351   for (unsigned i = 1; i < NumArgs; ++i) {
19352     MachineOperand &Op = MI->getOperand(i);
19353     if (!(Op.isReg() && Op.isImplicit()))
19354       MIB.addOperand(Op);
19355   }
19356   if (MI->hasOneMemOperand())
19357     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
19358
19359   BuildMI(*BB, MI, dl,
19360     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
19361     .addReg(X86::ECX);
19362
19363   MI->eraseFromParent();
19364   return BB;
19365 }
19366
19367 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
19368                                       const X86Subtarget *Subtarget) {
19369   DebugLoc dl = MI->getDebugLoc();
19370   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19371   // Address into RAX/EAX, other two args into ECX, EDX.
19372   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19373   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19374   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19375   for (int i = 0; i < X86::AddrNumOperands; ++i)
19376     MIB.addOperand(MI->getOperand(i));
19377
19378   unsigned ValOps = X86::AddrNumOperands;
19379   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19380     .addReg(MI->getOperand(ValOps).getReg());
19381   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19382     .addReg(MI->getOperand(ValOps+1).getReg());
19383
19384   // The instruction doesn't actually take any operands though.
19385   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19386
19387   MI->eraseFromParent(); // The pseudo is gone now.
19388   return BB;
19389 }
19390
19391 MachineBasicBlock *
19392 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19393                                                  MachineBasicBlock *MBB) const {
19394   // Emit va_arg instruction on X86-64.
19395
19396   // Operands to this pseudo-instruction:
19397   // 0  ) Output        : destination address (reg)
19398   // 1-5) Input         : va_list address (addr, i64mem)
19399   // 6  ) ArgSize       : Size (in bytes) of vararg type
19400   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19401   // 8  ) Align         : Alignment of type
19402   // 9  ) EFLAGS (implicit-def)
19403
19404   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19405   static_assert(X86::AddrNumOperands == 5,
19406                 "VAARG_64 assumes 5 address operands");
19407
19408   unsigned DestReg = MI->getOperand(0).getReg();
19409   MachineOperand &Base = MI->getOperand(1);
19410   MachineOperand &Scale = MI->getOperand(2);
19411   MachineOperand &Index = MI->getOperand(3);
19412   MachineOperand &Disp = MI->getOperand(4);
19413   MachineOperand &Segment = MI->getOperand(5);
19414   unsigned ArgSize = MI->getOperand(6).getImm();
19415   unsigned ArgMode = MI->getOperand(7).getImm();
19416   unsigned Align = MI->getOperand(8).getImm();
19417
19418   // Memory Reference
19419   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19420   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19421   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19422
19423   // Machine Information
19424   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19425   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19426   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19427   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19428   DebugLoc DL = MI->getDebugLoc();
19429
19430   // struct va_list {
19431   //   i32   gp_offset
19432   //   i32   fp_offset
19433   //   i64   overflow_area (address)
19434   //   i64   reg_save_area (address)
19435   // }
19436   // sizeof(va_list) = 24
19437   // alignment(va_list) = 8
19438
19439   unsigned TotalNumIntRegs = 6;
19440   unsigned TotalNumXMMRegs = 8;
19441   bool UseGPOffset = (ArgMode == 1);
19442   bool UseFPOffset = (ArgMode == 2);
19443   unsigned MaxOffset = TotalNumIntRegs * 8 +
19444                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19445
19446   /* Align ArgSize to a multiple of 8 */
19447   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19448   bool NeedsAlign = (Align > 8);
19449
19450   MachineBasicBlock *thisMBB = MBB;
19451   MachineBasicBlock *overflowMBB;
19452   MachineBasicBlock *offsetMBB;
19453   MachineBasicBlock *endMBB;
19454
19455   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19456   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19457   unsigned OffsetReg = 0;
19458
19459   if (!UseGPOffset && !UseFPOffset) {
19460     // If we only pull from the overflow region, we don't create a branch.
19461     // We don't need to alter control flow.
19462     OffsetDestReg = 0; // unused
19463     OverflowDestReg = DestReg;
19464
19465     offsetMBB = nullptr;
19466     overflowMBB = thisMBB;
19467     endMBB = thisMBB;
19468   } else {
19469     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19470     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19471     // If not, pull from overflow_area. (branch to overflowMBB)
19472     //
19473     //       thisMBB
19474     //         |     .
19475     //         |        .
19476     //     offsetMBB   overflowMBB
19477     //         |        .
19478     //         |     .
19479     //        endMBB
19480
19481     // Registers for the PHI in endMBB
19482     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19483     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19484
19485     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19486     MachineFunction *MF = MBB->getParent();
19487     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19488     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19489     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19490
19491     MachineFunction::iterator MBBIter = MBB;
19492     ++MBBIter;
19493
19494     // Insert the new basic blocks
19495     MF->insert(MBBIter, offsetMBB);
19496     MF->insert(MBBIter, overflowMBB);
19497     MF->insert(MBBIter, endMBB);
19498
19499     // Transfer the remainder of MBB and its successor edges to endMBB.
19500     endMBB->splice(endMBB->begin(), thisMBB,
19501                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19502     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19503
19504     // Make offsetMBB and overflowMBB successors of thisMBB
19505     thisMBB->addSuccessor(offsetMBB);
19506     thisMBB->addSuccessor(overflowMBB);
19507
19508     // endMBB is a successor of both offsetMBB and overflowMBB
19509     offsetMBB->addSuccessor(endMBB);
19510     overflowMBB->addSuccessor(endMBB);
19511
19512     // Load the offset value into a register
19513     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19514     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19515       .addOperand(Base)
19516       .addOperand(Scale)
19517       .addOperand(Index)
19518       .addDisp(Disp, UseFPOffset ? 4 : 0)
19519       .addOperand(Segment)
19520       .setMemRefs(MMOBegin, MMOEnd);
19521
19522     // Check if there is enough room left to pull this argument.
19523     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19524       .addReg(OffsetReg)
19525       .addImm(MaxOffset + 8 - ArgSizeA8);
19526
19527     // Branch to "overflowMBB" if offset >= max
19528     // Fall through to "offsetMBB" otherwise
19529     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19530       .addMBB(overflowMBB);
19531   }
19532
19533   // In offsetMBB, emit code to use the reg_save_area.
19534   if (offsetMBB) {
19535     assert(OffsetReg != 0);
19536
19537     // Read the reg_save_area address.
19538     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19539     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19540       .addOperand(Base)
19541       .addOperand(Scale)
19542       .addOperand(Index)
19543       .addDisp(Disp, 16)
19544       .addOperand(Segment)
19545       .setMemRefs(MMOBegin, MMOEnd);
19546
19547     // Zero-extend the offset
19548     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19549       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19550         .addImm(0)
19551         .addReg(OffsetReg)
19552         .addImm(X86::sub_32bit);
19553
19554     // Add the offset to the reg_save_area to get the final address.
19555     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19556       .addReg(OffsetReg64)
19557       .addReg(RegSaveReg);
19558
19559     // Compute the offset for the next argument
19560     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19561     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19562       .addReg(OffsetReg)
19563       .addImm(UseFPOffset ? 16 : 8);
19564
19565     // Store it back into the va_list.
19566     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19567       .addOperand(Base)
19568       .addOperand(Scale)
19569       .addOperand(Index)
19570       .addDisp(Disp, UseFPOffset ? 4 : 0)
19571       .addOperand(Segment)
19572       .addReg(NextOffsetReg)
19573       .setMemRefs(MMOBegin, MMOEnd);
19574
19575     // Jump to endMBB
19576     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19577       .addMBB(endMBB);
19578   }
19579
19580   //
19581   // Emit code to use overflow area
19582   //
19583
19584   // Load the overflow_area address into a register.
19585   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19586   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19587     .addOperand(Base)
19588     .addOperand(Scale)
19589     .addOperand(Index)
19590     .addDisp(Disp, 8)
19591     .addOperand(Segment)
19592     .setMemRefs(MMOBegin, MMOEnd);
19593
19594   // If we need to align it, do so. Otherwise, just copy the address
19595   // to OverflowDestReg.
19596   if (NeedsAlign) {
19597     // Align the overflow address
19598     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19599     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19600
19601     // aligned_addr = (addr + (align-1)) & ~(align-1)
19602     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19603       .addReg(OverflowAddrReg)
19604       .addImm(Align-1);
19605
19606     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19607       .addReg(TmpReg)
19608       .addImm(~(uint64_t)(Align-1));
19609   } else {
19610     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19611       .addReg(OverflowAddrReg);
19612   }
19613
19614   // Compute the next overflow address after this argument.
19615   // (the overflow address should be kept 8-byte aligned)
19616   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19617   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19618     .addReg(OverflowDestReg)
19619     .addImm(ArgSizeA8);
19620
19621   // Store the new overflow address.
19622   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19623     .addOperand(Base)
19624     .addOperand(Scale)
19625     .addOperand(Index)
19626     .addDisp(Disp, 8)
19627     .addOperand(Segment)
19628     .addReg(NextAddrReg)
19629     .setMemRefs(MMOBegin, MMOEnd);
19630
19631   // If we branched, emit the PHI to the front of endMBB.
19632   if (offsetMBB) {
19633     BuildMI(*endMBB, endMBB->begin(), DL,
19634             TII->get(X86::PHI), DestReg)
19635       .addReg(OffsetDestReg).addMBB(offsetMBB)
19636       .addReg(OverflowDestReg).addMBB(overflowMBB);
19637   }
19638
19639   // Erase the pseudo instruction
19640   MI->eraseFromParent();
19641
19642   return endMBB;
19643 }
19644
19645 MachineBasicBlock *
19646 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19647                                                  MachineInstr *MI,
19648                                                  MachineBasicBlock *MBB) const {
19649   // Emit code to save XMM registers to the stack. The ABI says that the
19650   // number of registers to save is given in %al, so it's theoretically
19651   // possible to do an indirect jump trick to avoid saving all of them,
19652   // however this code takes a simpler approach and just executes all
19653   // of the stores if %al is non-zero. It's less code, and it's probably
19654   // easier on the hardware branch predictor, and stores aren't all that
19655   // expensive anyway.
19656
19657   // Create the new basic blocks. One block contains all the XMM stores,
19658   // and one block is the final destination regardless of whether any
19659   // stores were performed.
19660   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19661   MachineFunction *F = MBB->getParent();
19662   MachineFunction::iterator MBBIter = MBB;
19663   ++MBBIter;
19664   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19665   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19666   F->insert(MBBIter, XMMSaveMBB);
19667   F->insert(MBBIter, EndMBB);
19668
19669   // Transfer the remainder of MBB and its successor edges to EndMBB.
19670   EndMBB->splice(EndMBB->begin(), MBB,
19671                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19672   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19673
19674   // The original block will now fall through to the XMM save block.
19675   MBB->addSuccessor(XMMSaveMBB);
19676   // The XMMSaveMBB will fall through to the end block.
19677   XMMSaveMBB->addSuccessor(EndMBB);
19678
19679   // Now add the instructions.
19680   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19681   DebugLoc DL = MI->getDebugLoc();
19682
19683   unsigned CountReg = MI->getOperand(0).getReg();
19684   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19685   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19686
19687   if (!Subtarget->isTargetWin64()) {
19688     // If %al is 0, branch around the XMM save block.
19689     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19690     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19691     MBB->addSuccessor(EndMBB);
19692   }
19693
19694   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19695   // that was just emitted, but clearly shouldn't be "saved".
19696   assert((MI->getNumOperands() <= 3 ||
19697           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19698           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19699          && "Expected last argument to be EFLAGS");
19700   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19701   // In the XMM save block, save all the XMM argument registers.
19702   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19703     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19704     MachineMemOperand *MMO =
19705       F->getMachineMemOperand(
19706           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19707         MachineMemOperand::MOStore,
19708         /*Size=*/16, /*Align=*/16);
19709     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19710       .addFrameIndex(RegSaveFrameIndex)
19711       .addImm(/*Scale=*/1)
19712       .addReg(/*IndexReg=*/0)
19713       .addImm(/*Disp=*/Offset)
19714       .addReg(/*Segment=*/0)
19715       .addReg(MI->getOperand(i).getReg())
19716       .addMemOperand(MMO);
19717   }
19718
19719   MI->eraseFromParent();   // The pseudo instruction is gone now.
19720
19721   return EndMBB;
19722 }
19723
19724 // The EFLAGS operand of SelectItr might be missing a kill marker
19725 // because there were multiple uses of EFLAGS, and ISel didn't know
19726 // which to mark. Figure out whether SelectItr should have had a
19727 // kill marker, and set it if it should. Returns the correct kill
19728 // marker value.
19729 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19730                                      MachineBasicBlock* BB,
19731                                      const TargetRegisterInfo* TRI) {
19732   // Scan forward through BB for a use/def of EFLAGS.
19733   MachineBasicBlock::iterator miI(std::next(SelectItr));
19734   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19735     const MachineInstr& mi = *miI;
19736     if (mi.readsRegister(X86::EFLAGS))
19737       return false;
19738     if (mi.definesRegister(X86::EFLAGS))
19739       break; // Should have kill-flag - update below.
19740   }
19741
19742   // If we hit the end of the block, check whether EFLAGS is live into a
19743   // successor.
19744   if (miI == BB->end()) {
19745     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19746                                           sEnd = BB->succ_end();
19747          sItr != sEnd; ++sItr) {
19748       MachineBasicBlock* succ = *sItr;
19749       if (succ->isLiveIn(X86::EFLAGS))
19750         return false;
19751     }
19752   }
19753
19754   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19755   // out. SelectMI should have a kill flag on EFLAGS.
19756   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19757   return true;
19758 }
19759
19760 MachineBasicBlock *
19761 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19762                                      MachineBasicBlock *BB) const {
19763   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19764   DebugLoc DL = MI->getDebugLoc();
19765
19766   // To "insert" a SELECT_CC instruction, we actually have to insert the
19767   // diamond control-flow pattern.  The incoming instruction knows the
19768   // destination vreg to set, the condition code register to branch on, the
19769   // true/false values to select between, and a branch opcode to use.
19770   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19771   MachineFunction::iterator It = BB;
19772   ++It;
19773
19774   //  thisMBB:
19775   //  ...
19776   //   TrueVal = ...
19777   //   cmpTY ccX, r1, r2
19778   //   bCC copy1MBB
19779   //   fallthrough --> copy0MBB
19780   MachineBasicBlock *thisMBB = BB;
19781   MachineFunction *F = BB->getParent();
19782
19783   // We also lower double CMOVs:
19784   //   (CMOV (CMOV F, T, cc1), T, cc2)
19785   // to two successives branches.  For that, we look for another CMOV as the
19786   // following instruction.
19787   //
19788   // Without this, we would add a PHI between the two jumps, which ends up
19789   // creating a few copies all around. For instance, for
19790   //
19791   //    (sitofp (zext (fcmp une)))
19792   //
19793   // we would generate:
19794   //
19795   //         ucomiss %xmm1, %xmm0
19796   //         movss  <1.0f>, %xmm0
19797   //         movaps  %xmm0, %xmm1
19798   //         jne     .LBB5_2
19799   //         xorps   %xmm1, %xmm1
19800   // .LBB5_2:
19801   //         jp      .LBB5_4
19802   //         movaps  %xmm1, %xmm0
19803   // .LBB5_4:
19804   //         retq
19805   //
19806   // because this custom-inserter would have generated:
19807   //
19808   //   A
19809   //   | \
19810   //   |  B
19811   //   | /
19812   //   C
19813   //   | \
19814   //   |  D
19815   //   | /
19816   //   E
19817   //
19818   // A: X = ...; Y = ...
19819   // B: empty
19820   // C: Z = PHI [X, A], [Y, B]
19821   // D: empty
19822   // E: PHI [X, C], [Z, D]
19823   //
19824   // If we lower both CMOVs in a single step, we can instead generate:
19825   //
19826   //   A
19827   //   | \
19828   //   |  C
19829   //   | /|
19830   //   |/ |
19831   //   |  |
19832   //   |  D
19833   //   | /
19834   //   E
19835   //
19836   // A: X = ...; Y = ...
19837   // D: empty
19838   // E: PHI [X, A], [X, C], [Y, D]
19839   //
19840   // Which, in our sitofp/fcmp example, gives us something like:
19841   //
19842   //         ucomiss %xmm1, %xmm0
19843   //         movss  <1.0f>, %xmm0
19844   //         jne     .LBB5_4
19845   //         jp      .LBB5_4
19846   //         xorps   %xmm0, %xmm0
19847   // .LBB5_4:
19848   //         retq
19849   //
19850   MachineInstr *NextCMOV = nullptr;
19851   MachineBasicBlock::iterator NextMIIt =
19852       std::next(MachineBasicBlock::iterator(MI));
19853   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19854       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19855       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19856     NextCMOV = &*NextMIIt;
19857
19858   MachineBasicBlock *jcc1MBB = nullptr;
19859
19860   // If we have a double CMOV, we lower it to two successive branches to
19861   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19862   if (NextCMOV) {
19863     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19864     F->insert(It, jcc1MBB);
19865     jcc1MBB->addLiveIn(X86::EFLAGS);
19866   }
19867
19868   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19869   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19870   F->insert(It, copy0MBB);
19871   F->insert(It, sinkMBB);
19872
19873   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19874   // live into the sink and copy blocks.
19875   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19876
19877   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19878   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19879       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19880     copy0MBB->addLiveIn(X86::EFLAGS);
19881     sinkMBB->addLiveIn(X86::EFLAGS);
19882   }
19883
19884   // Transfer the remainder of BB and its successor edges to sinkMBB.
19885   sinkMBB->splice(sinkMBB->begin(), BB,
19886                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19887   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19888
19889   // Add the true and fallthrough blocks as its successors.
19890   if (NextCMOV) {
19891     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19892     BB->addSuccessor(jcc1MBB);
19893
19894     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19895     // jump to the sinkMBB.
19896     jcc1MBB->addSuccessor(copy0MBB);
19897     jcc1MBB->addSuccessor(sinkMBB);
19898   } else {
19899     BB->addSuccessor(copy0MBB);
19900   }
19901
19902   // The true block target of the first (or only) branch is always sinkMBB.
19903   BB->addSuccessor(sinkMBB);
19904
19905   // Create the conditional branch instruction.
19906   unsigned Opc =
19907     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19908   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19909
19910   if (NextCMOV) {
19911     unsigned Opc2 = X86::GetCondBranchFromCond(
19912         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19913     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19914   }
19915
19916   //  copy0MBB:
19917   //   %FalseValue = ...
19918   //   # fallthrough to sinkMBB
19919   copy0MBB->addSuccessor(sinkMBB);
19920
19921   //  sinkMBB:
19922   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19923   //  ...
19924   MachineInstrBuilder MIB =
19925       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19926               MI->getOperand(0).getReg())
19927           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19928           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19929
19930   // If we have a double CMOV, the second Jcc provides the same incoming
19931   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19932   if (NextCMOV) {
19933     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19934     // Copy the PHI result to the register defined by the second CMOV.
19935     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19936             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19937         .addReg(MI->getOperand(0).getReg());
19938     NextCMOV->eraseFromParent();
19939   }
19940
19941   MI->eraseFromParent();   // The pseudo instruction is gone now.
19942   return sinkMBB;
19943 }
19944
19945 MachineBasicBlock *
19946 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19947                                         MachineBasicBlock *BB) const {
19948   MachineFunction *MF = BB->getParent();
19949   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19950   DebugLoc DL = MI->getDebugLoc();
19951   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19952
19953   assert(MF->shouldSplitStack());
19954
19955   const bool Is64Bit = Subtarget->is64Bit();
19956   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19957
19958   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19959   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19960
19961   // BB:
19962   //  ... [Till the alloca]
19963   // If stacklet is not large enough, jump to mallocMBB
19964   //
19965   // bumpMBB:
19966   //  Allocate by subtracting from RSP
19967   //  Jump to continueMBB
19968   //
19969   // mallocMBB:
19970   //  Allocate by call to runtime
19971   //
19972   // continueMBB:
19973   //  ...
19974   //  [rest of original BB]
19975   //
19976
19977   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19978   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19979   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19980
19981   MachineRegisterInfo &MRI = MF->getRegInfo();
19982   const TargetRegisterClass *AddrRegClass =
19983       getRegClassFor(getPointerTy(MF->getDataLayout()));
19984
19985   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19986     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19987     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19988     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19989     sizeVReg = MI->getOperand(1).getReg(),
19990     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19991
19992   MachineFunction::iterator MBBIter = BB;
19993   ++MBBIter;
19994
19995   MF->insert(MBBIter, bumpMBB);
19996   MF->insert(MBBIter, mallocMBB);
19997   MF->insert(MBBIter, continueMBB);
19998
19999   continueMBB->splice(continueMBB->begin(), BB,
20000                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
20001   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
20002
20003   // Add code to the main basic block to check if the stack limit has been hit,
20004   // and if so, jump to mallocMBB otherwise to bumpMBB.
20005   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
20006   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
20007     .addReg(tmpSPVReg).addReg(sizeVReg);
20008   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
20009     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
20010     .addReg(SPLimitVReg);
20011   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
20012
20013   // bumpMBB simply decreases the stack pointer, since we know the current
20014   // stacklet has enough space.
20015   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
20016     .addReg(SPLimitVReg);
20017   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
20018     .addReg(SPLimitVReg);
20019   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20020
20021   // Calls into a routine in libgcc to allocate more space from the heap.
20022   const uint32_t *RegMask =
20023       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
20024   if (IsLP64) {
20025     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
20026       .addReg(sizeVReg);
20027     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20028       .addExternalSymbol("__morestack_allocate_stack_space")
20029       .addRegMask(RegMask)
20030       .addReg(X86::RDI, RegState::Implicit)
20031       .addReg(X86::RAX, RegState::ImplicitDefine);
20032   } else if (Is64Bit) {
20033     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
20034       .addReg(sizeVReg);
20035     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
20036       .addExternalSymbol("__morestack_allocate_stack_space")
20037       .addRegMask(RegMask)
20038       .addReg(X86::EDI, RegState::Implicit)
20039       .addReg(X86::EAX, RegState::ImplicitDefine);
20040   } else {
20041     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
20042       .addImm(12);
20043     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
20044     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
20045       .addExternalSymbol("__morestack_allocate_stack_space")
20046       .addRegMask(RegMask)
20047       .addReg(X86::EAX, RegState::ImplicitDefine);
20048   }
20049
20050   if (!Is64Bit)
20051     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
20052       .addImm(16);
20053
20054   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
20055     .addReg(IsLP64 ? X86::RAX : X86::EAX);
20056   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
20057
20058   // Set up the CFG correctly.
20059   BB->addSuccessor(bumpMBB);
20060   BB->addSuccessor(mallocMBB);
20061   mallocMBB->addSuccessor(continueMBB);
20062   bumpMBB->addSuccessor(continueMBB);
20063
20064   // Take care of the PHI nodes.
20065   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
20066           MI->getOperand(0).getReg())
20067     .addReg(mallocPtrVReg).addMBB(mallocMBB)
20068     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
20069
20070   // Delete the original pseudo instruction.
20071   MI->eraseFromParent();
20072
20073   // And we're done.
20074   return continueMBB;
20075 }
20076
20077 MachineBasicBlock *
20078 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
20079                                         MachineBasicBlock *BB) const {
20080   DebugLoc DL = MI->getDebugLoc();
20081
20082   assert(!Subtarget->isTargetMachO());
20083
20084   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
20085                                                     DL);
20086
20087   MI->eraseFromParent();   // The pseudo instruction is gone now.
20088   return BB;
20089 }
20090
20091 MachineBasicBlock *
20092 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
20093                                       MachineBasicBlock *BB) const {
20094   // This is pretty easy.  We're taking the value that we received from
20095   // our load from the relocation, sticking it in either RDI (x86-64)
20096   // or EAX and doing an indirect call.  The return value will then
20097   // be in the normal return register.
20098   MachineFunction *F = BB->getParent();
20099   const X86InstrInfo *TII = Subtarget->getInstrInfo();
20100   DebugLoc DL = MI->getDebugLoc();
20101
20102   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
20103   assert(MI->getOperand(3).isGlobal() && "This should be a global");
20104
20105   // Get a register mask for the lowered call.
20106   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
20107   // proper register mask.
20108   const uint32_t *RegMask =
20109       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
20110   if (Subtarget->is64Bit()) {
20111     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20112                                       TII->get(X86::MOV64rm), X86::RDI)
20113     .addReg(X86::RIP)
20114     .addImm(0).addReg(0)
20115     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20116                       MI->getOperand(3).getTargetFlags())
20117     .addReg(0);
20118     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
20119     addDirectMem(MIB, X86::RDI);
20120     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
20121   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
20122     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20123                                       TII->get(X86::MOV32rm), X86::EAX)
20124     .addReg(0)
20125     .addImm(0).addReg(0)
20126     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20127                       MI->getOperand(3).getTargetFlags())
20128     .addReg(0);
20129     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20130     addDirectMem(MIB, X86::EAX);
20131     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20132   } else {
20133     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
20134                                       TII->get(X86::MOV32rm), X86::EAX)
20135     .addReg(TII->getGlobalBaseReg(F))
20136     .addImm(0).addReg(0)
20137     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
20138                       MI->getOperand(3).getTargetFlags())
20139     .addReg(0);
20140     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
20141     addDirectMem(MIB, X86::EAX);
20142     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
20143   }
20144
20145   MI->eraseFromParent(); // The pseudo instruction is gone now.
20146   return BB;
20147 }
20148
20149 MachineBasicBlock *
20150 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
20151                                     MachineBasicBlock *MBB) const {
20152   DebugLoc DL = MI->getDebugLoc();
20153   MachineFunction *MF = MBB->getParent();
20154   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20155   MachineRegisterInfo &MRI = MF->getRegInfo();
20156
20157   const BasicBlock *BB = MBB->getBasicBlock();
20158   MachineFunction::iterator I = MBB;
20159   ++I;
20160
20161   // Memory Reference
20162   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20163   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20164
20165   unsigned DstReg;
20166   unsigned MemOpndSlot = 0;
20167
20168   unsigned CurOp = 0;
20169
20170   DstReg = MI->getOperand(CurOp++).getReg();
20171   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
20172   assert(RC->hasType(MVT::i32) && "Invalid destination!");
20173   unsigned mainDstReg = MRI.createVirtualRegister(RC);
20174   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
20175
20176   MemOpndSlot = CurOp;
20177
20178   MVT PVT = getPointerTy(MF->getDataLayout());
20179   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20180          "Invalid Pointer Size!");
20181
20182   // For v = setjmp(buf), we generate
20183   //
20184   // thisMBB:
20185   //  buf[LabelOffset] = restoreMBB
20186   //  SjLjSetup restoreMBB
20187   //
20188   // mainMBB:
20189   //  v_main = 0
20190   //
20191   // sinkMBB:
20192   //  v = phi(main, restore)
20193   //
20194   // restoreMBB:
20195   //  if base pointer being used, load it from frame
20196   //  v_restore = 1
20197
20198   MachineBasicBlock *thisMBB = MBB;
20199   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
20200   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
20201   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
20202   MF->insert(I, mainMBB);
20203   MF->insert(I, sinkMBB);
20204   MF->push_back(restoreMBB);
20205
20206   MachineInstrBuilder MIB;
20207
20208   // Transfer the remainder of BB and its successor edges to sinkMBB.
20209   sinkMBB->splice(sinkMBB->begin(), MBB,
20210                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
20211   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
20212
20213   // thisMBB:
20214   unsigned PtrStoreOpc = 0;
20215   unsigned LabelReg = 0;
20216   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20217   Reloc::Model RM = MF->getTarget().getRelocationModel();
20218   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
20219                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
20220
20221   // Prepare IP either in reg or imm.
20222   if (!UseImmLabel) {
20223     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
20224     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
20225     LabelReg = MRI.createVirtualRegister(PtrRC);
20226     if (Subtarget->is64Bit()) {
20227       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
20228               .addReg(X86::RIP)
20229               .addImm(0)
20230               .addReg(0)
20231               .addMBB(restoreMBB)
20232               .addReg(0);
20233     } else {
20234       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
20235       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
20236               .addReg(XII->getGlobalBaseReg(MF))
20237               .addImm(0)
20238               .addReg(0)
20239               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
20240               .addReg(0);
20241     }
20242   } else
20243     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
20244   // Store IP
20245   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
20246   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20247     if (i == X86::AddrDisp)
20248       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
20249     else
20250       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
20251   }
20252   if (!UseImmLabel)
20253     MIB.addReg(LabelReg);
20254   else
20255     MIB.addMBB(restoreMBB);
20256   MIB.setMemRefs(MMOBegin, MMOEnd);
20257   // Setup
20258   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
20259           .addMBB(restoreMBB);
20260
20261   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20262   MIB.addRegMask(RegInfo->getNoPreservedMask());
20263   thisMBB->addSuccessor(mainMBB);
20264   thisMBB->addSuccessor(restoreMBB);
20265
20266   // mainMBB:
20267   //  EAX = 0
20268   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
20269   mainMBB->addSuccessor(sinkMBB);
20270
20271   // sinkMBB:
20272   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
20273           TII->get(X86::PHI), DstReg)
20274     .addReg(mainDstReg).addMBB(mainMBB)
20275     .addReg(restoreDstReg).addMBB(restoreMBB);
20276
20277   // restoreMBB:
20278   if (RegInfo->hasBasePointer(*MF)) {
20279     const bool Uses64BitFramePtr =
20280         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
20281     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
20282     X86FI->setRestoreBasePointer(MF);
20283     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
20284     unsigned BasePtr = RegInfo->getBaseRegister();
20285     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
20286     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
20287                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
20288       .setMIFlag(MachineInstr::FrameSetup);
20289   }
20290   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
20291   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
20292   restoreMBB->addSuccessor(sinkMBB);
20293
20294   MI->eraseFromParent();
20295   return sinkMBB;
20296 }
20297
20298 MachineBasicBlock *
20299 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
20300                                      MachineBasicBlock *MBB) const {
20301   DebugLoc DL = MI->getDebugLoc();
20302   MachineFunction *MF = MBB->getParent();
20303   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20304   MachineRegisterInfo &MRI = MF->getRegInfo();
20305
20306   // Memory Reference
20307   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
20308   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
20309
20310   MVT PVT = getPointerTy(MF->getDataLayout());
20311   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
20312          "Invalid Pointer Size!");
20313
20314   const TargetRegisterClass *RC =
20315     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
20316   unsigned Tmp = MRI.createVirtualRegister(RC);
20317   // Since FP is only updated here but NOT referenced, it's treated as GPR.
20318   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
20319   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
20320   unsigned SP = RegInfo->getStackRegister();
20321
20322   MachineInstrBuilder MIB;
20323
20324   const int64_t LabelOffset = 1 * PVT.getStoreSize();
20325   const int64_t SPOffset = 2 * PVT.getStoreSize();
20326
20327   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
20328   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
20329
20330   // Reload FP
20331   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
20332   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
20333     MIB.addOperand(MI->getOperand(i));
20334   MIB.setMemRefs(MMOBegin, MMOEnd);
20335   // Reload IP
20336   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
20337   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20338     if (i == X86::AddrDisp)
20339       MIB.addDisp(MI->getOperand(i), LabelOffset);
20340     else
20341       MIB.addOperand(MI->getOperand(i));
20342   }
20343   MIB.setMemRefs(MMOBegin, MMOEnd);
20344   // Reload SP
20345   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
20346   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
20347     if (i == X86::AddrDisp)
20348       MIB.addDisp(MI->getOperand(i), SPOffset);
20349     else
20350       MIB.addOperand(MI->getOperand(i));
20351   }
20352   MIB.setMemRefs(MMOBegin, MMOEnd);
20353   // Jump
20354   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
20355
20356   MI->eraseFromParent();
20357   return MBB;
20358 }
20359
20360 // Replace 213-type (isel default) FMA3 instructions with 231-type for
20361 // accumulator loops. Writing back to the accumulator allows the coalescer
20362 // to remove extra copies in the loop.
20363 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
20364 MachineBasicBlock *
20365 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
20366                                  MachineBasicBlock *MBB) const {
20367   MachineOperand &AddendOp = MI->getOperand(3);
20368
20369   // Bail out early if the addend isn't a register - we can't switch these.
20370   if (!AddendOp.isReg())
20371     return MBB;
20372
20373   MachineFunction &MF = *MBB->getParent();
20374   MachineRegisterInfo &MRI = MF.getRegInfo();
20375
20376   // Check whether the addend is defined by a PHI:
20377   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20378   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20379   if (!AddendDef.isPHI())
20380     return MBB;
20381
20382   // Look for the following pattern:
20383   // loop:
20384   //   %addend = phi [%entry, 0], [%loop, %result]
20385   //   ...
20386   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20387
20388   // Replace with:
20389   //   loop:
20390   //   %addend = phi [%entry, 0], [%loop, %result]
20391   //   ...
20392   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20393
20394   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20395     assert(AddendDef.getOperand(i).isReg());
20396     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20397     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20398     if (&PHISrcInst == MI) {
20399       // Found a matching instruction.
20400       unsigned NewFMAOpc = 0;
20401       switch (MI->getOpcode()) {
20402         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20403         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20404         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20405         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20406         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20407         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20408         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20409         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20410         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20411         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20412         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20413         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20414         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20415         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20416         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20417         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20418         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20419         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20420         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20421         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20422
20423         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20424         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20425         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20426         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20427         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20428         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20429         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20430         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20431         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20432         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20433         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20434         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20435         default: llvm_unreachable("Unrecognized FMA variant.");
20436       }
20437
20438       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20439       MachineInstrBuilder MIB =
20440         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20441         .addOperand(MI->getOperand(0))
20442         .addOperand(MI->getOperand(3))
20443         .addOperand(MI->getOperand(2))
20444         .addOperand(MI->getOperand(1));
20445       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20446       MI->eraseFromParent();
20447     }
20448   }
20449
20450   return MBB;
20451 }
20452
20453 MachineBasicBlock *
20454 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20455                                                MachineBasicBlock *BB) const {
20456   switch (MI->getOpcode()) {
20457   default: llvm_unreachable("Unexpected instr type to insert");
20458   case X86::TAILJMPd64:
20459   case X86::TAILJMPr64:
20460   case X86::TAILJMPm64:
20461   case X86::TAILJMPd64_REX:
20462   case X86::TAILJMPr64_REX:
20463   case X86::TAILJMPm64_REX:
20464     llvm_unreachable("TAILJMP64 would not be touched here.");
20465   case X86::TCRETURNdi64:
20466   case X86::TCRETURNri64:
20467   case X86::TCRETURNmi64:
20468     return BB;
20469   case X86::WIN_ALLOCA:
20470     return EmitLoweredWinAlloca(MI, BB);
20471   case X86::SEG_ALLOCA_32:
20472   case X86::SEG_ALLOCA_64:
20473     return EmitLoweredSegAlloca(MI, BB);
20474   case X86::TLSCall_32:
20475   case X86::TLSCall_64:
20476     return EmitLoweredTLSCall(MI, BB);
20477   case X86::CMOV_GR8:
20478   case X86::CMOV_FR32:
20479   case X86::CMOV_FR64:
20480   case X86::CMOV_V4F32:
20481   case X86::CMOV_V2F64:
20482   case X86::CMOV_V2I64:
20483   case X86::CMOV_V8F32:
20484   case X86::CMOV_V4F64:
20485   case X86::CMOV_V4I64:
20486   case X86::CMOV_V16F32:
20487   case X86::CMOV_V8F64:
20488   case X86::CMOV_V8I64:
20489   case X86::CMOV_GR16:
20490   case X86::CMOV_GR32:
20491   case X86::CMOV_RFP32:
20492   case X86::CMOV_RFP64:
20493   case X86::CMOV_RFP80:
20494   case X86::CMOV_V8I1:
20495   case X86::CMOV_V16I1:
20496   case X86::CMOV_V32I1:
20497   case X86::CMOV_V64I1:
20498     return EmitLoweredSelect(MI, BB);
20499
20500   case X86::FP32_TO_INT16_IN_MEM:
20501   case X86::FP32_TO_INT32_IN_MEM:
20502   case X86::FP32_TO_INT64_IN_MEM:
20503   case X86::FP64_TO_INT16_IN_MEM:
20504   case X86::FP64_TO_INT32_IN_MEM:
20505   case X86::FP64_TO_INT64_IN_MEM:
20506   case X86::FP80_TO_INT16_IN_MEM:
20507   case X86::FP80_TO_INT32_IN_MEM:
20508   case X86::FP80_TO_INT64_IN_MEM: {
20509     MachineFunction *F = BB->getParent();
20510     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20511     DebugLoc DL = MI->getDebugLoc();
20512
20513     // Change the floating point control register to use "round towards zero"
20514     // mode when truncating to an integer value.
20515     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20516     addFrameReference(BuildMI(*BB, MI, DL,
20517                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20518
20519     // Load the old value of the high byte of the control word...
20520     unsigned OldCW =
20521       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20522     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20523                       CWFrameIdx);
20524
20525     // Set the high part to be round to zero...
20526     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20527       .addImm(0xC7F);
20528
20529     // Reload the modified control word now...
20530     addFrameReference(BuildMI(*BB, MI, DL,
20531                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20532
20533     // Restore the memory image of control word to original value
20534     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20535       .addReg(OldCW);
20536
20537     // Get the X86 opcode to use.
20538     unsigned Opc;
20539     switch (MI->getOpcode()) {
20540     default: llvm_unreachable("illegal opcode!");
20541     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20542     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20543     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20544     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20545     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20546     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20547     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20548     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20549     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20550     }
20551
20552     X86AddressMode AM;
20553     MachineOperand &Op = MI->getOperand(0);
20554     if (Op.isReg()) {
20555       AM.BaseType = X86AddressMode::RegBase;
20556       AM.Base.Reg = Op.getReg();
20557     } else {
20558       AM.BaseType = X86AddressMode::FrameIndexBase;
20559       AM.Base.FrameIndex = Op.getIndex();
20560     }
20561     Op = MI->getOperand(1);
20562     if (Op.isImm())
20563       AM.Scale = Op.getImm();
20564     Op = MI->getOperand(2);
20565     if (Op.isImm())
20566       AM.IndexReg = Op.getImm();
20567     Op = MI->getOperand(3);
20568     if (Op.isGlobal()) {
20569       AM.GV = Op.getGlobal();
20570     } else {
20571       AM.Disp = Op.getImm();
20572     }
20573     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20574                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20575
20576     // Reload the original control word now.
20577     addFrameReference(BuildMI(*BB, MI, DL,
20578                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20579
20580     MI->eraseFromParent();   // The pseudo instruction is gone now.
20581     return BB;
20582   }
20583     // String/text processing lowering.
20584   case X86::PCMPISTRM128REG:
20585   case X86::VPCMPISTRM128REG:
20586   case X86::PCMPISTRM128MEM:
20587   case X86::VPCMPISTRM128MEM:
20588   case X86::PCMPESTRM128REG:
20589   case X86::VPCMPESTRM128REG:
20590   case X86::PCMPESTRM128MEM:
20591   case X86::VPCMPESTRM128MEM:
20592     assert(Subtarget->hasSSE42() &&
20593            "Target must have SSE4.2 or AVX features enabled");
20594     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20595
20596   // String/text processing lowering.
20597   case X86::PCMPISTRIREG:
20598   case X86::VPCMPISTRIREG:
20599   case X86::PCMPISTRIMEM:
20600   case X86::VPCMPISTRIMEM:
20601   case X86::PCMPESTRIREG:
20602   case X86::VPCMPESTRIREG:
20603   case X86::PCMPESTRIMEM:
20604   case X86::VPCMPESTRIMEM:
20605     assert(Subtarget->hasSSE42() &&
20606            "Target must have SSE4.2 or AVX features enabled");
20607     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20608
20609   // Thread synchronization.
20610   case X86::MONITOR:
20611     return EmitMonitor(MI, BB, Subtarget);
20612
20613   // xbegin
20614   case X86::XBEGIN:
20615     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20616
20617   case X86::VASTART_SAVE_XMM_REGS:
20618     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20619
20620   case X86::VAARG_64:
20621     return EmitVAARG64WithCustomInserter(MI, BB);
20622
20623   case X86::EH_SjLj_SetJmp32:
20624   case X86::EH_SjLj_SetJmp64:
20625     return emitEHSjLjSetJmp(MI, BB);
20626
20627   case X86::EH_SjLj_LongJmp32:
20628   case X86::EH_SjLj_LongJmp64:
20629     return emitEHSjLjLongJmp(MI, BB);
20630
20631   case TargetOpcode::STATEPOINT:
20632     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20633     // this point in the process.  We diverge later.
20634     return emitPatchPoint(MI, BB);
20635
20636   case TargetOpcode::STACKMAP:
20637   case TargetOpcode::PATCHPOINT:
20638     return emitPatchPoint(MI, BB);
20639
20640   case X86::VFMADDPDr213r:
20641   case X86::VFMADDPSr213r:
20642   case X86::VFMADDSDr213r:
20643   case X86::VFMADDSSr213r:
20644   case X86::VFMSUBPDr213r:
20645   case X86::VFMSUBPSr213r:
20646   case X86::VFMSUBSDr213r:
20647   case X86::VFMSUBSSr213r:
20648   case X86::VFNMADDPDr213r:
20649   case X86::VFNMADDPSr213r:
20650   case X86::VFNMADDSDr213r:
20651   case X86::VFNMADDSSr213r:
20652   case X86::VFNMSUBPDr213r:
20653   case X86::VFNMSUBPSr213r:
20654   case X86::VFNMSUBSDr213r:
20655   case X86::VFNMSUBSSr213r:
20656   case X86::VFMADDSUBPDr213r:
20657   case X86::VFMADDSUBPSr213r:
20658   case X86::VFMSUBADDPDr213r:
20659   case X86::VFMSUBADDPSr213r:
20660   case X86::VFMADDPDr213rY:
20661   case X86::VFMADDPSr213rY:
20662   case X86::VFMSUBPDr213rY:
20663   case X86::VFMSUBPSr213rY:
20664   case X86::VFNMADDPDr213rY:
20665   case X86::VFNMADDPSr213rY:
20666   case X86::VFNMSUBPDr213rY:
20667   case X86::VFNMSUBPSr213rY:
20668   case X86::VFMADDSUBPDr213rY:
20669   case X86::VFMADDSUBPSr213rY:
20670   case X86::VFMSUBADDPDr213rY:
20671   case X86::VFMSUBADDPSr213rY:
20672     return emitFMA3Instr(MI, BB);
20673   }
20674 }
20675
20676 //===----------------------------------------------------------------------===//
20677 //                           X86 Optimization Hooks
20678 //===----------------------------------------------------------------------===//
20679
20680 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20681                                                       APInt &KnownZero,
20682                                                       APInt &KnownOne,
20683                                                       const SelectionDAG &DAG,
20684                                                       unsigned Depth) const {
20685   unsigned BitWidth = KnownZero.getBitWidth();
20686   unsigned Opc = Op.getOpcode();
20687   assert((Opc >= ISD::BUILTIN_OP_END ||
20688           Opc == ISD::INTRINSIC_WO_CHAIN ||
20689           Opc == ISD::INTRINSIC_W_CHAIN ||
20690           Opc == ISD::INTRINSIC_VOID) &&
20691          "Should use MaskedValueIsZero if you don't know whether Op"
20692          " is a target node!");
20693
20694   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20695   switch (Opc) {
20696   default: break;
20697   case X86ISD::ADD:
20698   case X86ISD::SUB:
20699   case X86ISD::ADC:
20700   case X86ISD::SBB:
20701   case X86ISD::SMUL:
20702   case X86ISD::UMUL:
20703   case X86ISD::INC:
20704   case X86ISD::DEC:
20705   case X86ISD::OR:
20706   case X86ISD::XOR:
20707   case X86ISD::AND:
20708     // These nodes' second result is a boolean.
20709     if (Op.getResNo() == 0)
20710       break;
20711     // Fallthrough
20712   case X86ISD::SETCC:
20713     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20714     break;
20715   case ISD::INTRINSIC_WO_CHAIN: {
20716     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20717     unsigned NumLoBits = 0;
20718     switch (IntId) {
20719     default: break;
20720     case Intrinsic::x86_sse_movmsk_ps:
20721     case Intrinsic::x86_avx_movmsk_ps_256:
20722     case Intrinsic::x86_sse2_movmsk_pd:
20723     case Intrinsic::x86_avx_movmsk_pd_256:
20724     case Intrinsic::x86_mmx_pmovmskb:
20725     case Intrinsic::x86_sse2_pmovmskb_128:
20726     case Intrinsic::x86_avx2_pmovmskb: {
20727       // High bits of movmskp{s|d}, pmovmskb are known zero.
20728       switch (IntId) {
20729         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20730         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20731         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20732         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20733         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20734         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20735         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20736         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20737       }
20738       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20739       break;
20740     }
20741     }
20742     break;
20743   }
20744   }
20745 }
20746
20747 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20748   SDValue Op,
20749   const SelectionDAG &,
20750   unsigned Depth) const {
20751   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20752   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20753     return Op.getValueType().getScalarType().getSizeInBits();
20754
20755   // Fallback case.
20756   return 1;
20757 }
20758
20759 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20760 /// node is a GlobalAddress + offset.
20761 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20762                                        const GlobalValue* &GA,
20763                                        int64_t &Offset) const {
20764   if (N->getOpcode() == X86ISD::Wrapper) {
20765     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20766       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20767       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20768       return true;
20769     }
20770   }
20771   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20772 }
20773
20774 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20775 /// same as extracting the high 128-bit part of 256-bit vector and then
20776 /// inserting the result into the low part of a new 256-bit vector
20777 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20778   EVT VT = SVOp->getValueType(0);
20779   unsigned NumElems = VT.getVectorNumElements();
20780
20781   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20782   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20783     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20784         SVOp->getMaskElt(j) >= 0)
20785       return false;
20786
20787   return true;
20788 }
20789
20790 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20791 /// same as extracting the low 128-bit part of 256-bit vector and then
20792 /// inserting the result into the high part of a new 256-bit vector
20793 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20794   EVT VT = SVOp->getValueType(0);
20795   unsigned NumElems = VT.getVectorNumElements();
20796
20797   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20798   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20799     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20800         SVOp->getMaskElt(j) >= 0)
20801       return false;
20802
20803   return true;
20804 }
20805
20806 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20807 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20808                                         TargetLowering::DAGCombinerInfo &DCI,
20809                                         const X86Subtarget* Subtarget) {
20810   SDLoc dl(N);
20811   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20812   SDValue V1 = SVOp->getOperand(0);
20813   SDValue V2 = SVOp->getOperand(1);
20814   EVT VT = SVOp->getValueType(0);
20815   unsigned NumElems = VT.getVectorNumElements();
20816
20817   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20818       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20819     //
20820     //                   0,0,0,...
20821     //                      |
20822     //    V      UNDEF    BUILD_VECTOR    UNDEF
20823     //     \      /           \           /
20824     //  CONCAT_VECTOR         CONCAT_VECTOR
20825     //         \                  /
20826     //          \                /
20827     //          RESULT: V + zero extended
20828     //
20829     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20830         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20831         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20832       return SDValue();
20833
20834     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20835       return SDValue();
20836
20837     // To match the shuffle mask, the first half of the mask should
20838     // be exactly the first vector, and all the rest a splat with the
20839     // first element of the second one.
20840     for (unsigned i = 0; i != NumElems/2; ++i)
20841       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20842           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20843         return SDValue();
20844
20845     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20846     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20847       if (Ld->hasNUsesOfValue(1, 0)) {
20848         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20849         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20850         SDValue ResNode =
20851           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20852                                   Ld->getMemoryVT(),
20853                                   Ld->getPointerInfo(),
20854                                   Ld->getAlignment(),
20855                                   false/*isVolatile*/, true/*ReadMem*/,
20856                                   false/*WriteMem*/);
20857
20858         // Make sure the newly-created LOAD is in the same position as Ld in
20859         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20860         // and update uses of Ld's output chain to use the TokenFactor.
20861         if (Ld->hasAnyUseOfValue(1)) {
20862           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20863                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20864           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20865           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20866                                  SDValue(ResNode.getNode(), 1));
20867         }
20868
20869         return DAG.getBitcast(VT, ResNode);
20870       }
20871     }
20872
20873     // Emit a zeroed vector and insert the desired subvector on its
20874     // first half.
20875     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20876     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20877     return DCI.CombineTo(N, InsV);
20878   }
20879
20880   //===--------------------------------------------------------------------===//
20881   // Combine some shuffles into subvector extracts and inserts:
20882   //
20883
20884   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20885   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20886     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20887     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20888     return DCI.CombineTo(N, InsV);
20889   }
20890
20891   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20892   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20893     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20894     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20895     return DCI.CombineTo(N, InsV);
20896   }
20897
20898   return SDValue();
20899 }
20900
20901 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20902 /// possible.
20903 ///
20904 /// This is the leaf of the recursive combinine below. When we have found some
20905 /// chain of single-use x86 shuffle instructions and accumulated the combined
20906 /// shuffle mask represented by them, this will try to pattern match that mask
20907 /// into either a single instruction if there is a special purpose instruction
20908 /// for this operation, or into a PSHUFB instruction which is a fully general
20909 /// instruction but should only be used to replace chains over a certain depth.
20910 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20911                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20912                                    TargetLowering::DAGCombinerInfo &DCI,
20913                                    const X86Subtarget *Subtarget) {
20914   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20915
20916   // Find the operand that enters the chain. Note that multiple uses are OK
20917   // here, we're not going to remove the operand we find.
20918   SDValue Input = Op.getOperand(0);
20919   while (Input.getOpcode() == ISD::BITCAST)
20920     Input = Input.getOperand(0);
20921
20922   MVT VT = Input.getSimpleValueType();
20923   MVT RootVT = Root.getSimpleValueType();
20924   SDLoc DL(Root);
20925
20926   // Just remove no-op shuffle masks.
20927   if (Mask.size() == 1) {
20928     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20929                   /*AddTo*/ true);
20930     return true;
20931   }
20932
20933   // Use the float domain if the operand type is a floating point type.
20934   bool FloatDomain = VT.isFloatingPoint();
20935
20936   // For floating point shuffles, we don't have free copies in the shuffle
20937   // instructions or the ability to load as part of the instruction, so
20938   // canonicalize their shuffles to UNPCK or MOV variants.
20939   //
20940   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20941   // vectors because it can have a load folded into it that UNPCK cannot. This
20942   // doesn't preclude something switching to the shorter encoding post-RA.
20943   //
20944   // FIXME: Should teach these routines about AVX vector widths.
20945   if (FloatDomain && VT.getSizeInBits() == 128) {
20946     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20947       bool Lo = Mask.equals({0, 0});
20948       unsigned Shuffle;
20949       MVT ShuffleVT;
20950       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20951       // is no slower than UNPCKLPD but has the option to fold the input operand
20952       // into even an unaligned memory load.
20953       if (Lo && Subtarget->hasSSE3()) {
20954         Shuffle = X86ISD::MOVDDUP;
20955         ShuffleVT = MVT::v2f64;
20956       } else {
20957         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20958         // than the UNPCK variants.
20959         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20960         ShuffleVT = MVT::v4f32;
20961       }
20962       if (Depth == 1 && Root->getOpcode() == Shuffle)
20963         return false; // Nothing to do!
20964       Op = DAG.getBitcast(ShuffleVT, Input);
20965       DCI.AddToWorklist(Op.getNode());
20966       if (Shuffle == X86ISD::MOVDDUP)
20967         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20968       else
20969         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20970       DCI.AddToWorklist(Op.getNode());
20971       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20972                     /*AddTo*/ true);
20973       return true;
20974     }
20975     if (Subtarget->hasSSE3() &&
20976         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20977       bool Lo = Mask.equals({0, 0, 2, 2});
20978       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20979       MVT ShuffleVT = MVT::v4f32;
20980       if (Depth == 1 && Root->getOpcode() == Shuffle)
20981         return false; // Nothing to do!
20982       Op = DAG.getBitcast(ShuffleVT, Input);
20983       DCI.AddToWorklist(Op.getNode());
20984       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20985       DCI.AddToWorklist(Op.getNode());
20986       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20987                     /*AddTo*/ true);
20988       return true;
20989     }
20990     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20991       bool Lo = Mask.equals({0, 0, 1, 1});
20992       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20993       MVT ShuffleVT = MVT::v4f32;
20994       if (Depth == 1 && Root->getOpcode() == Shuffle)
20995         return false; // Nothing to do!
20996       Op = DAG.getBitcast(ShuffleVT, Input);
20997       DCI.AddToWorklist(Op.getNode());
20998       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20999       DCI.AddToWorklist(Op.getNode());
21000       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21001                     /*AddTo*/ true);
21002       return true;
21003     }
21004   }
21005
21006   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
21007   // variants as none of these have single-instruction variants that are
21008   // superior to the UNPCK formulation.
21009   if (!FloatDomain && VT.getSizeInBits() == 128 &&
21010       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21011        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
21012        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
21013        Mask.equals(
21014            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
21015     bool Lo = Mask[0] == 0;
21016     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
21017     if (Depth == 1 && Root->getOpcode() == Shuffle)
21018       return false; // Nothing to do!
21019     MVT ShuffleVT;
21020     switch (Mask.size()) {
21021     case 8:
21022       ShuffleVT = MVT::v8i16;
21023       break;
21024     case 16:
21025       ShuffleVT = MVT::v16i8;
21026       break;
21027     default:
21028       llvm_unreachable("Impossible mask size!");
21029     };
21030     Op = DAG.getBitcast(ShuffleVT, Input);
21031     DCI.AddToWorklist(Op.getNode());
21032     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
21033     DCI.AddToWorklist(Op.getNode());
21034     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21035                   /*AddTo*/ true);
21036     return true;
21037   }
21038
21039   // Don't try to re-form single instruction chains under any circumstances now
21040   // that we've done encoding canonicalization for them.
21041   if (Depth < 2)
21042     return false;
21043
21044   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
21045   // can replace them with a single PSHUFB instruction profitably. Intel's
21046   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
21047   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
21048   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
21049     SmallVector<SDValue, 16> PSHUFBMask;
21050     int NumBytes = VT.getSizeInBits() / 8;
21051     int Ratio = NumBytes / Mask.size();
21052     for (int i = 0; i < NumBytes; ++i) {
21053       if (Mask[i / Ratio] == SM_SentinelUndef) {
21054         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
21055         continue;
21056       }
21057       int M = Mask[i / Ratio] != SM_SentinelZero
21058                   ? Ratio * Mask[i / Ratio] + i % Ratio
21059                   : 255;
21060       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
21061     }
21062     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
21063     Op = DAG.getBitcast(ByteVT, Input);
21064     DCI.AddToWorklist(Op.getNode());
21065     SDValue PSHUFBMaskOp =
21066         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
21067     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
21068     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
21069     DCI.AddToWorklist(Op.getNode());
21070     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
21071                   /*AddTo*/ true);
21072     return true;
21073   }
21074
21075   // Failed to find any combines.
21076   return false;
21077 }
21078
21079 /// \brief Fully generic combining of x86 shuffle instructions.
21080 ///
21081 /// This should be the last combine run over the x86 shuffle instructions. Once
21082 /// they have been fully optimized, this will recursively consider all chains
21083 /// of single-use shuffle instructions, build a generic model of the cumulative
21084 /// shuffle operation, and check for simpler instructions which implement this
21085 /// operation. We use this primarily for two purposes:
21086 ///
21087 /// 1) Collapse generic shuffles to specialized single instructions when
21088 ///    equivalent. In most cases, this is just an encoding size win, but
21089 ///    sometimes we will collapse multiple generic shuffles into a single
21090 ///    special-purpose shuffle.
21091 /// 2) Look for sequences of shuffle instructions with 3 or more total
21092 ///    instructions, and replace them with the slightly more expensive SSSE3
21093 ///    PSHUFB instruction if available. We do this as the last combining step
21094 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
21095 ///    a suitable short sequence of other instructions. The PHUFB will either
21096 ///    use a register or have to read from memory and so is slightly (but only
21097 ///    slightly) more expensive than the other shuffle instructions.
21098 ///
21099 /// Because this is inherently a quadratic operation (for each shuffle in
21100 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
21101 /// This should never be an issue in practice as the shuffle lowering doesn't
21102 /// produce sequences of more than 8 instructions.
21103 ///
21104 /// FIXME: We will currently miss some cases where the redundant shuffling
21105 /// would simplify under the threshold for PSHUFB formation because of
21106 /// combine-ordering. To fix this, we should do the redundant instruction
21107 /// combining in this recursive walk.
21108 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
21109                                           ArrayRef<int> RootMask,
21110                                           int Depth, bool HasPSHUFB,
21111                                           SelectionDAG &DAG,
21112                                           TargetLowering::DAGCombinerInfo &DCI,
21113                                           const X86Subtarget *Subtarget) {
21114   // Bound the depth of our recursive combine because this is ultimately
21115   // quadratic in nature.
21116   if (Depth > 8)
21117     return false;
21118
21119   // Directly rip through bitcasts to find the underlying operand.
21120   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
21121     Op = Op.getOperand(0);
21122
21123   MVT VT = Op.getSimpleValueType();
21124   if (!VT.isVector())
21125     return false; // Bail if we hit a non-vector.
21126
21127   assert(Root.getSimpleValueType().isVector() &&
21128          "Shuffles operate on vector types!");
21129   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
21130          "Can only combine shuffles of the same vector register size.");
21131
21132   if (!isTargetShuffle(Op.getOpcode()))
21133     return false;
21134   SmallVector<int, 16> OpMask;
21135   bool IsUnary;
21136   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
21137   // We only can combine unary shuffles which we can decode the mask for.
21138   if (!HaveMask || !IsUnary)
21139     return false;
21140
21141   assert(VT.getVectorNumElements() == OpMask.size() &&
21142          "Different mask size from vector size!");
21143   assert(((RootMask.size() > OpMask.size() &&
21144            RootMask.size() % OpMask.size() == 0) ||
21145           (OpMask.size() > RootMask.size() &&
21146            OpMask.size() % RootMask.size() == 0) ||
21147           OpMask.size() == RootMask.size()) &&
21148          "The smaller number of elements must divide the larger.");
21149   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
21150   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
21151   assert(((RootRatio == 1 && OpRatio == 1) ||
21152           (RootRatio == 1) != (OpRatio == 1)) &&
21153          "Must not have a ratio for both incoming and op masks!");
21154
21155   SmallVector<int, 16> Mask;
21156   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
21157
21158   // Merge this shuffle operation's mask into our accumulated mask. Note that
21159   // this shuffle's mask will be the first applied to the input, followed by the
21160   // root mask to get us all the way to the root value arrangement. The reason
21161   // for this order is that we are recursing up the operation chain.
21162   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
21163     int RootIdx = i / RootRatio;
21164     if (RootMask[RootIdx] < 0) {
21165       // This is a zero or undef lane, we're done.
21166       Mask.push_back(RootMask[RootIdx]);
21167       continue;
21168     }
21169
21170     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
21171     int OpIdx = RootMaskedIdx / OpRatio;
21172     if (OpMask[OpIdx] < 0) {
21173       // The incoming lanes are zero or undef, it doesn't matter which ones we
21174       // are using.
21175       Mask.push_back(OpMask[OpIdx]);
21176       continue;
21177     }
21178
21179     // Ok, we have non-zero lanes, map them through.
21180     Mask.push_back(OpMask[OpIdx] * OpRatio +
21181                    RootMaskedIdx % OpRatio);
21182   }
21183
21184   // See if we can recurse into the operand to combine more things.
21185   switch (Op.getOpcode()) {
21186     case X86ISD::PSHUFB:
21187       HasPSHUFB = true;
21188     case X86ISD::PSHUFD:
21189     case X86ISD::PSHUFHW:
21190     case X86ISD::PSHUFLW:
21191       if (Op.getOperand(0).hasOneUse() &&
21192           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21193                                         HasPSHUFB, DAG, DCI, Subtarget))
21194         return true;
21195       break;
21196
21197     case X86ISD::UNPCKL:
21198     case X86ISD::UNPCKH:
21199       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
21200       // We can't check for single use, we have to check that this shuffle is the only user.
21201       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
21202           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
21203                                         HasPSHUFB, DAG, DCI, Subtarget))
21204           return true;
21205       break;
21206   }
21207
21208   // Minor canonicalization of the accumulated shuffle mask to make it easier
21209   // to match below. All this does is detect masks with squential pairs of
21210   // elements, and shrink them to the half-width mask. It does this in a loop
21211   // so it will reduce the size of the mask to the minimal width mask which
21212   // performs an equivalent shuffle.
21213   SmallVector<int, 16> WidenedMask;
21214   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
21215     Mask = std::move(WidenedMask);
21216     WidenedMask.clear();
21217   }
21218
21219   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
21220                                 Subtarget);
21221 }
21222
21223 /// \brief Get the PSHUF-style mask from PSHUF node.
21224 ///
21225 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
21226 /// PSHUF-style masks that can be reused with such instructions.
21227 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
21228   MVT VT = N.getSimpleValueType();
21229   SmallVector<int, 4> Mask;
21230   bool IsUnary;
21231   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
21232   (void)HaveMask;
21233   assert(HaveMask);
21234
21235   // If we have more than 128-bits, only the low 128-bits of shuffle mask
21236   // matter. Check that the upper masks are repeats and remove them.
21237   if (VT.getSizeInBits() > 128) {
21238     int LaneElts = 128 / VT.getScalarSizeInBits();
21239 #ifndef NDEBUG
21240     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
21241       for (int j = 0; j < LaneElts; ++j)
21242         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
21243                "Mask doesn't repeat in high 128-bit lanes!");
21244 #endif
21245     Mask.resize(LaneElts);
21246   }
21247
21248   switch (N.getOpcode()) {
21249   case X86ISD::PSHUFD:
21250     return Mask;
21251   case X86ISD::PSHUFLW:
21252     Mask.resize(4);
21253     return Mask;
21254   case X86ISD::PSHUFHW:
21255     Mask.erase(Mask.begin(), Mask.begin() + 4);
21256     for (int &M : Mask)
21257       M -= 4;
21258     return Mask;
21259   default:
21260     llvm_unreachable("No valid shuffle instruction found!");
21261   }
21262 }
21263
21264 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
21265 ///
21266 /// We walk up the chain and look for a combinable shuffle, skipping over
21267 /// shuffles that we could hoist this shuffle's transformation past without
21268 /// altering anything.
21269 static SDValue
21270 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
21271                              SelectionDAG &DAG,
21272                              TargetLowering::DAGCombinerInfo &DCI) {
21273   assert(N.getOpcode() == X86ISD::PSHUFD &&
21274          "Called with something other than an x86 128-bit half shuffle!");
21275   SDLoc DL(N);
21276
21277   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
21278   // of the shuffles in the chain so that we can form a fresh chain to replace
21279   // this one.
21280   SmallVector<SDValue, 8> Chain;
21281   SDValue V = N.getOperand(0);
21282   for (; V.hasOneUse(); V = V.getOperand(0)) {
21283     switch (V.getOpcode()) {
21284     default:
21285       return SDValue(); // Nothing combined!
21286
21287     case ISD::BITCAST:
21288       // Skip bitcasts as we always know the type for the target specific
21289       // instructions.
21290       continue;
21291
21292     case X86ISD::PSHUFD:
21293       // Found another dword shuffle.
21294       break;
21295
21296     case X86ISD::PSHUFLW:
21297       // Check that the low words (being shuffled) are the identity in the
21298       // dword shuffle, and the high words are self-contained.
21299       if (Mask[0] != 0 || Mask[1] != 1 ||
21300           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
21301         return SDValue();
21302
21303       Chain.push_back(V);
21304       continue;
21305
21306     case X86ISD::PSHUFHW:
21307       // Check that the high words (being shuffled) are the identity in the
21308       // dword shuffle, and the low words are self-contained.
21309       if (Mask[2] != 2 || Mask[3] != 3 ||
21310           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
21311         return SDValue();
21312
21313       Chain.push_back(V);
21314       continue;
21315
21316     case X86ISD::UNPCKL:
21317     case X86ISD::UNPCKH:
21318       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
21319       // shuffle into a preceding word shuffle.
21320       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
21321           V.getSimpleValueType().getScalarType() != MVT::i16)
21322         return SDValue();
21323
21324       // Search for a half-shuffle which we can combine with.
21325       unsigned CombineOp =
21326           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
21327       if (V.getOperand(0) != V.getOperand(1) ||
21328           !V->isOnlyUserOf(V.getOperand(0).getNode()))
21329         return SDValue();
21330       Chain.push_back(V);
21331       V = V.getOperand(0);
21332       do {
21333         switch (V.getOpcode()) {
21334         default:
21335           return SDValue(); // Nothing to combine.
21336
21337         case X86ISD::PSHUFLW:
21338         case X86ISD::PSHUFHW:
21339           if (V.getOpcode() == CombineOp)
21340             break;
21341
21342           Chain.push_back(V);
21343
21344           // Fallthrough!
21345         case ISD::BITCAST:
21346           V = V.getOperand(0);
21347           continue;
21348         }
21349         break;
21350       } while (V.hasOneUse());
21351       break;
21352     }
21353     // Break out of the loop if we break out of the switch.
21354     break;
21355   }
21356
21357   if (!V.hasOneUse())
21358     // We fell out of the loop without finding a viable combining instruction.
21359     return SDValue();
21360
21361   // Merge this node's mask and our incoming mask.
21362   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21363   for (int &M : Mask)
21364     M = VMask[M];
21365   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
21366                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21367
21368   // Rebuild the chain around this new shuffle.
21369   while (!Chain.empty()) {
21370     SDValue W = Chain.pop_back_val();
21371
21372     if (V.getValueType() != W.getOperand(0).getValueType())
21373       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21374
21375     switch (W.getOpcode()) {
21376     default:
21377       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21378
21379     case X86ISD::UNPCKL:
21380     case X86ISD::UNPCKH:
21381       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21382       break;
21383
21384     case X86ISD::PSHUFD:
21385     case X86ISD::PSHUFLW:
21386     case X86ISD::PSHUFHW:
21387       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21388       break;
21389     }
21390   }
21391   if (V.getValueType() != N.getValueType())
21392     V = DAG.getBitcast(N.getValueType(), V);
21393
21394   // Return the new chain to replace N.
21395   return V;
21396 }
21397
21398 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21399 ///
21400 /// We walk up the chain, skipping shuffles of the other half and looking
21401 /// through shuffles which switch halves trying to find a shuffle of the same
21402 /// pair of dwords.
21403 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21404                                         SelectionDAG &DAG,
21405                                         TargetLowering::DAGCombinerInfo &DCI) {
21406   assert(
21407       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21408       "Called with something other than an x86 128-bit half shuffle!");
21409   SDLoc DL(N);
21410   unsigned CombineOpcode = N.getOpcode();
21411
21412   // Walk up a single-use chain looking for a combinable shuffle.
21413   SDValue V = N.getOperand(0);
21414   for (; V.hasOneUse(); V = V.getOperand(0)) {
21415     switch (V.getOpcode()) {
21416     default:
21417       return false; // Nothing combined!
21418
21419     case ISD::BITCAST:
21420       // Skip bitcasts as we always know the type for the target specific
21421       // instructions.
21422       continue;
21423
21424     case X86ISD::PSHUFLW:
21425     case X86ISD::PSHUFHW:
21426       if (V.getOpcode() == CombineOpcode)
21427         break;
21428
21429       // Other-half shuffles are no-ops.
21430       continue;
21431     }
21432     // Break out of the loop if we break out of the switch.
21433     break;
21434   }
21435
21436   if (!V.hasOneUse())
21437     // We fell out of the loop without finding a viable combining instruction.
21438     return false;
21439
21440   // Combine away the bottom node as its shuffle will be accumulated into
21441   // a preceding shuffle.
21442   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21443
21444   // Record the old value.
21445   SDValue Old = V;
21446
21447   // Merge this node's mask and our incoming mask (adjusted to account for all
21448   // the pshufd instructions encountered).
21449   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21450   for (int &M : Mask)
21451     M = VMask[M];
21452   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21453                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21454
21455   // Check that the shuffles didn't cancel each other out. If not, we need to
21456   // combine to the new one.
21457   if (Old != V)
21458     // Replace the combinable shuffle with the combined one, updating all users
21459     // so that we re-evaluate the chain here.
21460     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21461
21462   return true;
21463 }
21464
21465 /// \brief Try to combine x86 target specific shuffles.
21466 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21467                                            TargetLowering::DAGCombinerInfo &DCI,
21468                                            const X86Subtarget *Subtarget) {
21469   SDLoc DL(N);
21470   MVT VT = N.getSimpleValueType();
21471   SmallVector<int, 4> Mask;
21472
21473   switch (N.getOpcode()) {
21474   case X86ISD::PSHUFD:
21475   case X86ISD::PSHUFLW:
21476   case X86ISD::PSHUFHW:
21477     Mask = getPSHUFShuffleMask(N);
21478     assert(Mask.size() == 4);
21479     break;
21480   default:
21481     return SDValue();
21482   }
21483
21484   // Nuke no-op shuffles that show up after combining.
21485   if (isNoopShuffleMask(Mask))
21486     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21487
21488   // Look for simplifications involving one or two shuffle instructions.
21489   SDValue V = N.getOperand(0);
21490   switch (N.getOpcode()) {
21491   default:
21492     break;
21493   case X86ISD::PSHUFLW:
21494   case X86ISD::PSHUFHW:
21495     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21496
21497     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21498       return SDValue(); // We combined away this shuffle, so we're done.
21499
21500     // See if this reduces to a PSHUFD which is no more expensive and can
21501     // combine with more operations. Note that it has to at least flip the
21502     // dwords as otherwise it would have been removed as a no-op.
21503     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21504       int DMask[] = {0, 1, 2, 3};
21505       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21506       DMask[DOffset + 0] = DOffset + 1;
21507       DMask[DOffset + 1] = DOffset + 0;
21508       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21509       V = DAG.getBitcast(DVT, V);
21510       DCI.AddToWorklist(V.getNode());
21511       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21512                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21513       DCI.AddToWorklist(V.getNode());
21514       return DAG.getBitcast(VT, V);
21515     }
21516
21517     // Look for shuffle patterns which can be implemented as a single unpack.
21518     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21519     // only works when we have a PSHUFD followed by two half-shuffles.
21520     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21521         (V.getOpcode() == X86ISD::PSHUFLW ||
21522          V.getOpcode() == X86ISD::PSHUFHW) &&
21523         V.getOpcode() != N.getOpcode() &&
21524         V.hasOneUse()) {
21525       SDValue D = V.getOperand(0);
21526       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21527         D = D.getOperand(0);
21528       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21529         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21530         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21531         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21532         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21533         int WordMask[8];
21534         for (int i = 0; i < 4; ++i) {
21535           WordMask[i + NOffset] = Mask[i] + NOffset;
21536           WordMask[i + VOffset] = VMask[i] + VOffset;
21537         }
21538         // Map the word mask through the DWord mask.
21539         int MappedMask[8];
21540         for (int i = 0; i < 8; ++i)
21541           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21542         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21543             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21544           // We can replace all three shuffles with an unpack.
21545           V = DAG.getBitcast(VT, D.getOperand(0));
21546           DCI.AddToWorklist(V.getNode());
21547           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21548                                                 : X86ISD::UNPCKH,
21549                              DL, VT, V, V);
21550         }
21551       }
21552     }
21553
21554     break;
21555
21556   case X86ISD::PSHUFD:
21557     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21558       return NewN;
21559
21560     break;
21561   }
21562
21563   return SDValue();
21564 }
21565
21566 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21567 ///
21568 /// We combine this directly on the abstract vector shuffle nodes so it is
21569 /// easier to generically match. We also insert dummy vector shuffle nodes for
21570 /// the operands which explicitly discard the lanes which are unused by this
21571 /// operation to try to flow through the rest of the combiner the fact that
21572 /// they're unused.
21573 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21574   SDLoc DL(N);
21575   EVT VT = N->getValueType(0);
21576
21577   // We only handle target-independent shuffles.
21578   // FIXME: It would be easy and harmless to use the target shuffle mask
21579   // extraction tool to support more.
21580   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21581     return SDValue();
21582
21583   auto *SVN = cast<ShuffleVectorSDNode>(N);
21584   ArrayRef<int> Mask = SVN->getMask();
21585   SDValue V1 = N->getOperand(0);
21586   SDValue V2 = N->getOperand(1);
21587
21588   // We require the first shuffle operand to be the SUB node, and the second to
21589   // be the ADD node.
21590   // FIXME: We should support the commuted patterns.
21591   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21592     return SDValue();
21593
21594   // If there are other uses of these operations we can't fold them.
21595   if (!V1->hasOneUse() || !V2->hasOneUse())
21596     return SDValue();
21597
21598   // Ensure that both operations have the same operands. Note that we can
21599   // commute the FADD operands.
21600   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21601   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21602       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21603     return SDValue();
21604
21605   // We're looking for blends between FADD and FSUB nodes. We insist on these
21606   // nodes being lined up in a specific expected pattern.
21607   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21608         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21609         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21610     return SDValue();
21611
21612   // Only specific types are legal at this point, assert so we notice if and
21613   // when these change.
21614   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21615           VT == MVT::v4f64) &&
21616          "Unknown vector type encountered!");
21617
21618   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21619 }
21620
21621 /// PerformShuffleCombine - Performs several different shuffle combines.
21622 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21623                                      TargetLowering::DAGCombinerInfo &DCI,
21624                                      const X86Subtarget *Subtarget) {
21625   SDLoc dl(N);
21626   SDValue N0 = N->getOperand(0);
21627   SDValue N1 = N->getOperand(1);
21628   EVT VT = N->getValueType(0);
21629
21630   // Don't create instructions with illegal types after legalize types has run.
21631   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21632   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21633     return SDValue();
21634
21635   // If we have legalized the vector types, look for blends of FADD and FSUB
21636   // nodes that we can fuse into an ADDSUB node.
21637   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21638     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21639       return AddSub;
21640
21641   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21642   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21643       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21644     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21645
21646   // During Type Legalization, when promoting illegal vector types,
21647   // the backend might introduce new shuffle dag nodes and bitcasts.
21648   //
21649   // This code performs the following transformation:
21650   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21651   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21652   //
21653   // We do this only if both the bitcast and the BINOP dag nodes have
21654   // one use. Also, perform this transformation only if the new binary
21655   // operation is legal. This is to avoid introducing dag nodes that
21656   // potentially need to be further expanded (or custom lowered) into a
21657   // less optimal sequence of dag nodes.
21658   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21659       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21660       N0.getOpcode() == ISD::BITCAST) {
21661     SDValue BC0 = N0.getOperand(0);
21662     EVT SVT = BC0.getValueType();
21663     unsigned Opcode = BC0.getOpcode();
21664     unsigned NumElts = VT.getVectorNumElements();
21665
21666     if (BC0.hasOneUse() && SVT.isVector() &&
21667         SVT.getVectorNumElements() * 2 == NumElts &&
21668         TLI.isOperationLegal(Opcode, VT)) {
21669       bool CanFold = false;
21670       switch (Opcode) {
21671       default : break;
21672       case ISD::ADD :
21673       case ISD::FADD :
21674       case ISD::SUB :
21675       case ISD::FSUB :
21676       case ISD::MUL :
21677       case ISD::FMUL :
21678         CanFold = true;
21679       }
21680
21681       unsigned SVTNumElts = SVT.getVectorNumElements();
21682       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21683       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21684         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21685       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21686         CanFold = SVOp->getMaskElt(i) < 0;
21687
21688       if (CanFold) {
21689         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21690         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21691         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21692         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21693       }
21694     }
21695   }
21696
21697   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21698   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21699   // consecutive, non-overlapping, and in the right order.
21700   SmallVector<SDValue, 16> Elts;
21701   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21702     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21703
21704   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21705     return LD;
21706
21707   if (isTargetShuffle(N->getOpcode())) {
21708     SDValue Shuffle =
21709         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21710     if (Shuffle.getNode())
21711       return Shuffle;
21712
21713     // Try recursively combining arbitrary sequences of x86 shuffle
21714     // instructions into higher-order shuffles. We do this after combining
21715     // specific PSHUF instruction sequences into their minimal form so that we
21716     // can evaluate how many specialized shuffle instructions are involved in
21717     // a particular chain.
21718     SmallVector<int, 1> NonceMask; // Just a placeholder.
21719     NonceMask.push_back(0);
21720     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21721                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21722                                       DCI, Subtarget))
21723       return SDValue(); // This routine will use CombineTo to replace N.
21724   }
21725
21726   return SDValue();
21727 }
21728
21729 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21730 /// specific shuffle of a load can be folded into a single element load.
21731 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21732 /// shuffles have been custom lowered so we need to handle those here.
21733 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21734                                          TargetLowering::DAGCombinerInfo &DCI) {
21735   if (DCI.isBeforeLegalizeOps())
21736     return SDValue();
21737
21738   SDValue InVec = N->getOperand(0);
21739   SDValue EltNo = N->getOperand(1);
21740
21741   if (!isa<ConstantSDNode>(EltNo))
21742     return SDValue();
21743
21744   EVT OriginalVT = InVec.getValueType();
21745
21746   if (InVec.getOpcode() == ISD::BITCAST) {
21747     // Don't duplicate a load with other uses.
21748     if (!InVec.hasOneUse())
21749       return SDValue();
21750     EVT BCVT = InVec.getOperand(0).getValueType();
21751     if (!BCVT.isVector() ||
21752         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21753       return SDValue();
21754     InVec = InVec.getOperand(0);
21755   }
21756
21757   EVT CurrentVT = InVec.getValueType();
21758
21759   if (!isTargetShuffle(InVec.getOpcode()))
21760     return SDValue();
21761
21762   // Don't duplicate a load with other uses.
21763   if (!InVec.hasOneUse())
21764     return SDValue();
21765
21766   SmallVector<int, 16> ShuffleMask;
21767   bool UnaryShuffle;
21768   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21769                             ShuffleMask, UnaryShuffle))
21770     return SDValue();
21771
21772   // Select the input vector, guarding against out of range extract vector.
21773   unsigned NumElems = CurrentVT.getVectorNumElements();
21774   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21775   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21776   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21777                                          : InVec.getOperand(1);
21778
21779   // If inputs to shuffle are the same for both ops, then allow 2 uses
21780   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21781                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21782
21783   if (LdNode.getOpcode() == ISD::BITCAST) {
21784     // Don't duplicate a load with other uses.
21785     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21786       return SDValue();
21787
21788     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21789     LdNode = LdNode.getOperand(0);
21790   }
21791
21792   if (!ISD::isNormalLoad(LdNode.getNode()))
21793     return SDValue();
21794
21795   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21796
21797   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21798     return SDValue();
21799
21800   EVT EltVT = N->getValueType(0);
21801   // If there's a bitcast before the shuffle, check if the load type and
21802   // alignment is valid.
21803   unsigned Align = LN0->getAlignment();
21804   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21805   unsigned NewAlign = DAG.getDataLayout().getABITypeAlignment(
21806       EltVT.getTypeForEVT(*DAG.getContext()));
21807
21808   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21809     return SDValue();
21810
21811   // All checks match so transform back to vector_shuffle so that DAG combiner
21812   // can finish the job
21813   SDLoc dl(N);
21814
21815   // Create shuffle node taking into account the case that its a unary shuffle
21816   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21817                                    : InVec.getOperand(1);
21818   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21819                                  InVec.getOperand(0), Shuffle,
21820                                  &ShuffleMask[0]);
21821   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21822   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21823                      EltNo);
21824 }
21825
21826 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21827 /// special and don't usually play with other vector types, it's better to
21828 /// handle them early to be sure we emit efficient code by avoiding
21829 /// store-load conversions.
21830 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21831   if (N->getValueType(0) != MVT::x86mmx ||
21832       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21833       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21834     return SDValue();
21835
21836   SDValue V = N->getOperand(0);
21837   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21838   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21839     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21840                        N->getValueType(0), V.getOperand(0));
21841
21842   return SDValue();
21843 }
21844
21845 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21846 /// generation and convert it from being a bunch of shuffles and extracts
21847 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21848 /// storing the value and loading scalars back, while for x64 we should
21849 /// use 64-bit extracts and shifts.
21850 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21851                                          TargetLowering::DAGCombinerInfo &DCI) {
21852   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21853     return NewOp;
21854
21855   SDValue InputVector = N->getOperand(0);
21856   SDLoc dl(InputVector);
21857   // Detect mmx to i32 conversion through a v2i32 elt extract.
21858   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21859       N->getValueType(0) == MVT::i32 &&
21860       InputVector.getValueType() == MVT::v2i32) {
21861
21862     // The bitcast source is a direct mmx result.
21863     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21864     if (MMXSrc.getValueType() == MVT::x86mmx)
21865       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21866                          N->getValueType(0),
21867                          InputVector.getNode()->getOperand(0));
21868
21869     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21870     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21871     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21872         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21873         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21874         MMXSrcOp.getValueType() == MVT::v1i64 &&
21875         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21876       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21877                          N->getValueType(0),
21878                          MMXSrcOp.getOperand(0));
21879   }
21880
21881   EVT VT = N->getValueType(0);
21882
21883   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21884       InputVector.getOpcode() == ISD::BITCAST &&
21885       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21886     uint64_t ExtractedElt =
21887           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21888     uint64_t InputValue =
21889           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21890     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21891     return DAG.getConstant(Res, dl, MVT::i1);
21892   }
21893   // Only operate on vectors of 4 elements, where the alternative shuffling
21894   // gets to be more expensive.
21895   if (InputVector.getValueType() != MVT::v4i32)
21896     return SDValue();
21897
21898   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21899   // single use which is a sign-extend or zero-extend, and all elements are
21900   // used.
21901   SmallVector<SDNode *, 4> Uses;
21902   unsigned ExtractedElements = 0;
21903   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21904        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21905     if (UI.getUse().getResNo() != InputVector.getResNo())
21906       return SDValue();
21907
21908     SDNode *Extract = *UI;
21909     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21910       return SDValue();
21911
21912     if (Extract->getValueType(0) != MVT::i32)
21913       return SDValue();
21914     if (!Extract->hasOneUse())
21915       return SDValue();
21916     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21917         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21918       return SDValue();
21919     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21920       return SDValue();
21921
21922     // Record which element was extracted.
21923     ExtractedElements |=
21924       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21925
21926     Uses.push_back(Extract);
21927   }
21928
21929   // If not all the elements were used, this may not be worthwhile.
21930   if (ExtractedElements != 15)
21931     return SDValue();
21932
21933   // Ok, we've now decided to do the transformation.
21934   // If 64-bit shifts are legal, use the extract-shift sequence,
21935   // otherwise bounce the vector off the cache.
21936   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21937   SDValue Vals[4];
21938
21939   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21940     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21941     auto &DL = DAG.getDataLayout();
21942     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy(DL);
21943     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21944       DAG.getConstant(0, dl, VecIdxTy));
21945     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21946       DAG.getConstant(1, dl, VecIdxTy));
21947
21948     SDValue ShAmt = DAG.getConstant(
21949         32, dl, DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64, DL));
21950     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21951     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21952       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21953     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21954     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21955       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21956   } else {
21957     // Store the value to a temporary stack slot.
21958     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21959     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21960       MachinePointerInfo(), false, false, 0);
21961
21962     EVT ElementType = InputVector.getValueType().getVectorElementType();
21963     unsigned EltSize = ElementType.getSizeInBits() / 8;
21964
21965     // Replace each use (extract) with a load of the appropriate element.
21966     for (unsigned i = 0; i < 4; ++i) {
21967       uint64_t Offset = EltSize * i;
21968       auto PtrVT = TLI.getPointerTy(DAG.getDataLayout());
21969       SDValue OffsetVal = DAG.getConstant(Offset, dl, PtrVT);
21970
21971       SDValue ScalarAddr =
21972           DAG.getNode(ISD::ADD, dl, PtrVT, StackPtr, OffsetVal);
21973
21974       // Load the scalar.
21975       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21976                             ScalarAddr, MachinePointerInfo(),
21977                             false, false, false, 0);
21978
21979     }
21980   }
21981
21982   // Replace the extracts
21983   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21984     UE = Uses.end(); UI != UE; ++UI) {
21985     SDNode *Extract = *UI;
21986
21987     SDValue Idx = Extract->getOperand(1);
21988     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21989     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21990   }
21991
21992   // The replacement was made in place; don't return anything.
21993   return SDValue();
21994 }
21995
21996 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21997 static std::pair<unsigned, bool>
21998 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21999                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
22000   if (!VT.isVector())
22001     return std::make_pair(0, false);
22002
22003   bool NeedSplit = false;
22004   switch (VT.getSimpleVT().SimpleTy) {
22005   default: return std::make_pair(0, false);
22006   case MVT::v4i64:
22007   case MVT::v2i64:
22008     if (!Subtarget->hasVLX())
22009       return std::make_pair(0, false);
22010     break;
22011   case MVT::v64i8:
22012   case MVT::v32i16:
22013     if (!Subtarget->hasBWI())
22014       return std::make_pair(0, false);
22015     break;
22016   case MVT::v16i32:
22017   case MVT::v8i64:
22018     if (!Subtarget->hasAVX512())
22019       return std::make_pair(0, false);
22020     break;
22021   case MVT::v32i8:
22022   case MVT::v16i16:
22023   case MVT::v8i32:
22024     if (!Subtarget->hasAVX2())
22025       NeedSplit = true;
22026     if (!Subtarget->hasAVX())
22027       return std::make_pair(0, false);
22028     break;
22029   case MVT::v16i8:
22030   case MVT::v8i16:
22031   case MVT::v4i32:
22032     if (!Subtarget->hasSSE2())
22033       return std::make_pair(0, false);
22034   }
22035
22036   // SSE2 has only a small subset of the operations.
22037   bool hasUnsigned = Subtarget->hasSSE41() ||
22038                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
22039   bool hasSigned = Subtarget->hasSSE41() ||
22040                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
22041
22042   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22043
22044   unsigned Opc = 0;
22045   // Check for x CC y ? x : y.
22046   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22047       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22048     switch (CC) {
22049     default: break;
22050     case ISD::SETULT:
22051     case ISD::SETULE:
22052       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22053     case ISD::SETUGT:
22054     case ISD::SETUGE:
22055       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22056     case ISD::SETLT:
22057     case ISD::SETLE:
22058       Opc = hasSigned ? ISD::SMIN : 0; break;
22059     case ISD::SETGT:
22060     case ISD::SETGE:
22061       Opc = hasSigned ? ISD::SMAX : 0; break;
22062     }
22063   // Check for x CC y ? y : x -- a min/max with reversed arms.
22064   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22065              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22066     switch (CC) {
22067     default: break;
22068     case ISD::SETULT:
22069     case ISD::SETULE:
22070       Opc = hasUnsigned ? ISD::UMAX : 0; break;
22071     case ISD::SETUGT:
22072     case ISD::SETUGE:
22073       Opc = hasUnsigned ? ISD::UMIN : 0; break;
22074     case ISD::SETLT:
22075     case ISD::SETLE:
22076       Opc = hasSigned ? ISD::SMAX : 0; break;
22077     case ISD::SETGT:
22078     case ISD::SETGE:
22079       Opc = hasSigned ? ISD::SMIN : 0; break;
22080     }
22081   }
22082
22083   return std::make_pair(Opc, NeedSplit);
22084 }
22085
22086 static SDValue
22087 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
22088                                       const X86Subtarget *Subtarget) {
22089   SDLoc dl(N);
22090   SDValue Cond = N->getOperand(0);
22091   SDValue LHS = N->getOperand(1);
22092   SDValue RHS = N->getOperand(2);
22093
22094   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
22095     SDValue CondSrc = Cond->getOperand(0);
22096     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
22097       Cond = CondSrc->getOperand(0);
22098   }
22099
22100   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
22101     return SDValue();
22102
22103   // A vselect where all conditions and data are constants can be optimized into
22104   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
22105   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
22106       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
22107     return SDValue();
22108
22109   unsigned MaskValue = 0;
22110   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
22111     return SDValue();
22112
22113   MVT VT = N->getSimpleValueType(0);
22114   unsigned NumElems = VT.getVectorNumElements();
22115   SmallVector<int, 8> ShuffleMask(NumElems, -1);
22116   for (unsigned i = 0; i < NumElems; ++i) {
22117     // Be sure we emit undef where we can.
22118     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
22119       ShuffleMask[i] = -1;
22120     else
22121       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
22122   }
22123
22124   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22125   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
22126     return SDValue();
22127   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
22128 }
22129
22130 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
22131 /// nodes.
22132 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
22133                                     TargetLowering::DAGCombinerInfo &DCI,
22134                                     const X86Subtarget *Subtarget) {
22135   SDLoc DL(N);
22136   SDValue Cond = N->getOperand(0);
22137   // Get the LHS/RHS of the select.
22138   SDValue LHS = N->getOperand(1);
22139   SDValue RHS = N->getOperand(2);
22140   EVT VT = LHS.getValueType();
22141   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
22142
22143   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
22144   // instructions match the semantics of the common C idiom x<y?x:y but not
22145   // x<=y?x:y, because of how they handle negative zero (which can be
22146   // ignored in unsafe-math mode).
22147   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
22148   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
22149       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
22150       (Subtarget->hasSSE2() ||
22151        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
22152     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22153
22154     unsigned Opcode = 0;
22155     // Check for x CC y ? x : y.
22156     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22157         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22158       switch (CC) {
22159       default: break;
22160       case ISD::SETULT:
22161         // Converting this to a min would handle NaNs incorrectly, and swapping
22162         // the operands would cause it to handle comparisons between positive
22163         // and negative zero incorrectly.
22164         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22165           if (!DAG.getTarget().Options.UnsafeFPMath &&
22166               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22167             break;
22168           std::swap(LHS, RHS);
22169         }
22170         Opcode = X86ISD::FMIN;
22171         break;
22172       case ISD::SETOLE:
22173         // Converting this to a min would handle comparisons between positive
22174         // and negative zero incorrectly.
22175         if (!DAG.getTarget().Options.UnsafeFPMath &&
22176             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22177           break;
22178         Opcode = X86ISD::FMIN;
22179         break;
22180       case ISD::SETULE:
22181         // Converting this to a min would handle both negative zeros and NaNs
22182         // incorrectly, but we can swap the operands to fix both.
22183         std::swap(LHS, RHS);
22184       case ISD::SETOLT:
22185       case ISD::SETLT:
22186       case ISD::SETLE:
22187         Opcode = X86ISD::FMIN;
22188         break;
22189
22190       case ISD::SETOGE:
22191         // Converting this to a max would handle comparisons between positive
22192         // and negative zero incorrectly.
22193         if (!DAG.getTarget().Options.UnsafeFPMath &&
22194             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
22195           break;
22196         Opcode = X86ISD::FMAX;
22197         break;
22198       case ISD::SETUGT:
22199         // Converting this to a max would handle NaNs incorrectly, and swapping
22200         // the operands would cause it to handle comparisons between positive
22201         // and negative zero incorrectly.
22202         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
22203           if (!DAG.getTarget().Options.UnsafeFPMath &&
22204               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
22205             break;
22206           std::swap(LHS, RHS);
22207         }
22208         Opcode = X86ISD::FMAX;
22209         break;
22210       case ISD::SETUGE:
22211         // Converting this to a max would handle both negative zeros and NaNs
22212         // incorrectly, but we can swap the operands to fix both.
22213         std::swap(LHS, RHS);
22214       case ISD::SETOGT:
22215       case ISD::SETGT:
22216       case ISD::SETGE:
22217         Opcode = X86ISD::FMAX;
22218         break;
22219       }
22220     // Check for x CC y ? y : x -- a min/max with reversed arms.
22221     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
22222                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
22223       switch (CC) {
22224       default: break;
22225       case ISD::SETOGE:
22226         // Converting this to a min would handle comparisons between positive
22227         // and negative zero incorrectly, and swapping the operands would
22228         // cause it to handle NaNs incorrectly.
22229         if (!DAG.getTarget().Options.UnsafeFPMath &&
22230             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
22231           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22232             break;
22233           std::swap(LHS, RHS);
22234         }
22235         Opcode = X86ISD::FMIN;
22236         break;
22237       case ISD::SETUGT:
22238         // Converting this to a min would handle NaNs incorrectly.
22239         if (!DAG.getTarget().Options.UnsafeFPMath &&
22240             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
22241           break;
22242         Opcode = X86ISD::FMIN;
22243         break;
22244       case ISD::SETUGE:
22245         // Converting this to a min would handle both negative zeros and NaNs
22246         // incorrectly, but we can swap the operands to fix both.
22247         std::swap(LHS, RHS);
22248       case ISD::SETOGT:
22249       case ISD::SETGT:
22250       case ISD::SETGE:
22251         Opcode = X86ISD::FMIN;
22252         break;
22253
22254       case ISD::SETULT:
22255         // Converting this to a max would handle NaNs incorrectly.
22256         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22257           break;
22258         Opcode = X86ISD::FMAX;
22259         break;
22260       case ISD::SETOLE:
22261         // Converting this to a max would handle comparisons between positive
22262         // and negative zero incorrectly, and swapping the operands would
22263         // cause it to handle NaNs incorrectly.
22264         if (!DAG.getTarget().Options.UnsafeFPMath &&
22265             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
22266           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
22267             break;
22268           std::swap(LHS, RHS);
22269         }
22270         Opcode = X86ISD::FMAX;
22271         break;
22272       case ISD::SETULE:
22273         // Converting this to a max would handle both negative zeros and NaNs
22274         // incorrectly, but we can swap the operands to fix both.
22275         std::swap(LHS, RHS);
22276       case ISD::SETOLT:
22277       case ISD::SETLT:
22278       case ISD::SETLE:
22279         Opcode = X86ISD::FMAX;
22280         break;
22281       }
22282     }
22283
22284     if (Opcode)
22285       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
22286   }
22287
22288   EVT CondVT = Cond.getValueType();
22289   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
22290       CondVT.getVectorElementType() == MVT::i1) {
22291     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
22292     // lowering on KNL. In this case we convert it to
22293     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
22294     // The same situation for all 128 and 256-bit vectors of i8 and i16.
22295     // Since SKX these selects have a proper lowering.
22296     EVT OpVT = LHS.getValueType();
22297     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
22298         (OpVT.getVectorElementType() == MVT::i8 ||
22299          OpVT.getVectorElementType() == MVT::i16) &&
22300         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
22301       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
22302       DCI.AddToWorklist(Cond.getNode());
22303       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
22304     }
22305   }
22306   // If this is a select between two integer constants, try to do some
22307   // optimizations.
22308   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
22309     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
22310       // Don't do this for crazy integer types.
22311       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
22312         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
22313         // so that TrueC (the true value) is larger than FalseC.
22314         bool NeedsCondInvert = false;
22315
22316         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
22317             // Efficiently invertible.
22318             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
22319              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
22320               isa<ConstantSDNode>(Cond.getOperand(1))))) {
22321           NeedsCondInvert = true;
22322           std::swap(TrueC, FalseC);
22323         }
22324
22325         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
22326         if (FalseC->getAPIntValue() == 0 &&
22327             TrueC->getAPIntValue().isPowerOf2()) {
22328           if (NeedsCondInvert) // Invert the condition if needed.
22329             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22330                                DAG.getConstant(1, DL, Cond.getValueType()));
22331
22332           // Zero extend the condition if needed.
22333           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
22334
22335           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22336           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
22337                              DAG.getConstant(ShAmt, DL, MVT::i8));
22338         }
22339
22340         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
22341         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22342           if (NeedsCondInvert) // Invert the condition if needed.
22343             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22344                                DAG.getConstant(1, DL, Cond.getValueType()));
22345
22346           // Zero extend the condition if needed.
22347           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22348                              FalseC->getValueType(0), Cond);
22349           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22350                              SDValue(FalseC, 0));
22351         }
22352
22353         // Optimize cases that will turn into an LEA instruction.  This requires
22354         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22355         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22356           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22357           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22358
22359           bool isFastMultiplier = false;
22360           if (Diff < 10) {
22361             switch ((unsigned char)Diff) {
22362               default: break;
22363               case 1:  // result = add base, cond
22364               case 2:  // result = lea base(    , cond*2)
22365               case 3:  // result = lea base(cond, cond*2)
22366               case 4:  // result = lea base(    , cond*4)
22367               case 5:  // result = lea base(cond, cond*4)
22368               case 8:  // result = lea base(    , cond*8)
22369               case 9:  // result = lea base(cond, cond*8)
22370                 isFastMultiplier = true;
22371                 break;
22372             }
22373           }
22374
22375           if (isFastMultiplier) {
22376             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22377             if (NeedsCondInvert) // Invert the condition if needed.
22378               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22379                                  DAG.getConstant(1, DL, Cond.getValueType()));
22380
22381             // Zero extend the condition if needed.
22382             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22383                                Cond);
22384             // Scale the condition by the difference.
22385             if (Diff != 1)
22386               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22387                                  DAG.getConstant(Diff, DL,
22388                                                  Cond.getValueType()));
22389
22390             // Add the base if non-zero.
22391             if (FalseC->getAPIntValue() != 0)
22392               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22393                                  SDValue(FalseC, 0));
22394             return Cond;
22395           }
22396         }
22397       }
22398   }
22399
22400   // Canonicalize max and min:
22401   // (x > y) ? x : y -> (x >= y) ? x : y
22402   // (x < y) ? x : y -> (x <= y) ? x : y
22403   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22404   // the need for an extra compare
22405   // against zero. e.g.
22406   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22407   // subl   %esi, %edi
22408   // testl  %edi, %edi
22409   // movl   $0, %eax
22410   // cmovgl %edi, %eax
22411   // =>
22412   // xorl   %eax, %eax
22413   // subl   %esi, $edi
22414   // cmovsl %eax, %edi
22415   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22416       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22417       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22418     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22419     switch (CC) {
22420     default: break;
22421     case ISD::SETLT:
22422     case ISD::SETGT: {
22423       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22424       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22425                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22426       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22427     }
22428     }
22429   }
22430
22431   // Early exit check
22432   if (!TLI.isTypeLegal(VT))
22433     return SDValue();
22434
22435   // Match VSELECTs into subs with unsigned saturation.
22436   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22437       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22438       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22439        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22440     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22441
22442     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22443     // left side invert the predicate to simplify logic below.
22444     SDValue Other;
22445     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22446       Other = RHS;
22447       CC = ISD::getSetCCInverse(CC, true);
22448     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22449       Other = LHS;
22450     }
22451
22452     if (Other.getNode() && Other->getNumOperands() == 2 &&
22453         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22454       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22455       SDValue CondRHS = Cond->getOperand(1);
22456
22457       // Look for a general sub with unsigned saturation first.
22458       // x >= y ? x-y : 0 --> subus x, y
22459       // x >  y ? x-y : 0 --> subus x, y
22460       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22461           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22462         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22463
22464       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22465         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22466           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22467             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22468               // If the RHS is a constant we have to reverse the const
22469               // canonicalization.
22470               // x > C-1 ? x+-C : 0 --> subus x, C
22471               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22472                   CondRHSConst->getAPIntValue() ==
22473                       (-OpRHSConst->getAPIntValue() - 1))
22474                 return DAG.getNode(
22475                     X86ISD::SUBUS, DL, VT, OpLHS,
22476                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22477
22478           // Another special case: If C was a sign bit, the sub has been
22479           // canonicalized into a xor.
22480           // FIXME: Would it be better to use computeKnownBits to determine
22481           //        whether it's safe to decanonicalize the xor?
22482           // x s< 0 ? x^C : 0 --> subus x, C
22483           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22484               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22485               OpRHSConst->getAPIntValue().isSignBit())
22486             // Note that we have to rebuild the RHS constant here to ensure we
22487             // don't rely on particular values of undef lanes.
22488             return DAG.getNode(
22489                 X86ISD::SUBUS, DL, VT, OpLHS,
22490                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22491         }
22492     }
22493   }
22494
22495   // Try to match a min/max vector operation.
22496   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22497     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22498     unsigned Opc = ret.first;
22499     bool NeedSplit = ret.second;
22500
22501     if (Opc && NeedSplit) {
22502       unsigned NumElems = VT.getVectorNumElements();
22503       // Extract the LHS vectors
22504       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22505       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22506
22507       // Extract the RHS vectors
22508       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22509       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22510
22511       // Create min/max for each subvector
22512       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22513       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22514
22515       // Merge the result
22516       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22517     } else if (Opc)
22518       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22519   }
22520
22521   // Simplify vector selection if condition value type matches vselect
22522   // operand type
22523   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22524     assert(Cond.getValueType().isVector() &&
22525            "vector select expects a vector selector!");
22526
22527     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22528     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22529
22530     // Try invert the condition if true value is not all 1s and false value
22531     // is not all 0s.
22532     if (!TValIsAllOnes && !FValIsAllZeros &&
22533         // Check if the selector will be produced by CMPP*/PCMP*
22534         Cond.getOpcode() == ISD::SETCC &&
22535         // Check if SETCC has already been promoted
22536         TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT) ==
22537             CondVT) {
22538       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22539       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22540
22541       if (TValIsAllZeros || FValIsAllOnes) {
22542         SDValue CC = Cond.getOperand(2);
22543         ISD::CondCode NewCC =
22544           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22545                                Cond.getOperand(0).getValueType().isInteger());
22546         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22547         std::swap(LHS, RHS);
22548         TValIsAllOnes = FValIsAllOnes;
22549         FValIsAllZeros = TValIsAllZeros;
22550       }
22551     }
22552
22553     if (TValIsAllOnes || FValIsAllZeros) {
22554       SDValue Ret;
22555
22556       if (TValIsAllOnes && FValIsAllZeros)
22557         Ret = Cond;
22558       else if (TValIsAllOnes)
22559         Ret =
22560             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22561       else if (FValIsAllZeros)
22562         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22563                           DAG.getBitcast(CondVT, LHS));
22564
22565       return DAG.getBitcast(VT, Ret);
22566     }
22567   }
22568
22569   // We should generate an X86ISD::BLENDI from a vselect if its argument
22570   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22571   // constants. This specific pattern gets generated when we split a
22572   // selector for a 512 bit vector in a machine without AVX512 (but with
22573   // 256-bit vectors), during legalization:
22574   //
22575   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22576   //
22577   // Iff we find this pattern and the build_vectors are built from
22578   // constants, we translate the vselect into a shuffle_vector that we
22579   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22580   if ((N->getOpcode() == ISD::VSELECT ||
22581        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22582       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22583     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22584     if (Shuffle.getNode())
22585       return Shuffle;
22586   }
22587
22588   // If this is a *dynamic* select (non-constant condition) and we can match
22589   // this node with one of the variable blend instructions, restructure the
22590   // condition so that the blends can use the high bit of each element and use
22591   // SimplifyDemandedBits to simplify the condition operand.
22592   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22593       !DCI.isBeforeLegalize() &&
22594       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22595     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22596
22597     // Don't optimize vector selects that map to mask-registers.
22598     if (BitWidth == 1)
22599       return SDValue();
22600
22601     // We can only handle the cases where VSELECT is directly legal on the
22602     // subtarget. We custom lower VSELECT nodes with constant conditions and
22603     // this makes it hard to see whether a dynamic VSELECT will correctly
22604     // lower, so we both check the operation's status and explicitly handle the
22605     // cases where a *dynamic* blend will fail even though a constant-condition
22606     // blend could be custom lowered.
22607     // FIXME: We should find a better way to handle this class of problems.
22608     // Potentially, we should combine constant-condition vselect nodes
22609     // pre-legalization into shuffles and not mark as many types as custom
22610     // lowered.
22611     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22612       return SDValue();
22613     // FIXME: We don't support i16-element blends currently. We could and
22614     // should support them by making *all* the bits in the condition be set
22615     // rather than just the high bit and using an i8-element blend.
22616     if (VT.getScalarType() == MVT::i16)
22617       return SDValue();
22618     // Dynamic blending was only available from SSE4.1 onward.
22619     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22620       return SDValue();
22621     // Byte blends are only available in AVX2
22622     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22623         !Subtarget->hasAVX2())
22624       return SDValue();
22625
22626     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22627     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22628
22629     APInt KnownZero, KnownOne;
22630     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22631                                           DCI.isBeforeLegalizeOps());
22632     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22633         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22634                                  TLO)) {
22635       // If we changed the computation somewhere in the DAG, this change
22636       // will affect all users of Cond.
22637       // Make sure it is fine and update all the nodes so that we do not
22638       // use the generic VSELECT anymore. Otherwise, we may perform
22639       // wrong optimizations as we messed up with the actual expectation
22640       // for the vector boolean values.
22641       if (Cond != TLO.Old) {
22642         // Check all uses of that condition operand to check whether it will be
22643         // consumed by non-BLEND instructions, which may depend on all bits are
22644         // set properly.
22645         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22646              I != E; ++I)
22647           if (I->getOpcode() != ISD::VSELECT)
22648             // TODO: Add other opcodes eventually lowered into BLEND.
22649             return SDValue();
22650
22651         // Update all the users of the condition, before committing the change,
22652         // so that the VSELECT optimizations that expect the correct vector
22653         // boolean value will not be triggered.
22654         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22655              I != E; ++I)
22656           DAG.ReplaceAllUsesOfValueWith(
22657               SDValue(*I, 0),
22658               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22659                           Cond, I->getOperand(1), I->getOperand(2)));
22660         DCI.CommitTargetLoweringOpt(TLO);
22661         return SDValue();
22662       }
22663       // At this point, only Cond is changed. Change the condition
22664       // just for N to keep the opportunity to optimize all other
22665       // users their own way.
22666       DAG.ReplaceAllUsesOfValueWith(
22667           SDValue(N, 0),
22668           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22669                       TLO.New, N->getOperand(1), N->getOperand(2)));
22670       return SDValue();
22671     }
22672   }
22673
22674   return SDValue();
22675 }
22676
22677 // Check whether a boolean test is testing a boolean value generated by
22678 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22679 // code.
22680 //
22681 // Simplify the following patterns:
22682 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22683 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22684 // to (Op EFLAGS Cond)
22685 //
22686 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22687 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22688 // to (Op EFLAGS !Cond)
22689 //
22690 // where Op could be BRCOND or CMOV.
22691 //
22692 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22693   // Quit if not CMP and SUB with its value result used.
22694   if (Cmp.getOpcode() != X86ISD::CMP &&
22695       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22696       return SDValue();
22697
22698   // Quit if not used as a boolean value.
22699   if (CC != X86::COND_E && CC != X86::COND_NE)
22700     return SDValue();
22701
22702   // Check CMP operands. One of them should be 0 or 1 and the other should be
22703   // an SetCC or extended from it.
22704   SDValue Op1 = Cmp.getOperand(0);
22705   SDValue Op2 = Cmp.getOperand(1);
22706
22707   SDValue SetCC;
22708   const ConstantSDNode* C = nullptr;
22709   bool needOppositeCond = (CC == X86::COND_E);
22710   bool checkAgainstTrue = false; // Is it a comparison against 1?
22711
22712   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22713     SetCC = Op2;
22714   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22715     SetCC = Op1;
22716   else // Quit if all operands are not constants.
22717     return SDValue();
22718
22719   if (C->getZExtValue() == 1) {
22720     needOppositeCond = !needOppositeCond;
22721     checkAgainstTrue = true;
22722   } else if (C->getZExtValue() != 0)
22723     // Quit if the constant is neither 0 or 1.
22724     return SDValue();
22725
22726   bool truncatedToBoolWithAnd = false;
22727   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22728   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22729          SetCC.getOpcode() == ISD::TRUNCATE ||
22730          SetCC.getOpcode() == ISD::AND) {
22731     if (SetCC.getOpcode() == ISD::AND) {
22732       int OpIdx = -1;
22733       ConstantSDNode *CS;
22734       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22735           CS->getZExtValue() == 1)
22736         OpIdx = 1;
22737       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22738           CS->getZExtValue() == 1)
22739         OpIdx = 0;
22740       if (OpIdx == -1)
22741         break;
22742       SetCC = SetCC.getOperand(OpIdx);
22743       truncatedToBoolWithAnd = true;
22744     } else
22745       SetCC = SetCC.getOperand(0);
22746   }
22747
22748   switch (SetCC.getOpcode()) {
22749   case X86ISD::SETCC_CARRY:
22750     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22751     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22752     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22753     // truncated to i1 using 'and'.
22754     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22755       break;
22756     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22757            "Invalid use of SETCC_CARRY!");
22758     // FALL THROUGH
22759   case X86ISD::SETCC:
22760     // Set the condition code or opposite one if necessary.
22761     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22762     if (needOppositeCond)
22763       CC = X86::GetOppositeBranchCondition(CC);
22764     return SetCC.getOperand(1);
22765   case X86ISD::CMOV: {
22766     // Check whether false/true value has canonical one, i.e. 0 or 1.
22767     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22768     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22769     // Quit if true value is not a constant.
22770     if (!TVal)
22771       return SDValue();
22772     // Quit if false value is not a constant.
22773     if (!FVal) {
22774       SDValue Op = SetCC.getOperand(0);
22775       // Skip 'zext' or 'trunc' node.
22776       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22777           Op.getOpcode() == ISD::TRUNCATE)
22778         Op = Op.getOperand(0);
22779       // A special case for rdrand/rdseed, where 0 is set if false cond is
22780       // found.
22781       if ((Op.getOpcode() != X86ISD::RDRAND &&
22782            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22783         return SDValue();
22784     }
22785     // Quit if false value is not the constant 0 or 1.
22786     bool FValIsFalse = true;
22787     if (FVal && FVal->getZExtValue() != 0) {
22788       if (FVal->getZExtValue() != 1)
22789         return SDValue();
22790       // If FVal is 1, opposite cond is needed.
22791       needOppositeCond = !needOppositeCond;
22792       FValIsFalse = false;
22793     }
22794     // Quit if TVal is not the constant opposite of FVal.
22795     if (FValIsFalse && TVal->getZExtValue() != 1)
22796       return SDValue();
22797     if (!FValIsFalse && TVal->getZExtValue() != 0)
22798       return SDValue();
22799     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22800     if (needOppositeCond)
22801       CC = X86::GetOppositeBranchCondition(CC);
22802     return SetCC.getOperand(3);
22803   }
22804   }
22805
22806   return SDValue();
22807 }
22808
22809 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22810 /// Match:
22811 ///   (X86or (X86setcc) (X86setcc))
22812 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22813 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22814                                            X86::CondCode &CC1, SDValue &Flags,
22815                                            bool &isAnd) {
22816   if (Cond->getOpcode() == X86ISD::CMP) {
22817     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22818     if (!CondOp1C || !CondOp1C->isNullValue())
22819       return false;
22820
22821     Cond = Cond->getOperand(0);
22822   }
22823
22824   isAnd = false;
22825
22826   SDValue SetCC0, SetCC1;
22827   switch (Cond->getOpcode()) {
22828   default: return false;
22829   case ISD::AND:
22830   case X86ISD::AND:
22831     isAnd = true;
22832     // fallthru
22833   case ISD::OR:
22834   case X86ISD::OR:
22835     SetCC0 = Cond->getOperand(0);
22836     SetCC1 = Cond->getOperand(1);
22837     break;
22838   };
22839
22840   // Make sure we have SETCC nodes, using the same flags value.
22841   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22842       SetCC1.getOpcode() != X86ISD::SETCC ||
22843       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22844     return false;
22845
22846   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22847   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22848   Flags = SetCC0->getOperand(1);
22849   return true;
22850 }
22851
22852 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22853 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22854                                   TargetLowering::DAGCombinerInfo &DCI,
22855                                   const X86Subtarget *Subtarget) {
22856   SDLoc DL(N);
22857
22858   // If the flag operand isn't dead, don't touch this CMOV.
22859   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22860     return SDValue();
22861
22862   SDValue FalseOp = N->getOperand(0);
22863   SDValue TrueOp = N->getOperand(1);
22864   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22865   SDValue Cond = N->getOperand(3);
22866
22867   if (CC == X86::COND_E || CC == X86::COND_NE) {
22868     switch (Cond.getOpcode()) {
22869     default: break;
22870     case X86ISD::BSR:
22871     case X86ISD::BSF:
22872       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22873       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22874         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22875     }
22876   }
22877
22878   SDValue Flags;
22879
22880   Flags = checkBoolTestSetCCCombine(Cond, CC);
22881   if (Flags.getNode() &&
22882       // Extra check as FCMOV only supports a subset of X86 cond.
22883       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22884     SDValue Ops[] = { FalseOp, TrueOp,
22885                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22886     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22887   }
22888
22889   // If this is a select between two integer constants, try to do some
22890   // optimizations.  Note that the operands are ordered the opposite of SELECT
22891   // operands.
22892   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22893     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22894       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22895       // larger than FalseC (the false value).
22896       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22897         CC = X86::GetOppositeBranchCondition(CC);
22898         std::swap(TrueC, FalseC);
22899         std::swap(TrueOp, FalseOp);
22900       }
22901
22902       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22903       // This is efficient for any integer data type (including i8/i16) and
22904       // shift amount.
22905       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22906         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22907                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22908
22909         // Zero extend the condition if needed.
22910         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22911
22912         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22913         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22914                            DAG.getConstant(ShAmt, DL, MVT::i8));
22915         if (N->getNumValues() == 2)  // Dead flag value?
22916           return DCI.CombineTo(N, Cond, SDValue());
22917         return Cond;
22918       }
22919
22920       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22921       // for any integer data type, including i8/i16.
22922       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22923         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22924                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22925
22926         // Zero extend the condition if needed.
22927         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22928                            FalseC->getValueType(0), Cond);
22929         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22930                            SDValue(FalseC, 0));
22931
22932         if (N->getNumValues() == 2)  // Dead flag value?
22933           return DCI.CombineTo(N, Cond, SDValue());
22934         return Cond;
22935       }
22936
22937       // Optimize cases that will turn into an LEA instruction.  This requires
22938       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22939       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22940         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22941         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22942
22943         bool isFastMultiplier = false;
22944         if (Diff < 10) {
22945           switch ((unsigned char)Diff) {
22946           default: break;
22947           case 1:  // result = add base, cond
22948           case 2:  // result = lea base(    , cond*2)
22949           case 3:  // result = lea base(cond, cond*2)
22950           case 4:  // result = lea base(    , cond*4)
22951           case 5:  // result = lea base(cond, cond*4)
22952           case 8:  // result = lea base(    , cond*8)
22953           case 9:  // result = lea base(cond, cond*8)
22954             isFastMultiplier = true;
22955             break;
22956           }
22957         }
22958
22959         if (isFastMultiplier) {
22960           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22961           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22962                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22963           // Zero extend the condition if needed.
22964           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22965                              Cond);
22966           // Scale the condition by the difference.
22967           if (Diff != 1)
22968             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22969                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22970
22971           // Add the base if non-zero.
22972           if (FalseC->getAPIntValue() != 0)
22973             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22974                                SDValue(FalseC, 0));
22975           if (N->getNumValues() == 2)  // Dead flag value?
22976             return DCI.CombineTo(N, Cond, SDValue());
22977           return Cond;
22978         }
22979       }
22980     }
22981   }
22982
22983   // Handle these cases:
22984   //   (select (x != c), e, c) -> select (x != c), e, x),
22985   //   (select (x == c), c, e) -> select (x == c), x, e)
22986   // where the c is an integer constant, and the "select" is the combination
22987   // of CMOV and CMP.
22988   //
22989   // The rationale for this change is that the conditional-move from a constant
22990   // needs two instructions, however, conditional-move from a register needs
22991   // only one instruction.
22992   //
22993   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22994   //  some instruction-combining opportunities. This opt needs to be
22995   //  postponed as late as possible.
22996   //
22997   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22998     // the DCI.xxxx conditions are provided to postpone the optimization as
22999     // late as possible.
23000
23001     ConstantSDNode *CmpAgainst = nullptr;
23002     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
23003         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
23004         !isa<ConstantSDNode>(Cond.getOperand(0))) {
23005
23006       if (CC == X86::COND_NE &&
23007           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
23008         CC = X86::GetOppositeBranchCondition(CC);
23009         std::swap(TrueOp, FalseOp);
23010       }
23011
23012       if (CC == X86::COND_E &&
23013           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
23014         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
23015                           DAG.getConstant(CC, DL, MVT::i8), Cond };
23016         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
23017       }
23018     }
23019   }
23020
23021   // Fold and/or of setcc's to double CMOV:
23022   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
23023   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
23024   //
23025   // This combine lets us generate:
23026   //   cmovcc1 (jcc1 if we don't have CMOV)
23027   //   cmovcc2 (same)
23028   // instead of:
23029   //   setcc1
23030   //   setcc2
23031   //   and/or
23032   //   cmovne (jne if we don't have CMOV)
23033   // When we can't use the CMOV instruction, it might increase branch
23034   // mispredicts.
23035   // When we can use CMOV, or when there is no mispredict, this improves
23036   // throughput and reduces register pressure.
23037   //
23038   if (CC == X86::COND_NE) {
23039     SDValue Flags;
23040     X86::CondCode CC0, CC1;
23041     bool isAndSetCC;
23042     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
23043       if (isAndSetCC) {
23044         std::swap(FalseOp, TrueOp);
23045         CC0 = X86::GetOppositeBranchCondition(CC0);
23046         CC1 = X86::GetOppositeBranchCondition(CC1);
23047       }
23048
23049       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
23050         Flags};
23051       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
23052       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
23053       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
23054       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
23055       return CMOV;
23056     }
23057   }
23058
23059   return SDValue();
23060 }
23061
23062 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
23063                                                 const X86Subtarget *Subtarget) {
23064   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
23065   switch (IntNo) {
23066   default: return SDValue();
23067   // SSE/AVX/AVX2 blend intrinsics.
23068   case Intrinsic::x86_avx2_pblendvb:
23069     // Don't try to simplify this intrinsic if we don't have AVX2.
23070     if (!Subtarget->hasAVX2())
23071       return SDValue();
23072     // FALL-THROUGH
23073   case Intrinsic::x86_avx_blendv_pd_256:
23074   case Intrinsic::x86_avx_blendv_ps_256:
23075     // Don't try to simplify this intrinsic if we don't have AVX.
23076     if (!Subtarget->hasAVX())
23077       return SDValue();
23078     // FALL-THROUGH
23079   case Intrinsic::x86_sse41_blendvps:
23080   case Intrinsic::x86_sse41_blendvpd:
23081   case Intrinsic::x86_sse41_pblendvb: {
23082     SDValue Op0 = N->getOperand(1);
23083     SDValue Op1 = N->getOperand(2);
23084     SDValue Mask = N->getOperand(3);
23085
23086     // Don't try to simplify this intrinsic if we don't have SSE4.1.
23087     if (!Subtarget->hasSSE41())
23088       return SDValue();
23089
23090     // fold (blend A, A, Mask) -> A
23091     if (Op0 == Op1)
23092       return Op0;
23093     // fold (blend A, B, allZeros) -> A
23094     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
23095       return Op0;
23096     // fold (blend A, B, allOnes) -> B
23097     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
23098       return Op1;
23099
23100     // Simplify the case where the mask is a constant i32 value.
23101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
23102       if (C->isNullValue())
23103         return Op0;
23104       if (C->isAllOnesValue())
23105         return Op1;
23106     }
23107
23108     return SDValue();
23109   }
23110
23111   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
23112   case Intrinsic::x86_sse2_psrai_w:
23113   case Intrinsic::x86_sse2_psrai_d:
23114   case Intrinsic::x86_avx2_psrai_w:
23115   case Intrinsic::x86_avx2_psrai_d:
23116   case Intrinsic::x86_sse2_psra_w:
23117   case Intrinsic::x86_sse2_psra_d:
23118   case Intrinsic::x86_avx2_psra_w:
23119   case Intrinsic::x86_avx2_psra_d: {
23120     SDValue Op0 = N->getOperand(1);
23121     SDValue Op1 = N->getOperand(2);
23122     EVT VT = Op0.getValueType();
23123     assert(VT.isVector() && "Expected a vector type!");
23124
23125     if (isa<BuildVectorSDNode>(Op1))
23126       Op1 = Op1.getOperand(0);
23127
23128     if (!isa<ConstantSDNode>(Op1))
23129       return SDValue();
23130
23131     EVT SVT = VT.getVectorElementType();
23132     unsigned SVTBits = SVT.getSizeInBits();
23133
23134     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
23135     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
23136     uint64_t ShAmt = C.getZExtValue();
23137
23138     // Don't try to convert this shift into a ISD::SRA if the shift
23139     // count is bigger than or equal to the element size.
23140     if (ShAmt >= SVTBits)
23141       return SDValue();
23142
23143     // Trivial case: if the shift count is zero, then fold this
23144     // into the first operand.
23145     if (ShAmt == 0)
23146       return Op0;
23147
23148     // Replace this packed shift intrinsic with a target independent
23149     // shift dag node.
23150     SDLoc DL(N);
23151     SDValue Splat = DAG.getConstant(C, DL, VT);
23152     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
23153   }
23154   }
23155 }
23156
23157 /// PerformMulCombine - Optimize a single multiply with constant into two
23158 /// in order to implement it with two cheaper instructions, e.g.
23159 /// LEA + SHL, LEA + LEA.
23160 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
23161                                  TargetLowering::DAGCombinerInfo &DCI) {
23162   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
23163     return SDValue();
23164
23165   EVT VT = N->getValueType(0);
23166   if (VT != MVT::i64 && VT != MVT::i32)
23167     return SDValue();
23168
23169   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
23170   if (!C)
23171     return SDValue();
23172   uint64_t MulAmt = C->getZExtValue();
23173   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
23174     return SDValue();
23175
23176   uint64_t MulAmt1 = 0;
23177   uint64_t MulAmt2 = 0;
23178   if ((MulAmt % 9) == 0) {
23179     MulAmt1 = 9;
23180     MulAmt2 = MulAmt / 9;
23181   } else if ((MulAmt % 5) == 0) {
23182     MulAmt1 = 5;
23183     MulAmt2 = MulAmt / 5;
23184   } else if ((MulAmt % 3) == 0) {
23185     MulAmt1 = 3;
23186     MulAmt2 = MulAmt / 3;
23187   }
23188   if (MulAmt2 &&
23189       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
23190     SDLoc DL(N);
23191
23192     if (isPowerOf2_64(MulAmt2) &&
23193         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
23194       // If second multiplifer is pow2, issue it first. We want the multiply by
23195       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
23196       // is an add.
23197       std::swap(MulAmt1, MulAmt2);
23198
23199     SDValue NewMul;
23200     if (isPowerOf2_64(MulAmt1))
23201       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
23202                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
23203     else
23204       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
23205                            DAG.getConstant(MulAmt1, DL, VT));
23206
23207     if (isPowerOf2_64(MulAmt2))
23208       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
23209                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
23210     else
23211       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
23212                            DAG.getConstant(MulAmt2, DL, VT));
23213
23214     // Do not add new nodes to DAG combiner worklist.
23215     DCI.CombineTo(N, NewMul, false);
23216   }
23217   return SDValue();
23218 }
23219
23220 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
23221   SDValue N0 = N->getOperand(0);
23222   SDValue N1 = N->getOperand(1);
23223   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
23224   EVT VT = N0.getValueType();
23225
23226   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
23227   // since the result of setcc_c is all zero's or all ones.
23228   if (VT.isInteger() && !VT.isVector() &&
23229       N1C && N0.getOpcode() == ISD::AND &&
23230       N0.getOperand(1).getOpcode() == ISD::Constant) {
23231     SDValue N00 = N0.getOperand(0);
23232     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
23233         ((N00.getOpcode() == ISD::ANY_EXTEND ||
23234           N00.getOpcode() == ISD::ZERO_EXTEND) &&
23235          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
23236       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
23237       APInt ShAmt = N1C->getAPIntValue();
23238       Mask = Mask.shl(ShAmt);
23239       if (Mask != 0) {
23240         SDLoc DL(N);
23241         return DAG.getNode(ISD::AND, DL, VT,
23242                            N00, DAG.getConstant(Mask, DL, VT));
23243       }
23244     }
23245   }
23246
23247   // Hardware support for vector shifts is sparse which makes us scalarize the
23248   // vector operations in many cases. Also, on sandybridge ADD is faster than
23249   // shl.
23250   // (shl V, 1) -> add V,V
23251   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
23252     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
23253       assert(N0.getValueType().isVector() && "Invalid vector shift type");
23254       // We shift all of the values by one. In many cases we do not have
23255       // hardware support for this operation. This is better expressed as an ADD
23256       // of two values.
23257       if (N1SplatC->getAPIntValue() == 1)
23258         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
23259     }
23260
23261   return SDValue();
23262 }
23263
23264 /// \brief Returns a vector of 0s if the node in input is a vector logical
23265 /// shift by a constant amount which is known to be bigger than or equal
23266 /// to the vector element size in bits.
23267 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
23268                                       const X86Subtarget *Subtarget) {
23269   EVT VT = N->getValueType(0);
23270
23271   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
23272       (!Subtarget->hasInt256() ||
23273        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
23274     return SDValue();
23275
23276   SDValue Amt = N->getOperand(1);
23277   SDLoc DL(N);
23278   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
23279     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
23280       APInt ShiftAmt = AmtSplat->getAPIntValue();
23281       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
23282
23283       // SSE2/AVX2 logical shifts always return a vector of 0s
23284       // if the shift amount is bigger than or equal to
23285       // the element size. The constant shift amount will be
23286       // encoded as a 8-bit immediate.
23287       if (ShiftAmt.trunc(8).uge(MaxAmount))
23288         return getZeroVector(VT, Subtarget, DAG, DL);
23289     }
23290
23291   return SDValue();
23292 }
23293
23294 /// PerformShiftCombine - Combine shifts.
23295 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
23296                                    TargetLowering::DAGCombinerInfo &DCI,
23297                                    const X86Subtarget *Subtarget) {
23298   if (N->getOpcode() == ISD::SHL)
23299     if (SDValue V = PerformSHLCombine(N, DAG))
23300       return V;
23301
23302   // Try to fold this logical shift into a zero vector.
23303   if (N->getOpcode() != ISD::SRA)
23304     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
23305       return V;
23306
23307   return SDValue();
23308 }
23309
23310 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
23311 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
23312 // and friends.  Likewise for OR -> CMPNEQSS.
23313 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
23314                             TargetLowering::DAGCombinerInfo &DCI,
23315                             const X86Subtarget *Subtarget) {
23316   unsigned opcode;
23317
23318   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
23319   // we're requiring SSE2 for both.
23320   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
23321     SDValue N0 = N->getOperand(0);
23322     SDValue N1 = N->getOperand(1);
23323     SDValue CMP0 = N0->getOperand(1);
23324     SDValue CMP1 = N1->getOperand(1);
23325     SDLoc DL(N);
23326
23327     // The SETCCs should both refer to the same CMP.
23328     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
23329       return SDValue();
23330
23331     SDValue CMP00 = CMP0->getOperand(0);
23332     SDValue CMP01 = CMP0->getOperand(1);
23333     EVT     VT    = CMP00.getValueType();
23334
23335     if (VT == MVT::f32 || VT == MVT::f64) {
23336       bool ExpectingFlags = false;
23337       // Check for any users that want flags:
23338       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
23339            !ExpectingFlags && UI != UE; ++UI)
23340         switch (UI->getOpcode()) {
23341         default:
23342         case ISD::BR_CC:
23343         case ISD::BRCOND:
23344         case ISD::SELECT:
23345           ExpectingFlags = true;
23346           break;
23347         case ISD::CopyToReg:
23348         case ISD::SIGN_EXTEND:
23349         case ISD::ZERO_EXTEND:
23350         case ISD::ANY_EXTEND:
23351           break;
23352         }
23353
23354       if (!ExpectingFlags) {
23355         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
23356         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
23357
23358         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
23359           X86::CondCode tmp = cc0;
23360           cc0 = cc1;
23361           cc1 = tmp;
23362         }
23363
23364         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
23365             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
23366           // FIXME: need symbolic constants for these magic numbers.
23367           // See X86ATTInstPrinter.cpp:printSSECC().
23368           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
23369           if (Subtarget->hasAVX512()) {
23370             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
23371                                          CMP01,
23372                                          DAG.getConstant(x86cc, DL, MVT::i8));
23373             if (N->getValueType(0) != MVT::i1)
23374               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23375                                  FSetCC);
23376             return FSetCC;
23377           }
23378           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23379                                               CMP00.getValueType(), CMP00, CMP01,
23380                                               DAG.getConstant(x86cc, DL,
23381                                                               MVT::i8));
23382
23383           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23384           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23385
23386           if (is64BitFP && !Subtarget->is64Bit()) {
23387             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23388             // 64-bit integer, since that's not a legal type. Since
23389             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23390             // bits, but can do this little dance to extract the lowest 32 bits
23391             // and work with those going forward.
23392             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23393                                            OnesOrZeroesF);
23394             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23395             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23396                                         Vector32, DAG.getIntPtrConstant(0, DL));
23397             IntVT = MVT::i32;
23398           }
23399
23400           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23401           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23402                                       DAG.getConstant(1, DL, IntVT));
23403           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23404                                               ANDed);
23405           return OneBitOfTruth;
23406         }
23407       }
23408     }
23409   }
23410   return SDValue();
23411 }
23412
23413 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23414 /// so it can be folded inside ANDNP.
23415 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23416   EVT VT = N->getValueType(0);
23417
23418   // Match direct AllOnes for 128 and 256-bit vectors
23419   if (ISD::isBuildVectorAllOnes(N))
23420     return true;
23421
23422   // Look through a bit convert.
23423   if (N->getOpcode() == ISD::BITCAST)
23424     N = N->getOperand(0).getNode();
23425
23426   // Sometimes the operand may come from a insert_subvector building a 256-bit
23427   // allones vector
23428   if (VT.is256BitVector() &&
23429       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23430     SDValue V1 = N->getOperand(0);
23431     SDValue V2 = N->getOperand(1);
23432
23433     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23434         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23435         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23436         ISD::isBuildVectorAllOnes(V2.getNode()))
23437       return true;
23438   }
23439
23440   return false;
23441 }
23442
23443 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23444 // register. In most cases we actually compare or select YMM-sized registers
23445 // and mixing the two types creates horrible code. This method optimizes
23446 // some of the transition sequences.
23447 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23448                                  TargetLowering::DAGCombinerInfo &DCI,
23449                                  const X86Subtarget *Subtarget) {
23450   EVT VT = N->getValueType(0);
23451   if (!VT.is256BitVector())
23452     return SDValue();
23453
23454   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23455           N->getOpcode() == ISD::ZERO_EXTEND ||
23456           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23457
23458   SDValue Narrow = N->getOperand(0);
23459   EVT NarrowVT = Narrow->getValueType(0);
23460   if (!NarrowVT.is128BitVector())
23461     return SDValue();
23462
23463   if (Narrow->getOpcode() != ISD::XOR &&
23464       Narrow->getOpcode() != ISD::AND &&
23465       Narrow->getOpcode() != ISD::OR)
23466     return SDValue();
23467
23468   SDValue N0  = Narrow->getOperand(0);
23469   SDValue N1  = Narrow->getOperand(1);
23470   SDLoc DL(Narrow);
23471
23472   // The Left side has to be a trunc.
23473   if (N0.getOpcode() != ISD::TRUNCATE)
23474     return SDValue();
23475
23476   // The type of the truncated inputs.
23477   EVT WideVT = N0->getOperand(0)->getValueType(0);
23478   if (WideVT != VT)
23479     return SDValue();
23480
23481   // The right side has to be a 'trunc' or a constant vector.
23482   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23483   ConstantSDNode *RHSConstSplat = nullptr;
23484   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23485     RHSConstSplat = RHSBV->getConstantSplatNode();
23486   if (!RHSTrunc && !RHSConstSplat)
23487     return SDValue();
23488
23489   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23490
23491   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23492     return SDValue();
23493
23494   // Set N0 and N1 to hold the inputs to the new wide operation.
23495   N0 = N0->getOperand(0);
23496   if (RHSConstSplat) {
23497     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23498                      SDValue(RHSConstSplat, 0));
23499     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23500     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23501   } else if (RHSTrunc) {
23502     N1 = N1->getOperand(0);
23503   }
23504
23505   // Generate the wide operation.
23506   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23507   unsigned Opcode = N->getOpcode();
23508   switch (Opcode) {
23509   case ISD::ANY_EXTEND:
23510     return Op;
23511   case ISD::ZERO_EXTEND: {
23512     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23513     APInt Mask = APInt::getAllOnesValue(InBits);
23514     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23515     return DAG.getNode(ISD::AND, DL, VT,
23516                        Op, DAG.getConstant(Mask, DL, VT));
23517   }
23518   case ISD::SIGN_EXTEND:
23519     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23520                        Op, DAG.getValueType(NarrowVT));
23521   default:
23522     llvm_unreachable("Unexpected opcode");
23523   }
23524 }
23525
23526 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23527                                  TargetLowering::DAGCombinerInfo &DCI,
23528                                  const X86Subtarget *Subtarget) {
23529   SDValue N0 = N->getOperand(0);
23530   SDValue N1 = N->getOperand(1);
23531   SDLoc DL(N);
23532
23533   // A vector zext_in_reg may be represented as a shuffle,
23534   // feeding into a bitcast (this represents anyext) feeding into
23535   // an and with a mask.
23536   // We'd like to try to combine that into a shuffle with zero
23537   // plus a bitcast, removing the and.
23538   if (N0.getOpcode() != ISD::BITCAST ||
23539       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23540     return SDValue();
23541
23542   // The other side of the AND should be a splat of 2^C, where C
23543   // is the number of bits in the source type.
23544   if (N1.getOpcode() == ISD::BITCAST)
23545     N1 = N1.getOperand(0);
23546   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23547     return SDValue();
23548   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23549
23550   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23551   EVT SrcType = Shuffle->getValueType(0);
23552
23553   // We expect a single-source shuffle
23554   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23555     return SDValue();
23556
23557   unsigned SrcSize = SrcType.getScalarSizeInBits();
23558
23559   APInt SplatValue, SplatUndef;
23560   unsigned SplatBitSize;
23561   bool HasAnyUndefs;
23562   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23563                                 SplatBitSize, HasAnyUndefs))
23564     return SDValue();
23565
23566   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23567   // Make sure the splat matches the mask we expect
23568   if (SplatBitSize > ResSize ||
23569       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23570     return SDValue();
23571
23572   // Make sure the input and output size make sense
23573   if (SrcSize >= ResSize || ResSize % SrcSize)
23574     return SDValue();
23575
23576   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23577   // The number of u's between each two values depends on the ratio between
23578   // the source and dest type.
23579   unsigned ZextRatio = ResSize / SrcSize;
23580   bool IsZext = true;
23581   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23582     if (i % ZextRatio) {
23583       if (Shuffle->getMaskElt(i) > 0) {
23584         // Expected undef
23585         IsZext = false;
23586         break;
23587       }
23588     } else {
23589       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23590         // Expected element number
23591         IsZext = false;
23592         break;
23593       }
23594     }
23595   }
23596
23597   if (!IsZext)
23598     return SDValue();
23599
23600   // Ok, perform the transformation - replace the shuffle with
23601   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23602   // (instead of undef) where the k elements come from the zero vector.
23603   SmallVector<int, 8> Mask;
23604   unsigned NumElems = SrcType.getVectorNumElements();
23605   for (unsigned i = 0; i < NumElems; ++i)
23606     if (i % ZextRatio)
23607       Mask.push_back(NumElems);
23608     else
23609       Mask.push_back(i / ZextRatio);
23610
23611   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23612     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23613   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23614 }
23615
23616 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23617                                  TargetLowering::DAGCombinerInfo &DCI,
23618                                  const X86Subtarget *Subtarget) {
23619   if (DCI.isBeforeLegalizeOps())
23620     return SDValue();
23621
23622   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23623     return Zext;
23624
23625   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23626     return R;
23627
23628   EVT VT = N->getValueType(0);
23629   SDValue N0 = N->getOperand(0);
23630   SDValue N1 = N->getOperand(1);
23631   SDLoc DL(N);
23632
23633   // Create BEXTR instructions
23634   // BEXTR is ((X >> imm) & (2**size-1))
23635   if (VT == MVT::i32 || VT == MVT::i64) {
23636     // Check for BEXTR.
23637     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23638         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23639       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23640       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23641       if (MaskNode && ShiftNode) {
23642         uint64_t Mask = MaskNode->getZExtValue();
23643         uint64_t Shift = ShiftNode->getZExtValue();
23644         if (isMask_64(Mask)) {
23645           uint64_t MaskSize = countPopulation(Mask);
23646           if (Shift + MaskSize <= VT.getSizeInBits())
23647             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23648                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23649                                                VT));
23650         }
23651       }
23652     } // BEXTR
23653
23654     return SDValue();
23655   }
23656
23657   // Want to form ANDNP nodes:
23658   // 1) In the hopes of then easily combining them with OR and AND nodes
23659   //    to form PBLEND/PSIGN.
23660   // 2) To match ANDN packed intrinsics
23661   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23662     return SDValue();
23663
23664   // Check LHS for vnot
23665   if (N0.getOpcode() == ISD::XOR &&
23666       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23667       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23668     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23669
23670   // Check RHS for vnot
23671   if (N1.getOpcode() == ISD::XOR &&
23672       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23673       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23674     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23675
23676   return SDValue();
23677 }
23678
23679 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23680                                 TargetLowering::DAGCombinerInfo &DCI,
23681                                 const X86Subtarget *Subtarget) {
23682   if (DCI.isBeforeLegalizeOps())
23683     return SDValue();
23684
23685   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23686     return R;
23687
23688   SDValue N0 = N->getOperand(0);
23689   SDValue N1 = N->getOperand(1);
23690   EVT VT = N->getValueType(0);
23691
23692   // look for psign/blend
23693   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23694     if (!Subtarget->hasSSSE3() ||
23695         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23696       return SDValue();
23697
23698     // Canonicalize pandn to RHS
23699     if (N0.getOpcode() == X86ISD::ANDNP)
23700       std::swap(N0, N1);
23701     // or (and (m, y), (pandn m, x))
23702     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23703       SDValue Mask = N1.getOperand(0);
23704       SDValue X    = N1.getOperand(1);
23705       SDValue Y;
23706       if (N0.getOperand(0) == Mask)
23707         Y = N0.getOperand(1);
23708       if (N0.getOperand(1) == Mask)
23709         Y = N0.getOperand(0);
23710
23711       // Check to see if the mask appeared in both the AND and ANDNP and
23712       if (!Y.getNode())
23713         return SDValue();
23714
23715       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23716       // Look through mask bitcast.
23717       if (Mask.getOpcode() == ISD::BITCAST)
23718         Mask = Mask.getOperand(0);
23719       if (X.getOpcode() == ISD::BITCAST)
23720         X = X.getOperand(0);
23721       if (Y.getOpcode() == ISD::BITCAST)
23722         Y = Y.getOperand(0);
23723
23724       EVT MaskVT = Mask.getValueType();
23725
23726       // Validate that the Mask operand is a vector sra node.
23727       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23728       // there is no psrai.b
23729       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23730       unsigned SraAmt = ~0;
23731       if (Mask.getOpcode() == ISD::SRA) {
23732         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23733           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23734             SraAmt = AmtConst->getZExtValue();
23735       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23736         SDValue SraC = Mask.getOperand(1);
23737         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23738       }
23739       if ((SraAmt + 1) != EltBits)
23740         return SDValue();
23741
23742       SDLoc DL(N);
23743
23744       // Now we know we at least have a plendvb with the mask val.  See if
23745       // we can form a psignb/w/d.
23746       // psign = x.type == y.type == mask.type && y = sub(0, x);
23747       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23748           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23749           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23750         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23751                "Unsupported VT for PSIGN");
23752         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23753         return DAG.getBitcast(VT, Mask);
23754       }
23755       // PBLENDVB only available on SSE 4.1
23756       if (!Subtarget->hasSSE41())
23757         return SDValue();
23758
23759       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23760
23761       X = DAG.getBitcast(BlendVT, X);
23762       Y = DAG.getBitcast(BlendVT, Y);
23763       Mask = DAG.getBitcast(BlendVT, Mask);
23764       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23765       return DAG.getBitcast(VT, Mask);
23766     }
23767   }
23768
23769   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23770     return SDValue();
23771
23772   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23773   MachineFunction &MF = DAG.getMachineFunction();
23774   bool OptForSize =
23775       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23776
23777   // SHLD/SHRD instructions have lower register pressure, but on some
23778   // platforms they have higher latency than the equivalent
23779   // series of shifts/or that would otherwise be generated.
23780   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23781   // have higher latencies and we are not optimizing for size.
23782   if (!OptForSize && Subtarget->isSHLDSlow())
23783     return SDValue();
23784
23785   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23786     std::swap(N0, N1);
23787   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23788     return SDValue();
23789   if (!N0.hasOneUse() || !N1.hasOneUse())
23790     return SDValue();
23791
23792   SDValue ShAmt0 = N0.getOperand(1);
23793   if (ShAmt0.getValueType() != MVT::i8)
23794     return SDValue();
23795   SDValue ShAmt1 = N1.getOperand(1);
23796   if (ShAmt1.getValueType() != MVT::i8)
23797     return SDValue();
23798   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23799     ShAmt0 = ShAmt0.getOperand(0);
23800   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23801     ShAmt1 = ShAmt1.getOperand(0);
23802
23803   SDLoc DL(N);
23804   unsigned Opc = X86ISD::SHLD;
23805   SDValue Op0 = N0.getOperand(0);
23806   SDValue Op1 = N1.getOperand(0);
23807   if (ShAmt0.getOpcode() == ISD::SUB) {
23808     Opc = X86ISD::SHRD;
23809     std::swap(Op0, Op1);
23810     std::swap(ShAmt0, ShAmt1);
23811   }
23812
23813   unsigned Bits = VT.getSizeInBits();
23814   if (ShAmt1.getOpcode() == ISD::SUB) {
23815     SDValue Sum = ShAmt1.getOperand(0);
23816     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23817       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23818       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23819         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23820       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23821         return DAG.getNode(Opc, DL, VT,
23822                            Op0, Op1,
23823                            DAG.getNode(ISD::TRUNCATE, DL,
23824                                        MVT::i8, ShAmt0));
23825     }
23826   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23827     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23828     if (ShAmt0C &&
23829         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23830       return DAG.getNode(Opc, DL, VT,
23831                          N0.getOperand(0), N1.getOperand(0),
23832                          DAG.getNode(ISD::TRUNCATE, DL,
23833                                        MVT::i8, ShAmt0));
23834   }
23835
23836   return SDValue();
23837 }
23838
23839 // Generate NEG and CMOV for integer abs.
23840 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23841   EVT VT = N->getValueType(0);
23842
23843   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23844   // 8-bit integer abs to NEG and CMOV.
23845   if (VT.isInteger() && VT.getSizeInBits() == 8)
23846     return SDValue();
23847
23848   SDValue N0 = N->getOperand(0);
23849   SDValue N1 = N->getOperand(1);
23850   SDLoc DL(N);
23851
23852   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23853   // and change it to SUB and CMOV.
23854   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23855       N0.getOpcode() == ISD::ADD &&
23856       N0.getOperand(1) == N1 &&
23857       N1.getOpcode() == ISD::SRA &&
23858       N1.getOperand(0) == N0.getOperand(0))
23859     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23860       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23861         // Generate SUB & CMOV.
23862         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23863                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23864
23865         SDValue Ops[] = { N0.getOperand(0), Neg,
23866                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23867                           SDValue(Neg.getNode(), 1) };
23868         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23869       }
23870   return SDValue();
23871 }
23872
23873 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23874 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23875                                  TargetLowering::DAGCombinerInfo &DCI,
23876                                  const X86Subtarget *Subtarget) {
23877   if (DCI.isBeforeLegalizeOps())
23878     return SDValue();
23879
23880   if (Subtarget->hasCMov())
23881     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23882       return RV;
23883
23884   return SDValue();
23885 }
23886
23887 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23888 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23889                                   TargetLowering::DAGCombinerInfo &DCI,
23890                                   const X86Subtarget *Subtarget) {
23891   LoadSDNode *Ld = cast<LoadSDNode>(N);
23892   EVT RegVT = Ld->getValueType(0);
23893   EVT MemVT = Ld->getMemoryVT();
23894   SDLoc dl(Ld);
23895   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23896
23897   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23898   // into two 16-byte operations.
23899   ISD::LoadExtType Ext = Ld->getExtensionType();
23900   unsigned Alignment = Ld->getAlignment();
23901   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23902   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23903       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23904     unsigned NumElems = RegVT.getVectorNumElements();
23905     if (NumElems < 2)
23906       return SDValue();
23907
23908     SDValue Ptr = Ld->getBasePtr();
23909     SDValue Increment =
23910         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
23911
23912     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23913                                   NumElems/2);
23914     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23915                                 Ld->getPointerInfo(), Ld->isVolatile(),
23916                                 Ld->isNonTemporal(), Ld->isInvariant(),
23917                                 Alignment);
23918     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23919     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23920                                 Ld->getPointerInfo(), Ld->isVolatile(),
23921                                 Ld->isNonTemporal(), Ld->isInvariant(),
23922                                 std::min(16U, Alignment));
23923     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23924                              Load1.getValue(1),
23925                              Load2.getValue(1));
23926
23927     SDValue NewVec = DAG.getUNDEF(RegVT);
23928     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23929     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23930     return DCI.CombineTo(N, NewVec, TF, true);
23931   }
23932
23933   return SDValue();
23934 }
23935
23936 /// PerformMLOADCombine - Resolve extending loads
23937 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23938                                    TargetLowering::DAGCombinerInfo &DCI,
23939                                    const X86Subtarget *Subtarget) {
23940   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23941   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23942     return SDValue();
23943
23944   EVT VT = Mld->getValueType(0);
23945   unsigned NumElems = VT.getVectorNumElements();
23946   EVT LdVT = Mld->getMemoryVT();
23947   SDLoc dl(Mld);
23948
23949   assert(LdVT != VT && "Cannot extend to the same type");
23950   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23951   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23952   // From, To sizes and ElemCount must be pow of two
23953   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23954     "Unexpected size for extending masked load");
23955
23956   unsigned SizeRatio  = ToSz / FromSz;
23957   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23958
23959   // Create a type on which we perform the shuffle
23960   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23961           LdVT.getScalarType(), NumElems*SizeRatio);
23962   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23963
23964   // Convert Src0 value
23965   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23966   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23967     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23968     for (unsigned i = 0; i != NumElems; ++i)
23969       ShuffleVec[i] = i * SizeRatio;
23970
23971     // Can't shuffle using an illegal type.
23972     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23973             && "WideVecVT should be legal");
23974     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23975                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23976   }
23977   // Prepare the new mask
23978   SDValue NewMask;
23979   SDValue Mask = Mld->getMask();
23980   if (Mask.getValueType() == VT) {
23981     // Mask and original value have the same type
23982     NewMask = DAG.getBitcast(WideVecVT, Mask);
23983     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23984     for (unsigned i = 0; i != NumElems; ++i)
23985       ShuffleVec[i] = i * SizeRatio;
23986     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23987       ShuffleVec[i] = NumElems*SizeRatio;
23988     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23989                                    DAG.getConstant(0, dl, WideVecVT),
23990                                    &ShuffleVec[0]);
23991   }
23992   else {
23993     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23994     unsigned WidenNumElts = NumElems*SizeRatio;
23995     unsigned MaskNumElts = VT.getVectorNumElements();
23996     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23997                                      WidenNumElts);
23998
23999     unsigned NumConcat = WidenNumElts / MaskNumElts;
24000     SmallVector<SDValue, 16> Ops(NumConcat);
24001     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24002     Ops[0] = Mask;
24003     for (unsigned i = 1; i != NumConcat; ++i)
24004       Ops[i] = ZeroVal;
24005
24006     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24007   }
24008
24009   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
24010                                      Mld->getBasePtr(), NewMask, WideSrc0,
24011                                      Mld->getMemoryVT(), Mld->getMemOperand(),
24012                                      ISD::NON_EXTLOAD);
24013   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
24014   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
24015
24016 }
24017 /// PerformMSTORECombine - Resolve truncating stores
24018 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
24019                                     const X86Subtarget *Subtarget) {
24020   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
24021   if (!Mst->isTruncatingStore())
24022     return SDValue();
24023
24024   EVT VT = Mst->getValue().getValueType();
24025   unsigned NumElems = VT.getVectorNumElements();
24026   EVT StVT = Mst->getMemoryVT();
24027   SDLoc dl(Mst);
24028
24029   assert(StVT != VT && "Cannot truncate to the same type");
24030   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24031   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24032
24033   // From, To sizes and ElemCount must be pow of two
24034   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
24035     "Unexpected size for truncating masked store");
24036   // We are going to use the original vector elt for storing.
24037   // Accumulated smaller vector elements must be a multiple of the store size.
24038   assert (((NumElems * FromSz) % ToSz) == 0 &&
24039           "Unexpected ratio for truncating masked store");
24040
24041   unsigned SizeRatio  = FromSz / ToSz;
24042   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24043
24044   // Create a type on which we perform the shuffle
24045   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24046           StVT.getScalarType(), NumElems*SizeRatio);
24047
24048   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24049
24050   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
24051   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
24052   for (unsigned i = 0; i != NumElems; ++i)
24053     ShuffleVec[i] = i * SizeRatio;
24054
24055   // Can't shuffle using an illegal type.
24056   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
24057           && "WideVecVT should be legal");
24058
24059   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24060                                         DAG.getUNDEF(WideVecVT),
24061                                         &ShuffleVec[0]);
24062
24063   SDValue NewMask;
24064   SDValue Mask = Mst->getMask();
24065   if (Mask.getValueType() == VT) {
24066     // Mask and original value have the same type
24067     NewMask = DAG.getBitcast(WideVecVT, Mask);
24068     for (unsigned i = 0; i != NumElems; ++i)
24069       ShuffleVec[i] = i * SizeRatio;
24070     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
24071       ShuffleVec[i] = NumElems*SizeRatio;
24072     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
24073                                    DAG.getConstant(0, dl, WideVecVT),
24074                                    &ShuffleVec[0]);
24075   }
24076   else {
24077     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
24078     unsigned WidenNumElts = NumElems*SizeRatio;
24079     unsigned MaskNumElts = VT.getVectorNumElements();
24080     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
24081                                      WidenNumElts);
24082
24083     unsigned NumConcat = WidenNumElts / MaskNumElts;
24084     SmallVector<SDValue, 16> Ops(NumConcat);
24085     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
24086     Ops[0] = Mask;
24087     for (unsigned i = 1; i != NumConcat; ++i)
24088       Ops[i] = ZeroVal;
24089
24090     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
24091   }
24092
24093   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
24094                             NewMask, StVT, Mst->getMemOperand(), false);
24095 }
24096 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
24097 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
24098                                    const X86Subtarget *Subtarget) {
24099   StoreSDNode *St = cast<StoreSDNode>(N);
24100   EVT VT = St->getValue().getValueType();
24101   EVT StVT = St->getMemoryVT();
24102   SDLoc dl(St);
24103   SDValue StoredVal = St->getOperand(1);
24104   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24105
24106   // If we are saving a concatenation of two XMM registers and 32-byte stores
24107   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
24108   unsigned Alignment = St->getAlignment();
24109   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
24110   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
24111       StVT == VT && !IsAligned) {
24112     unsigned NumElems = VT.getVectorNumElements();
24113     if (NumElems < 2)
24114       return SDValue();
24115
24116     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
24117     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
24118
24119     SDValue Stride =
24120         DAG.getConstant(16, dl, TLI.getPointerTy(DAG.getDataLayout()));
24121     SDValue Ptr0 = St->getBasePtr();
24122     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
24123
24124     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
24125                                 St->getPointerInfo(), St->isVolatile(),
24126                                 St->isNonTemporal(), Alignment);
24127     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
24128                                 St->getPointerInfo(), St->isVolatile(),
24129                                 St->isNonTemporal(),
24130                                 std::min(16U, Alignment));
24131     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
24132   }
24133
24134   // Optimize trunc store (of multiple scalars) to shuffle and store.
24135   // First, pack all of the elements in one place. Next, store to memory
24136   // in fewer chunks.
24137   if (St->isTruncatingStore() && VT.isVector()) {
24138     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24139     unsigned NumElems = VT.getVectorNumElements();
24140     assert(StVT != VT && "Cannot truncate to the same type");
24141     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
24142     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
24143
24144     // From, To sizes and ElemCount must be pow of two
24145     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
24146     // We are going to use the original vector elt for storing.
24147     // Accumulated smaller vector elements must be a multiple of the store size.
24148     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
24149
24150     unsigned SizeRatio  = FromSz / ToSz;
24151
24152     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
24153
24154     // Create a type on which we perform the shuffle
24155     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
24156             StVT.getScalarType(), NumElems*SizeRatio);
24157
24158     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
24159
24160     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
24161     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
24162     for (unsigned i = 0; i != NumElems; ++i)
24163       ShuffleVec[i] = i * SizeRatio;
24164
24165     // Can't shuffle using an illegal type.
24166     if (!TLI.isTypeLegal(WideVecVT))
24167       return SDValue();
24168
24169     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
24170                                          DAG.getUNDEF(WideVecVT),
24171                                          &ShuffleVec[0]);
24172     // At this point all of the data is stored at the bottom of the
24173     // register. We now need to save it to mem.
24174
24175     // Find the largest store unit
24176     MVT StoreType = MVT::i8;
24177     for (MVT Tp : MVT::integer_valuetypes()) {
24178       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
24179         StoreType = Tp;
24180     }
24181
24182     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
24183     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
24184         (64 <= NumElems * ToSz))
24185       StoreType = MVT::f64;
24186
24187     // Bitcast the original vector into a vector of store-size units
24188     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
24189             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
24190     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
24191     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
24192     SmallVector<SDValue, 8> Chains;
24193     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits() / 8, dl,
24194                                         TLI.getPointerTy(DAG.getDataLayout()));
24195     SDValue Ptr = St->getBasePtr();
24196
24197     // Perform one or more big stores into memory.
24198     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
24199       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
24200                                    StoreType, ShuffWide,
24201                                    DAG.getIntPtrConstant(i, dl));
24202       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
24203                                 St->getPointerInfo(), St->isVolatile(),
24204                                 St->isNonTemporal(), St->getAlignment());
24205       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
24206       Chains.push_back(Ch);
24207     }
24208
24209     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
24210   }
24211
24212   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
24213   // the FP state in cases where an emms may be missing.
24214   // A preferable solution to the general problem is to figure out the right
24215   // places to insert EMMS.  This qualifies as a quick hack.
24216
24217   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
24218   if (VT.getSizeInBits() != 64)
24219     return SDValue();
24220
24221   const Function *F = DAG.getMachineFunction().getFunction();
24222   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
24223   bool F64IsLegal =
24224       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
24225   if ((VT.isVector() ||
24226        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
24227       isa<LoadSDNode>(St->getValue()) &&
24228       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
24229       St->getChain().hasOneUse() && !St->isVolatile()) {
24230     SDNode* LdVal = St->getValue().getNode();
24231     LoadSDNode *Ld = nullptr;
24232     int TokenFactorIndex = -1;
24233     SmallVector<SDValue, 8> Ops;
24234     SDNode* ChainVal = St->getChain().getNode();
24235     // Must be a store of a load.  We currently handle two cases:  the load
24236     // is a direct child, and it's under an intervening TokenFactor.  It is
24237     // possible to dig deeper under nested TokenFactors.
24238     if (ChainVal == LdVal)
24239       Ld = cast<LoadSDNode>(St->getChain());
24240     else if (St->getValue().hasOneUse() &&
24241              ChainVal->getOpcode() == ISD::TokenFactor) {
24242       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
24243         if (ChainVal->getOperand(i).getNode() == LdVal) {
24244           TokenFactorIndex = i;
24245           Ld = cast<LoadSDNode>(St->getValue());
24246         } else
24247           Ops.push_back(ChainVal->getOperand(i));
24248       }
24249     }
24250
24251     if (!Ld || !ISD::isNormalLoad(Ld))
24252       return SDValue();
24253
24254     // If this is not the MMX case, i.e. we are just turning i64 load/store
24255     // into f64 load/store, avoid the transformation if there are multiple
24256     // uses of the loaded value.
24257     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
24258       return SDValue();
24259
24260     SDLoc LdDL(Ld);
24261     SDLoc StDL(N);
24262     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
24263     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
24264     // pair instead.
24265     if (Subtarget->is64Bit() || F64IsLegal) {
24266       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
24267       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
24268                                   Ld->getPointerInfo(), Ld->isVolatile(),
24269                                   Ld->isNonTemporal(), Ld->isInvariant(),
24270                                   Ld->getAlignment());
24271       SDValue NewChain = NewLd.getValue(1);
24272       if (TokenFactorIndex != -1) {
24273         Ops.push_back(NewChain);
24274         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24275       }
24276       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
24277                           St->getPointerInfo(),
24278                           St->isVolatile(), St->isNonTemporal(),
24279                           St->getAlignment());
24280     }
24281
24282     // Otherwise, lower to two pairs of 32-bit loads / stores.
24283     SDValue LoAddr = Ld->getBasePtr();
24284     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
24285                                  DAG.getConstant(4, LdDL, MVT::i32));
24286
24287     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
24288                                Ld->getPointerInfo(),
24289                                Ld->isVolatile(), Ld->isNonTemporal(),
24290                                Ld->isInvariant(), Ld->getAlignment());
24291     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
24292                                Ld->getPointerInfo().getWithOffset(4),
24293                                Ld->isVolatile(), Ld->isNonTemporal(),
24294                                Ld->isInvariant(),
24295                                MinAlign(Ld->getAlignment(), 4));
24296
24297     SDValue NewChain = LoLd.getValue(1);
24298     if (TokenFactorIndex != -1) {
24299       Ops.push_back(LoLd);
24300       Ops.push_back(HiLd);
24301       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
24302     }
24303
24304     LoAddr = St->getBasePtr();
24305     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
24306                          DAG.getConstant(4, StDL, MVT::i32));
24307
24308     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
24309                                 St->getPointerInfo(),
24310                                 St->isVolatile(), St->isNonTemporal(),
24311                                 St->getAlignment());
24312     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
24313                                 St->getPointerInfo().getWithOffset(4),
24314                                 St->isVolatile(),
24315                                 St->isNonTemporal(),
24316                                 MinAlign(St->getAlignment(), 4));
24317     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
24318   }
24319
24320   // This is similar to the above case, but here we handle a scalar 64-bit
24321   // integer store that is extracted from a vector on a 32-bit target.
24322   // If we have SSE2, then we can treat it like a floating-point double
24323   // to get past legalization. The execution dependencies fixup pass will
24324   // choose the optimal machine instruction for the store if this really is
24325   // an integer or v2f32 rather than an f64.
24326   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
24327       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
24328     SDValue OldExtract = St->getOperand(1);
24329     SDValue ExtOp0 = OldExtract.getOperand(0);
24330     unsigned VecSize = ExtOp0.getValueSizeInBits();
24331     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
24332     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
24333     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
24334                                      BitCast, OldExtract.getOperand(1));
24335     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
24336                         St->getPointerInfo(), St->isVolatile(),
24337                         St->isNonTemporal(), St->getAlignment());
24338   }
24339
24340   return SDValue();
24341 }
24342
24343 /// Return 'true' if this vector operation is "horizontal"
24344 /// and return the operands for the horizontal operation in LHS and RHS.  A
24345 /// horizontal operation performs the binary operation on successive elements
24346 /// of its first operand, then on successive elements of its second operand,
24347 /// returning the resulting values in a vector.  For example, if
24348 ///   A = < float a0, float a1, float a2, float a3 >
24349 /// and
24350 ///   B = < float b0, float b1, float b2, float b3 >
24351 /// then the result of doing a horizontal operation on A and B is
24352 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
24353 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
24354 /// A horizontal-op B, for some already available A and B, and if so then LHS is
24355 /// set to A, RHS to B, and the routine returns 'true'.
24356 /// Note that the binary operation should have the property that if one of the
24357 /// operands is UNDEF then the result is UNDEF.
24358 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
24359   // Look for the following pattern: if
24360   //   A = < float a0, float a1, float a2, float a3 >
24361   //   B = < float b0, float b1, float b2, float b3 >
24362   // and
24363   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
24364   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
24365   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
24366   // which is A horizontal-op B.
24367
24368   // At least one of the operands should be a vector shuffle.
24369   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
24370       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
24371     return false;
24372
24373   MVT VT = LHS.getSimpleValueType();
24374
24375   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24376          "Unsupported vector type for horizontal add/sub");
24377
24378   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24379   // operate independently on 128-bit lanes.
24380   unsigned NumElts = VT.getVectorNumElements();
24381   unsigned NumLanes = VT.getSizeInBits()/128;
24382   unsigned NumLaneElts = NumElts / NumLanes;
24383   assert((NumLaneElts % 2 == 0) &&
24384          "Vector type should have an even number of elements in each lane");
24385   unsigned HalfLaneElts = NumLaneElts/2;
24386
24387   // View LHS in the form
24388   //   LHS = VECTOR_SHUFFLE A, B, LMask
24389   // If LHS is not a shuffle then pretend it is the shuffle
24390   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24391   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24392   // type VT.
24393   SDValue A, B;
24394   SmallVector<int, 16> LMask(NumElts);
24395   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24396     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24397       A = LHS.getOperand(0);
24398     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24399       B = LHS.getOperand(1);
24400     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24401     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24402   } else {
24403     if (LHS.getOpcode() != ISD::UNDEF)
24404       A = LHS;
24405     for (unsigned i = 0; i != NumElts; ++i)
24406       LMask[i] = i;
24407   }
24408
24409   // Likewise, view RHS in the form
24410   //   RHS = VECTOR_SHUFFLE C, D, RMask
24411   SDValue C, D;
24412   SmallVector<int, 16> RMask(NumElts);
24413   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24414     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24415       C = RHS.getOperand(0);
24416     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24417       D = RHS.getOperand(1);
24418     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24419     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24420   } else {
24421     if (RHS.getOpcode() != ISD::UNDEF)
24422       C = RHS;
24423     for (unsigned i = 0; i != NumElts; ++i)
24424       RMask[i] = i;
24425   }
24426
24427   // Check that the shuffles are both shuffling the same vectors.
24428   if (!(A == C && B == D) && !(A == D && B == C))
24429     return false;
24430
24431   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24432   if (!A.getNode() && !B.getNode())
24433     return false;
24434
24435   // If A and B occur in reverse order in RHS, then "swap" them (which means
24436   // rewriting the mask).
24437   if (A != C)
24438     ShuffleVectorSDNode::commuteMask(RMask);
24439
24440   // At this point LHS and RHS are equivalent to
24441   //   LHS = VECTOR_SHUFFLE A, B, LMask
24442   //   RHS = VECTOR_SHUFFLE A, B, RMask
24443   // Check that the masks correspond to performing a horizontal operation.
24444   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24445     for (unsigned i = 0; i != NumLaneElts; ++i) {
24446       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24447
24448       // Ignore any UNDEF components.
24449       if (LIdx < 0 || RIdx < 0 ||
24450           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24451           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24452         continue;
24453
24454       // Check that successive elements are being operated on.  If not, this is
24455       // not a horizontal operation.
24456       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24457       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24458       if (!(LIdx == Index && RIdx == Index + 1) &&
24459           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24460         return false;
24461     }
24462   }
24463
24464   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24465   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24466   return true;
24467 }
24468
24469 /// Do target-specific dag combines on floating point adds.
24470 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24471                                   const X86Subtarget *Subtarget) {
24472   EVT VT = N->getValueType(0);
24473   SDValue LHS = N->getOperand(0);
24474   SDValue RHS = N->getOperand(1);
24475
24476   // Try to synthesize horizontal adds from adds of shuffles.
24477   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24478        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24479       isHorizontalBinOp(LHS, RHS, true))
24480     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24481   return SDValue();
24482 }
24483
24484 /// Do target-specific dag combines on floating point subs.
24485 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24486                                   const X86Subtarget *Subtarget) {
24487   EVT VT = N->getValueType(0);
24488   SDValue LHS = N->getOperand(0);
24489   SDValue RHS = N->getOperand(1);
24490
24491   // Try to synthesize horizontal subs from subs of shuffles.
24492   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24493        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24494       isHorizontalBinOp(LHS, RHS, false))
24495     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24496   return SDValue();
24497 }
24498
24499 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24500 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24501   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24502
24503   // F[X]OR(0.0, x) -> x
24504   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24505     if (C->getValueAPF().isPosZero())
24506       return N->getOperand(1);
24507
24508   // F[X]OR(x, 0.0) -> x
24509   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24510     if (C->getValueAPF().isPosZero())
24511       return N->getOperand(0);
24512   return SDValue();
24513 }
24514
24515 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24516 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24517   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24518
24519   // Only perform optimizations if UnsafeMath is used.
24520   if (!DAG.getTarget().Options.UnsafeFPMath)
24521     return SDValue();
24522
24523   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24524   // into FMINC and FMAXC, which are Commutative operations.
24525   unsigned NewOp = 0;
24526   switch (N->getOpcode()) {
24527     default: llvm_unreachable("unknown opcode");
24528     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24529     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24530   }
24531
24532   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24533                      N->getOperand(0), N->getOperand(1));
24534 }
24535
24536 /// Do target-specific dag combines on X86ISD::FAND nodes.
24537 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24538   // FAND(0.0, x) -> 0.0
24539   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24540     if (C->getValueAPF().isPosZero())
24541       return N->getOperand(0);
24542
24543   // FAND(x, 0.0) -> 0.0
24544   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24545     if (C->getValueAPF().isPosZero())
24546       return N->getOperand(1);
24547
24548   return SDValue();
24549 }
24550
24551 /// Do target-specific dag combines on X86ISD::FANDN nodes
24552 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24553   // FANDN(0.0, x) -> x
24554   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24555     if (C->getValueAPF().isPosZero())
24556       return N->getOperand(1);
24557
24558   // FANDN(x, 0.0) -> 0.0
24559   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24560     if (C->getValueAPF().isPosZero())
24561       return N->getOperand(1);
24562
24563   return SDValue();
24564 }
24565
24566 static SDValue PerformBTCombine(SDNode *N,
24567                                 SelectionDAG &DAG,
24568                                 TargetLowering::DAGCombinerInfo &DCI) {
24569   // BT ignores high bits in the bit index operand.
24570   SDValue Op1 = N->getOperand(1);
24571   if (Op1.hasOneUse()) {
24572     unsigned BitWidth = Op1.getValueSizeInBits();
24573     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24574     APInt KnownZero, KnownOne;
24575     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24576                                           !DCI.isBeforeLegalizeOps());
24577     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24578     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24579         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24580       DCI.CommitTargetLoweringOpt(TLO);
24581   }
24582   return SDValue();
24583 }
24584
24585 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24586   SDValue Op = N->getOperand(0);
24587   if (Op.getOpcode() == ISD::BITCAST)
24588     Op = Op.getOperand(0);
24589   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24590   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24591       VT.getVectorElementType().getSizeInBits() ==
24592       OpVT.getVectorElementType().getSizeInBits()) {
24593     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24594   }
24595   return SDValue();
24596 }
24597
24598 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24599                                                const X86Subtarget *Subtarget) {
24600   EVT VT = N->getValueType(0);
24601   if (!VT.isVector())
24602     return SDValue();
24603
24604   SDValue N0 = N->getOperand(0);
24605   SDValue N1 = N->getOperand(1);
24606   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24607   SDLoc dl(N);
24608
24609   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24610   // both SSE and AVX2 since there is no sign-extended shift right
24611   // operation on a vector with 64-bit elements.
24612   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24613   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24614   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24615       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24616     SDValue N00 = N0.getOperand(0);
24617
24618     // EXTLOAD has a better solution on AVX2,
24619     // it may be replaced with X86ISD::VSEXT node.
24620     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24621       if (!ISD::isNormalLoad(N00.getNode()))
24622         return SDValue();
24623
24624     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24625         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24626                                   N00, N1);
24627       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24628     }
24629   }
24630   return SDValue();
24631 }
24632
24633 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24634                                   TargetLowering::DAGCombinerInfo &DCI,
24635                                   const X86Subtarget *Subtarget) {
24636   SDValue N0 = N->getOperand(0);
24637   EVT VT = N->getValueType(0);
24638   EVT SVT = VT.getScalarType();
24639   EVT InVT = N0.getValueType();
24640   EVT InSVT = InVT.getScalarType();
24641   SDLoc DL(N);
24642
24643   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24644   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24645   // This exposes the sext to the sdivrem lowering, so that it directly extends
24646   // from AH (which we otherwise need to do contortions to access).
24647   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24648       InVT == MVT::i8 && VT == MVT::i32) {
24649     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24650     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24651                             N0.getOperand(0), N0.getOperand(1));
24652     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24653     return R.getValue(1);
24654   }
24655
24656   if (!DCI.isBeforeLegalizeOps()) {
24657     if (InVT == MVT::i1) {
24658       SDValue Zero = DAG.getConstant(0, DL, VT);
24659       SDValue AllOnes =
24660         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24661       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24662     }
24663     return SDValue();
24664   }
24665
24666   if (VT.isVector() && Subtarget->hasSSE2()) {
24667     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24668       EVT InVT = N.getValueType();
24669       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24670                                    Size / InVT.getScalarSizeInBits());
24671       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24672                                     DAG.getUNDEF(InVT));
24673       Opnds[0] = N;
24674       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24675     };
24676
24677     // If target-size is less than 128-bits, extend to a type that would extend
24678     // to 128 bits, extend that and extract the original target vector.
24679     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24680         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24681         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24682       unsigned Scale = 128 / VT.getSizeInBits();
24683       EVT ExVT =
24684           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24685       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24686       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24687       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24688                          DAG.getIntPtrConstant(0, DL));
24689     }
24690
24691     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24692     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24693     if (VT.getSizeInBits() == 128 &&
24694         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24695         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24696       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24697       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24698     }
24699
24700     // On pre-AVX2 targets, split into 128-bit nodes of
24701     // ISD::SIGN_EXTEND_VECTOR_INREG.
24702     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24703         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24704         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24705       unsigned NumVecs = VT.getSizeInBits() / 128;
24706       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24707       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24708       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24709
24710       SmallVector<SDValue, 8> Opnds;
24711       for (unsigned i = 0, Offset = 0; i != NumVecs;
24712            ++i, Offset += NumSubElts) {
24713         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24714                                      DAG.getIntPtrConstant(Offset, DL));
24715         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24716         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24717         Opnds.push_back(SrcVec);
24718       }
24719       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24720     }
24721   }
24722
24723   if (!Subtarget->hasFp256())
24724     return SDValue();
24725
24726   if (VT.isVector() && VT.getSizeInBits() == 256)
24727     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24728       return R;
24729
24730   return SDValue();
24731 }
24732
24733 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24734                                  const X86Subtarget* Subtarget) {
24735   SDLoc dl(N);
24736   EVT VT = N->getValueType(0);
24737
24738   // Let legalize expand this if it isn't a legal type yet.
24739   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24740     return SDValue();
24741
24742   EVT ScalarVT = VT.getScalarType();
24743   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24744       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24745        !Subtarget->hasAVX512()))
24746     return SDValue();
24747
24748   SDValue A = N->getOperand(0);
24749   SDValue B = N->getOperand(1);
24750   SDValue C = N->getOperand(2);
24751
24752   bool NegA = (A.getOpcode() == ISD::FNEG);
24753   bool NegB = (B.getOpcode() == ISD::FNEG);
24754   bool NegC = (C.getOpcode() == ISD::FNEG);
24755
24756   // Negative multiplication when NegA xor NegB
24757   bool NegMul = (NegA != NegB);
24758   if (NegA)
24759     A = A.getOperand(0);
24760   if (NegB)
24761     B = B.getOperand(0);
24762   if (NegC)
24763     C = C.getOperand(0);
24764
24765   unsigned Opcode;
24766   if (!NegMul)
24767     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24768   else
24769     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24770
24771   return DAG.getNode(Opcode, dl, VT, A, B, C);
24772 }
24773
24774 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24775                                   TargetLowering::DAGCombinerInfo &DCI,
24776                                   const X86Subtarget *Subtarget) {
24777   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24778   //           (and (i32 x86isd::setcc_carry), 1)
24779   // This eliminates the zext. This transformation is necessary because
24780   // ISD::SETCC is always legalized to i8.
24781   SDLoc dl(N);
24782   SDValue N0 = N->getOperand(0);
24783   EVT VT = N->getValueType(0);
24784
24785   if (N0.getOpcode() == ISD::AND &&
24786       N0.hasOneUse() &&
24787       N0.getOperand(0).hasOneUse()) {
24788     SDValue N00 = N0.getOperand(0);
24789     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24790       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24791       if (!C || C->getZExtValue() != 1)
24792         return SDValue();
24793       return DAG.getNode(ISD::AND, dl, VT,
24794                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24795                                      N00.getOperand(0), N00.getOperand(1)),
24796                          DAG.getConstant(1, dl, VT));
24797     }
24798   }
24799
24800   if (N0.getOpcode() == ISD::TRUNCATE &&
24801       N0.hasOneUse() &&
24802       N0.getOperand(0).hasOneUse()) {
24803     SDValue N00 = N0.getOperand(0);
24804     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24805       return DAG.getNode(ISD::AND, dl, VT,
24806                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24807                                      N00.getOperand(0), N00.getOperand(1)),
24808                          DAG.getConstant(1, dl, VT));
24809     }
24810   }
24811
24812   if (VT.is256BitVector())
24813     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24814       return R;
24815
24816   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24817   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24818   // This exposes the zext to the udivrem lowering, so that it directly extends
24819   // from AH (which we otherwise need to do contortions to access).
24820   if (N0.getOpcode() == ISD::UDIVREM &&
24821       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24822       (VT == MVT::i32 || VT == MVT::i64)) {
24823     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24824     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24825                             N0.getOperand(0), N0.getOperand(1));
24826     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24827     return R.getValue(1);
24828   }
24829
24830   return SDValue();
24831 }
24832
24833 // Optimize x == -y --> x+y == 0
24834 //          x != -y --> x+y != 0
24835 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24836                                       const X86Subtarget* Subtarget) {
24837   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24838   SDValue LHS = N->getOperand(0);
24839   SDValue RHS = N->getOperand(1);
24840   EVT VT = N->getValueType(0);
24841   SDLoc DL(N);
24842
24843   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24844     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24845       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24846         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24847                                    LHS.getOperand(1));
24848         return DAG.getSetCC(DL, N->getValueType(0), addV,
24849                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24850       }
24851   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24852     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24853       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24854         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24855                                    RHS.getOperand(1));
24856         return DAG.getSetCC(DL, N->getValueType(0), addV,
24857                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24858       }
24859
24860   if (VT.getScalarType() == MVT::i1 &&
24861       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24862     bool IsSEXT0 =
24863         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24864         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24865     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24866
24867     if (!IsSEXT0 || !IsVZero1) {
24868       // Swap the operands and update the condition code.
24869       std::swap(LHS, RHS);
24870       CC = ISD::getSetCCSwappedOperands(CC);
24871
24872       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24873                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24874       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24875     }
24876
24877     if (IsSEXT0 && IsVZero1) {
24878       assert(VT == LHS.getOperand(0).getValueType() &&
24879              "Uexpected operand type");
24880       if (CC == ISD::SETGT)
24881         return DAG.getConstant(0, DL, VT);
24882       if (CC == ISD::SETLE)
24883         return DAG.getConstant(1, DL, VT);
24884       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24885         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24886
24887       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24888              "Unexpected condition code!");
24889       return LHS.getOperand(0);
24890     }
24891   }
24892
24893   return SDValue();
24894 }
24895
24896 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24897                                          SelectionDAG &DAG) {
24898   SDLoc dl(Load);
24899   MVT VT = Load->getSimpleValueType(0);
24900   MVT EVT = VT.getVectorElementType();
24901   SDValue Addr = Load->getOperand(1);
24902   SDValue NewAddr = DAG.getNode(
24903       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24904       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24905                       Addr.getSimpleValueType()));
24906
24907   SDValue NewLoad =
24908       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24909                   DAG.getMachineFunction().getMachineMemOperand(
24910                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24911   return NewLoad;
24912 }
24913
24914 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24915                                       const X86Subtarget *Subtarget) {
24916   SDLoc dl(N);
24917   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24918   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24919          "X86insertps is only defined for v4x32");
24920
24921   SDValue Ld = N->getOperand(1);
24922   if (MayFoldLoad(Ld)) {
24923     // Extract the countS bits from the immediate so we can get the proper
24924     // address when narrowing the vector load to a specific element.
24925     // When the second source op is a memory address, insertps doesn't use
24926     // countS and just gets an f32 from that address.
24927     unsigned DestIndex =
24928         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24929
24930     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24931
24932     // Create this as a scalar to vector to match the instruction pattern.
24933     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24934     // countS bits are ignored when loading from memory on insertps, which
24935     // means we don't need to explicitly set them to 0.
24936     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24937                        LoadScalarToVector, N->getOperand(2));
24938   }
24939   return SDValue();
24940 }
24941
24942 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24943   SDValue V0 = N->getOperand(0);
24944   SDValue V1 = N->getOperand(1);
24945   SDLoc DL(N);
24946   EVT VT = N->getValueType(0);
24947
24948   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24949   // operands and changing the mask to 1. This saves us a bunch of
24950   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24951   // x86InstrInfo knows how to commute this back after instruction selection
24952   // if it would help register allocation.
24953
24954   // TODO: If optimizing for size or a processor that doesn't suffer from
24955   // partial register update stalls, this should be transformed into a MOVSD
24956   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24957
24958   if (VT == MVT::v2f64)
24959     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24960       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24961         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24962         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24963       }
24964
24965   return SDValue();
24966 }
24967
24968 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24969 // as "sbb reg,reg", since it can be extended without zext and produces
24970 // an all-ones bit which is more useful than 0/1 in some cases.
24971 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24972                                MVT VT) {
24973   if (VT == MVT::i8)
24974     return DAG.getNode(ISD::AND, DL, VT,
24975                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24976                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24977                                    EFLAGS),
24978                        DAG.getConstant(1, DL, VT));
24979   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24980   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24981                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24982                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24983                                  EFLAGS));
24984 }
24985
24986 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24987 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24988                                    TargetLowering::DAGCombinerInfo &DCI,
24989                                    const X86Subtarget *Subtarget) {
24990   SDLoc DL(N);
24991   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24992   SDValue EFLAGS = N->getOperand(1);
24993
24994   if (CC == X86::COND_A) {
24995     // Try to convert COND_A into COND_B in an attempt to facilitate
24996     // materializing "setb reg".
24997     //
24998     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24999     // cannot take an immediate as its first operand.
25000     //
25001     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
25002         EFLAGS.getValueType().isInteger() &&
25003         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
25004       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
25005                                    EFLAGS.getNode()->getVTList(),
25006                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
25007       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
25008       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
25009     }
25010   }
25011
25012   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
25013   // a zext and produces an all-ones bit which is more useful than 0/1 in some
25014   // cases.
25015   if (CC == X86::COND_B)
25016     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
25017
25018   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25019     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25020     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
25021   }
25022
25023   return SDValue();
25024 }
25025
25026 // Optimize branch condition evaluation.
25027 //
25028 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
25029                                     TargetLowering::DAGCombinerInfo &DCI,
25030                                     const X86Subtarget *Subtarget) {
25031   SDLoc DL(N);
25032   SDValue Chain = N->getOperand(0);
25033   SDValue Dest = N->getOperand(1);
25034   SDValue EFLAGS = N->getOperand(3);
25035   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
25036
25037   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
25038     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
25039     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
25040                        Flags);
25041   }
25042
25043   return SDValue();
25044 }
25045
25046 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
25047                                                          SelectionDAG &DAG) {
25048   // Take advantage of vector comparisons producing 0 or -1 in each lane to
25049   // optimize away operation when it's from a constant.
25050   //
25051   // The general transformation is:
25052   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
25053   //       AND(VECTOR_CMP(x,y), constant2)
25054   //    constant2 = UNARYOP(constant)
25055
25056   // Early exit if this isn't a vector operation, the operand of the
25057   // unary operation isn't a bitwise AND, or if the sizes of the operations
25058   // aren't the same.
25059   EVT VT = N->getValueType(0);
25060   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
25061       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
25062       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
25063     return SDValue();
25064
25065   // Now check that the other operand of the AND is a constant. We could
25066   // make the transformation for non-constant splats as well, but it's unclear
25067   // that would be a benefit as it would not eliminate any operations, just
25068   // perform one more step in scalar code before moving to the vector unit.
25069   if (BuildVectorSDNode *BV =
25070           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
25071     // Bail out if the vector isn't a constant.
25072     if (!BV->isConstant())
25073       return SDValue();
25074
25075     // Everything checks out. Build up the new and improved node.
25076     SDLoc DL(N);
25077     EVT IntVT = BV->getValueType(0);
25078     // Create a new constant of the appropriate type for the transformed
25079     // DAG.
25080     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
25081     // The AND node needs bitcasts to/from an integer vector type around it.
25082     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
25083     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
25084                                  N->getOperand(0)->getOperand(0), MaskConst);
25085     SDValue Res = DAG.getBitcast(VT, NewAnd);
25086     return Res;
25087   }
25088
25089   return SDValue();
25090 }
25091
25092 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25093                                         const X86Subtarget *Subtarget) {
25094   SDValue Op0 = N->getOperand(0);
25095   EVT VT = N->getValueType(0);
25096   EVT InVT = Op0.getValueType();
25097   EVT InSVT = InVT.getScalarType();
25098   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
25099
25100   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
25101   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
25102   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25103     SDLoc dl(N);
25104     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25105                                  InVT.getVectorNumElements());
25106     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
25107
25108     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
25109       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
25110
25111     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25112   }
25113
25114   return SDValue();
25115 }
25116
25117 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
25118                                         const X86Subtarget *Subtarget) {
25119   // First try to optimize away the conversion entirely when it's
25120   // conditionally from a constant. Vectors only.
25121   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
25122     return Res;
25123
25124   // Now move on to more general possibilities.
25125   SDValue Op0 = N->getOperand(0);
25126   EVT VT = N->getValueType(0);
25127   EVT InVT = Op0.getValueType();
25128   EVT InSVT = InVT.getScalarType();
25129
25130   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
25131   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
25132   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
25133     SDLoc dl(N);
25134     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
25135                                  InVT.getVectorNumElements());
25136     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
25137     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
25138   }
25139
25140   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
25141   // a 32-bit target where SSE doesn't support i64->FP operations.
25142   if (Op0.getOpcode() == ISD::LOAD) {
25143     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
25144     EVT LdVT = Ld->getValueType(0);
25145
25146     // This transformation is not supported if the result type is f16
25147     if (VT == MVT::f16)
25148       return SDValue();
25149
25150     if (!Ld->isVolatile() && !VT.isVector() &&
25151         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
25152         !Subtarget->is64Bit() && LdVT == MVT::i64) {
25153       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
25154           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
25155       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
25156       return FILDChain;
25157     }
25158   }
25159   return SDValue();
25160 }
25161
25162 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
25163 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
25164                                  X86TargetLowering::DAGCombinerInfo &DCI) {
25165   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
25166   // the result is either zero or one (depending on the input carry bit).
25167   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
25168   if (X86::isZeroNode(N->getOperand(0)) &&
25169       X86::isZeroNode(N->getOperand(1)) &&
25170       // We don't have a good way to replace an EFLAGS use, so only do this when
25171       // dead right now.
25172       SDValue(N, 1).use_empty()) {
25173     SDLoc DL(N);
25174     EVT VT = N->getValueType(0);
25175     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
25176     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
25177                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
25178                                            DAG.getConstant(X86::COND_B, DL,
25179                                                            MVT::i8),
25180                                            N->getOperand(2)),
25181                                DAG.getConstant(1, DL, VT));
25182     return DCI.CombineTo(N, Res1, CarryOut);
25183   }
25184
25185   return SDValue();
25186 }
25187
25188 // fold (add Y, (sete  X, 0)) -> adc  0, Y
25189 //      (add Y, (setne X, 0)) -> sbb -1, Y
25190 //      (sub (sete  X, 0), Y) -> sbb  0, Y
25191 //      (sub (setne X, 0), Y) -> adc -1, Y
25192 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
25193   SDLoc DL(N);
25194
25195   // Look through ZExts.
25196   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
25197   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
25198     return SDValue();
25199
25200   SDValue SetCC = Ext.getOperand(0);
25201   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
25202     return SDValue();
25203
25204   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
25205   if (CC != X86::COND_E && CC != X86::COND_NE)
25206     return SDValue();
25207
25208   SDValue Cmp = SetCC.getOperand(1);
25209   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
25210       !X86::isZeroNode(Cmp.getOperand(1)) ||
25211       !Cmp.getOperand(0).getValueType().isInteger())
25212     return SDValue();
25213
25214   SDValue CmpOp0 = Cmp.getOperand(0);
25215   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
25216                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
25217
25218   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
25219   if (CC == X86::COND_NE)
25220     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
25221                        DL, OtherVal.getValueType(), OtherVal,
25222                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
25223                        NewCmp);
25224   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
25225                      DL, OtherVal.getValueType(), OtherVal,
25226                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
25227 }
25228
25229 /// PerformADDCombine - Do target-specific dag combines on integer adds.
25230 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
25231                                  const X86Subtarget *Subtarget) {
25232   EVT VT = N->getValueType(0);
25233   SDValue Op0 = N->getOperand(0);
25234   SDValue Op1 = N->getOperand(1);
25235
25236   // Try to synthesize horizontal adds from adds of shuffles.
25237   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25238        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25239       isHorizontalBinOp(Op0, Op1, true))
25240     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
25241
25242   return OptimizeConditionalInDecrement(N, DAG);
25243 }
25244
25245 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
25246                                  const X86Subtarget *Subtarget) {
25247   SDValue Op0 = N->getOperand(0);
25248   SDValue Op1 = N->getOperand(1);
25249
25250   // X86 can't encode an immediate LHS of a sub. See if we can push the
25251   // negation into a preceding instruction.
25252   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
25253     // If the RHS of the sub is a XOR with one use and a constant, invert the
25254     // immediate. Then add one to the LHS of the sub so we can turn
25255     // X-Y -> X+~Y+1, saving one register.
25256     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
25257         isa<ConstantSDNode>(Op1.getOperand(1))) {
25258       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
25259       EVT VT = Op0.getValueType();
25260       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
25261                                    Op1.getOperand(0),
25262                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
25263       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
25264                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
25265     }
25266   }
25267
25268   // Try to synthesize horizontal adds from adds of shuffles.
25269   EVT VT = N->getValueType(0);
25270   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
25271        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
25272       isHorizontalBinOp(Op0, Op1, true))
25273     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
25274
25275   return OptimizeConditionalInDecrement(N, DAG);
25276 }
25277
25278 /// performVZEXTCombine - Performs build vector combines
25279 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
25280                                    TargetLowering::DAGCombinerInfo &DCI,
25281                                    const X86Subtarget *Subtarget) {
25282   SDLoc DL(N);
25283   MVT VT = N->getSimpleValueType(0);
25284   SDValue Op = N->getOperand(0);
25285   MVT OpVT = Op.getSimpleValueType();
25286   MVT OpEltVT = OpVT.getVectorElementType();
25287   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
25288
25289   // (vzext (bitcast (vzext (x)) -> (vzext x)
25290   SDValue V = Op;
25291   while (V.getOpcode() == ISD::BITCAST)
25292     V = V.getOperand(0);
25293
25294   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
25295     MVT InnerVT = V.getSimpleValueType();
25296     MVT InnerEltVT = InnerVT.getVectorElementType();
25297
25298     // If the element sizes match exactly, we can just do one larger vzext. This
25299     // is always an exact type match as vzext operates on integer types.
25300     if (OpEltVT == InnerEltVT) {
25301       assert(OpVT == InnerVT && "Types must match for vzext!");
25302       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
25303     }
25304
25305     // The only other way we can combine them is if only a single element of the
25306     // inner vzext is used in the input to the outer vzext.
25307     if (InnerEltVT.getSizeInBits() < InputBits)
25308       return SDValue();
25309
25310     // In this case, the inner vzext is completely dead because we're going to
25311     // only look at bits inside of the low element. Just do the outer vzext on
25312     // a bitcast of the input to the inner.
25313     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
25314   }
25315
25316   // Check if we can bypass extracting and re-inserting an element of an input
25317   // vector. Essentialy:
25318   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
25319   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
25320       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
25321       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
25322     SDValue ExtractedV = V.getOperand(0);
25323     SDValue OrigV = ExtractedV.getOperand(0);
25324     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
25325       if (ExtractIdx->getZExtValue() == 0) {
25326         MVT OrigVT = OrigV.getSimpleValueType();
25327         // Extract a subvector if necessary...
25328         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
25329           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
25330           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
25331                                     OrigVT.getVectorNumElements() / Ratio);
25332           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
25333                               DAG.getIntPtrConstant(0, DL));
25334         }
25335         Op = DAG.getBitcast(OpVT, OrigV);
25336         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
25337       }
25338   }
25339
25340   return SDValue();
25341 }
25342
25343 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
25344                                              DAGCombinerInfo &DCI) const {
25345   SelectionDAG &DAG = DCI.DAG;
25346   switch (N->getOpcode()) {
25347   default: break;
25348   case ISD::EXTRACT_VECTOR_ELT:
25349     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
25350   case ISD::VSELECT:
25351   case ISD::SELECT:
25352   case X86ISD::SHRUNKBLEND:
25353     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
25354   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
25355   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
25356   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
25357   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
25358   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
25359   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
25360   case ISD::SHL:
25361   case ISD::SRA:
25362   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
25363   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
25364   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
25365   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
25366   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
25367   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
25368   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
25369   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
25370   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
25371   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
25372   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
25373   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
25374   case X86ISD::FXOR:
25375   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25376   case X86ISD::FMIN:
25377   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25378   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25379   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25380   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25381   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25382   case ISD::ANY_EXTEND:
25383   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25384   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25385   case ISD::SIGN_EXTEND_INREG:
25386     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25387   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25388   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25389   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25390   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25391   case X86ISD::SHUFP:       // Handle all target specific shuffles
25392   case X86ISD::PALIGNR:
25393   case X86ISD::UNPCKH:
25394   case X86ISD::UNPCKL:
25395   case X86ISD::MOVHLPS:
25396   case X86ISD::MOVLHPS:
25397   case X86ISD::PSHUFB:
25398   case X86ISD::PSHUFD:
25399   case X86ISD::PSHUFHW:
25400   case X86ISD::PSHUFLW:
25401   case X86ISD::MOVSS:
25402   case X86ISD::MOVSD:
25403   case X86ISD::VPERMILPI:
25404   case X86ISD::VPERM2X128:
25405   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25406   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25407   case ISD::INTRINSIC_WO_CHAIN:
25408     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25409   case X86ISD::INSERTPS: {
25410     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25411       return PerformINSERTPSCombine(N, DAG, Subtarget);
25412     break;
25413   }
25414   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25415   }
25416
25417   return SDValue();
25418 }
25419
25420 /// isTypeDesirableForOp - Return true if the target has native support for
25421 /// the specified value type and it is 'desirable' to use the type for the
25422 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25423 /// instruction encodings are longer and some i16 instructions are slow.
25424 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25425   if (!isTypeLegal(VT))
25426     return false;
25427   if (VT != MVT::i16)
25428     return true;
25429
25430   switch (Opc) {
25431   default:
25432     return true;
25433   case ISD::LOAD:
25434   case ISD::SIGN_EXTEND:
25435   case ISD::ZERO_EXTEND:
25436   case ISD::ANY_EXTEND:
25437   case ISD::SHL:
25438   case ISD::SRL:
25439   case ISD::SUB:
25440   case ISD::ADD:
25441   case ISD::MUL:
25442   case ISD::AND:
25443   case ISD::OR:
25444   case ISD::XOR:
25445     return false;
25446   }
25447 }
25448
25449 /// IsDesirableToPromoteOp - This method query the target whether it is
25450 /// beneficial for dag combiner to promote the specified node. If true, it
25451 /// should return the desired promotion type by reference.
25452 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25453   EVT VT = Op.getValueType();
25454   if (VT != MVT::i16)
25455     return false;
25456
25457   bool Promote = false;
25458   bool Commute = false;
25459   switch (Op.getOpcode()) {
25460   default: break;
25461   case ISD::LOAD: {
25462     LoadSDNode *LD = cast<LoadSDNode>(Op);
25463     // If the non-extending load has a single use and it's not live out, then it
25464     // might be folded.
25465     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25466                                                      Op.hasOneUse()*/) {
25467       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25468              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25469         // The only case where we'd want to promote LOAD (rather then it being
25470         // promoted as an operand is when it's only use is liveout.
25471         if (UI->getOpcode() != ISD::CopyToReg)
25472           return false;
25473       }
25474     }
25475     Promote = true;
25476     break;
25477   }
25478   case ISD::SIGN_EXTEND:
25479   case ISD::ZERO_EXTEND:
25480   case ISD::ANY_EXTEND:
25481     Promote = true;
25482     break;
25483   case ISD::SHL:
25484   case ISD::SRL: {
25485     SDValue N0 = Op.getOperand(0);
25486     // Look out for (store (shl (load), x)).
25487     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25488       return false;
25489     Promote = true;
25490     break;
25491   }
25492   case ISD::ADD:
25493   case ISD::MUL:
25494   case ISD::AND:
25495   case ISD::OR:
25496   case ISD::XOR:
25497     Commute = true;
25498     // fallthrough
25499   case ISD::SUB: {
25500     SDValue N0 = Op.getOperand(0);
25501     SDValue N1 = Op.getOperand(1);
25502     if (!Commute && MayFoldLoad(N1))
25503       return false;
25504     // Avoid disabling potential load folding opportunities.
25505     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25506       return false;
25507     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25508       return false;
25509     Promote = true;
25510   }
25511   }
25512
25513   PVT = MVT::i32;
25514   return Promote;
25515 }
25516
25517 //===----------------------------------------------------------------------===//
25518 //                           X86 Inline Assembly Support
25519 //===----------------------------------------------------------------------===//
25520
25521 // Helper to match a string separated by whitespace.
25522 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25523   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25524
25525   for (StringRef Piece : Pieces) {
25526     if (!S.startswith(Piece)) // Check if the piece matches.
25527       return false;
25528
25529     S = S.substr(Piece.size());
25530     StringRef::size_type Pos = S.find_first_not_of(" \t");
25531     if (Pos == 0) // We matched a prefix.
25532       return false;
25533
25534     S = S.substr(Pos);
25535   }
25536
25537   return S.empty();
25538 }
25539
25540 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25541
25542   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25543     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25544         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25545         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25546
25547       if (AsmPieces.size() == 3)
25548         return true;
25549       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25550         return true;
25551     }
25552   }
25553   return false;
25554 }
25555
25556 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25557   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25558
25559   std::string AsmStr = IA->getAsmString();
25560
25561   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25562   if (!Ty || Ty->getBitWidth() % 16 != 0)
25563     return false;
25564
25565   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25566   SmallVector<StringRef, 4> AsmPieces;
25567   SplitString(AsmStr, AsmPieces, ";\n");
25568
25569   switch (AsmPieces.size()) {
25570   default: return false;
25571   case 1:
25572     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25573     // we will turn this bswap into something that will be lowered to logical
25574     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25575     // lower so don't worry about this.
25576     // bswap $0
25577     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25578         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25579         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25580         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25581         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25582         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25583       // No need to check constraints, nothing other than the equivalent of
25584       // "=r,0" would be valid here.
25585       return IntrinsicLowering::LowerToByteSwap(CI);
25586     }
25587
25588     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25589     if (CI->getType()->isIntegerTy(16) &&
25590         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25591         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25592          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25593       AsmPieces.clear();
25594       StringRef ConstraintsStr = IA->getConstraintString();
25595       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25596       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25597       if (clobbersFlagRegisters(AsmPieces))
25598         return IntrinsicLowering::LowerToByteSwap(CI);
25599     }
25600     break;
25601   case 3:
25602     if (CI->getType()->isIntegerTy(32) &&
25603         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25604         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25605         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25606         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25607       AsmPieces.clear();
25608       StringRef ConstraintsStr = IA->getConstraintString();
25609       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25610       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25611       if (clobbersFlagRegisters(AsmPieces))
25612         return IntrinsicLowering::LowerToByteSwap(CI);
25613     }
25614
25615     if (CI->getType()->isIntegerTy(64)) {
25616       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25617       if (Constraints.size() >= 2 &&
25618           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25619           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25620         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25621         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25622             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25623             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25624           return IntrinsicLowering::LowerToByteSwap(CI);
25625       }
25626     }
25627     break;
25628   }
25629   return false;
25630 }
25631
25632 /// getConstraintType - Given a constraint letter, return the type of
25633 /// constraint it is for this target.
25634 X86TargetLowering::ConstraintType
25635 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25636   if (Constraint.size() == 1) {
25637     switch (Constraint[0]) {
25638     case 'R':
25639     case 'q':
25640     case 'Q':
25641     case 'f':
25642     case 't':
25643     case 'u':
25644     case 'y':
25645     case 'x':
25646     case 'Y':
25647     case 'l':
25648       return C_RegisterClass;
25649     case 'a':
25650     case 'b':
25651     case 'c':
25652     case 'd':
25653     case 'S':
25654     case 'D':
25655     case 'A':
25656       return C_Register;
25657     case 'I':
25658     case 'J':
25659     case 'K':
25660     case 'L':
25661     case 'M':
25662     case 'N':
25663     case 'G':
25664     case 'C':
25665     case 'e':
25666     case 'Z':
25667       return C_Other;
25668     default:
25669       break;
25670     }
25671   }
25672   return TargetLowering::getConstraintType(Constraint);
25673 }
25674
25675 /// Examine constraint type and operand type and determine a weight value.
25676 /// This object must already have been set up with the operand type
25677 /// and the current alternative constraint selected.
25678 TargetLowering::ConstraintWeight
25679   X86TargetLowering::getSingleConstraintMatchWeight(
25680     AsmOperandInfo &info, const char *constraint) const {
25681   ConstraintWeight weight = CW_Invalid;
25682   Value *CallOperandVal = info.CallOperandVal;
25683     // If we don't have a value, we can't do a match,
25684     // but allow it at the lowest weight.
25685   if (!CallOperandVal)
25686     return CW_Default;
25687   Type *type = CallOperandVal->getType();
25688   // Look at the constraint type.
25689   switch (*constraint) {
25690   default:
25691     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25692   case 'R':
25693   case 'q':
25694   case 'Q':
25695   case 'a':
25696   case 'b':
25697   case 'c':
25698   case 'd':
25699   case 'S':
25700   case 'D':
25701   case 'A':
25702     if (CallOperandVal->getType()->isIntegerTy())
25703       weight = CW_SpecificReg;
25704     break;
25705   case 'f':
25706   case 't':
25707   case 'u':
25708     if (type->isFloatingPointTy())
25709       weight = CW_SpecificReg;
25710     break;
25711   case 'y':
25712     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25713       weight = CW_SpecificReg;
25714     break;
25715   case 'x':
25716   case 'Y':
25717     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25718         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25719       weight = CW_Register;
25720     break;
25721   case 'I':
25722     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25723       if (C->getZExtValue() <= 31)
25724         weight = CW_Constant;
25725     }
25726     break;
25727   case 'J':
25728     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25729       if (C->getZExtValue() <= 63)
25730         weight = CW_Constant;
25731     }
25732     break;
25733   case 'K':
25734     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25735       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25736         weight = CW_Constant;
25737     }
25738     break;
25739   case 'L':
25740     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25741       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25742         weight = CW_Constant;
25743     }
25744     break;
25745   case 'M':
25746     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25747       if (C->getZExtValue() <= 3)
25748         weight = CW_Constant;
25749     }
25750     break;
25751   case 'N':
25752     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25753       if (C->getZExtValue() <= 0xff)
25754         weight = CW_Constant;
25755     }
25756     break;
25757   case 'G':
25758   case 'C':
25759     if (isa<ConstantFP>(CallOperandVal)) {
25760       weight = CW_Constant;
25761     }
25762     break;
25763   case 'e':
25764     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25765       if ((C->getSExtValue() >= -0x80000000LL) &&
25766           (C->getSExtValue() <= 0x7fffffffLL))
25767         weight = CW_Constant;
25768     }
25769     break;
25770   case 'Z':
25771     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25772       if (C->getZExtValue() <= 0xffffffff)
25773         weight = CW_Constant;
25774     }
25775     break;
25776   }
25777   return weight;
25778 }
25779
25780 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25781 /// with another that has more specific requirements based on the type of the
25782 /// corresponding operand.
25783 const char *X86TargetLowering::
25784 LowerXConstraint(EVT ConstraintVT) const {
25785   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25786   // 'f' like normal targets.
25787   if (ConstraintVT.isFloatingPoint()) {
25788     if (Subtarget->hasSSE2())
25789       return "Y";
25790     if (Subtarget->hasSSE1())
25791       return "x";
25792   }
25793
25794   return TargetLowering::LowerXConstraint(ConstraintVT);
25795 }
25796
25797 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25798 /// vector.  If it is invalid, don't add anything to Ops.
25799 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25800                                                      std::string &Constraint,
25801                                                      std::vector<SDValue>&Ops,
25802                                                      SelectionDAG &DAG) const {
25803   SDValue Result;
25804
25805   // Only support length 1 constraints for now.
25806   if (Constraint.length() > 1) return;
25807
25808   char ConstraintLetter = Constraint[0];
25809   switch (ConstraintLetter) {
25810   default: break;
25811   case 'I':
25812     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25813       if (C->getZExtValue() <= 31) {
25814         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25815                                        Op.getValueType());
25816         break;
25817       }
25818     }
25819     return;
25820   case 'J':
25821     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25822       if (C->getZExtValue() <= 63) {
25823         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25824                                        Op.getValueType());
25825         break;
25826       }
25827     }
25828     return;
25829   case 'K':
25830     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25831       if (isInt<8>(C->getSExtValue())) {
25832         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25833                                        Op.getValueType());
25834         break;
25835       }
25836     }
25837     return;
25838   case 'L':
25839     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25840       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25841           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25842         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25843                                        Op.getValueType());
25844         break;
25845       }
25846     }
25847     return;
25848   case 'M':
25849     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25850       if (C->getZExtValue() <= 3) {
25851         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25852                                        Op.getValueType());
25853         break;
25854       }
25855     }
25856     return;
25857   case 'N':
25858     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25859       if (C->getZExtValue() <= 255) {
25860         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25861                                        Op.getValueType());
25862         break;
25863       }
25864     }
25865     return;
25866   case 'O':
25867     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25868       if (C->getZExtValue() <= 127) {
25869         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25870                                        Op.getValueType());
25871         break;
25872       }
25873     }
25874     return;
25875   case 'e': {
25876     // 32-bit signed value
25877     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25878       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25879                                            C->getSExtValue())) {
25880         // Widen to 64 bits here to get it sign extended.
25881         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25882         break;
25883       }
25884     // FIXME gcc accepts some relocatable values here too, but only in certain
25885     // memory models; it's complicated.
25886     }
25887     return;
25888   }
25889   case 'Z': {
25890     // 32-bit unsigned value
25891     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25892       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25893                                            C->getZExtValue())) {
25894         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25895                                        Op.getValueType());
25896         break;
25897       }
25898     }
25899     // FIXME gcc accepts some relocatable values here too, but only in certain
25900     // memory models; it's complicated.
25901     return;
25902   }
25903   case 'i': {
25904     // Literal immediates are always ok.
25905     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25906       // Widen to 64 bits here to get it sign extended.
25907       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25908       break;
25909     }
25910
25911     // In any sort of PIC mode addresses need to be computed at runtime by
25912     // adding in a register or some sort of table lookup.  These can't
25913     // be used as immediates.
25914     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25915       return;
25916
25917     // If we are in non-pic codegen mode, we allow the address of a global (with
25918     // an optional displacement) to be used with 'i'.
25919     GlobalAddressSDNode *GA = nullptr;
25920     int64_t Offset = 0;
25921
25922     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25923     while (1) {
25924       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25925         Offset += GA->getOffset();
25926         break;
25927       } else if (Op.getOpcode() == ISD::ADD) {
25928         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25929           Offset += C->getZExtValue();
25930           Op = Op.getOperand(0);
25931           continue;
25932         }
25933       } else if (Op.getOpcode() == ISD::SUB) {
25934         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25935           Offset += -C->getZExtValue();
25936           Op = Op.getOperand(0);
25937           continue;
25938         }
25939       }
25940
25941       // Otherwise, this isn't something we can handle, reject it.
25942       return;
25943     }
25944
25945     const GlobalValue *GV = GA->getGlobal();
25946     // If we require an extra load to get this address, as in PIC mode, we
25947     // can't accept it.
25948     if (isGlobalStubReference(
25949             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25950       return;
25951
25952     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25953                                         GA->getValueType(0), Offset);
25954     break;
25955   }
25956   }
25957
25958   if (Result.getNode()) {
25959     Ops.push_back(Result);
25960     return;
25961   }
25962   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25963 }
25964
25965 std::pair<unsigned, const TargetRegisterClass *>
25966 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25967                                                 StringRef Constraint,
25968                                                 MVT VT) const {
25969   // First, see if this is a constraint that directly corresponds to an LLVM
25970   // register class.
25971   if (Constraint.size() == 1) {
25972     // GCC Constraint Letters
25973     switch (Constraint[0]) {
25974     default: break;
25975       // TODO: Slight differences here in allocation order and leaving
25976       // RIP in the class. Do they matter any more here than they do
25977       // in the normal allocation?
25978     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25979       if (Subtarget->is64Bit()) {
25980         if (VT == MVT::i32 || VT == MVT::f32)
25981           return std::make_pair(0U, &X86::GR32RegClass);
25982         if (VT == MVT::i16)
25983           return std::make_pair(0U, &X86::GR16RegClass);
25984         if (VT == MVT::i8 || VT == MVT::i1)
25985           return std::make_pair(0U, &X86::GR8RegClass);
25986         if (VT == MVT::i64 || VT == MVT::f64)
25987           return std::make_pair(0U, &X86::GR64RegClass);
25988         break;
25989       }
25990       // 32-bit fallthrough
25991     case 'Q':   // Q_REGS
25992       if (VT == MVT::i32 || VT == MVT::f32)
25993         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25994       if (VT == MVT::i16)
25995         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25996       if (VT == MVT::i8 || VT == MVT::i1)
25997         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25998       if (VT == MVT::i64)
25999         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
26000       break;
26001     case 'r':   // GENERAL_REGS
26002     case 'l':   // INDEX_REGS
26003       if (VT == MVT::i8 || VT == MVT::i1)
26004         return std::make_pair(0U, &X86::GR8RegClass);
26005       if (VT == MVT::i16)
26006         return std::make_pair(0U, &X86::GR16RegClass);
26007       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
26008         return std::make_pair(0U, &X86::GR32RegClass);
26009       return std::make_pair(0U, &X86::GR64RegClass);
26010     case 'R':   // LEGACY_REGS
26011       if (VT == MVT::i8 || VT == MVT::i1)
26012         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
26013       if (VT == MVT::i16)
26014         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
26015       if (VT == MVT::i32 || !Subtarget->is64Bit())
26016         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
26017       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
26018     case 'f':  // FP Stack registers.
26019       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
26020       // value to the correct fpstack register class.
26021       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
26022         return std::make_pair(0U, &X86::RFP32RegClass);
26023       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
26024         return std::make_pair(0U, &X86::RFP64RegClass);
26025       return std::make_pair(0U, &X86::RFP80RegClass);
26026     case 'y':   // MMX_REGS if MMX allowed.
26027       if (!Subtarget->hasMMX()) break;
26028       return std::make_pair(0U, &X86::VR64RegClass);
26029     case 'Y':   // SSE_REGS if SSE2 allowed
26030       if (!Subtarget->hasSSE2()) break;
26031       // FALL THROUGH.
26032     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
26033       if (!Subtarget->hasSSE1()) break;
26034
26035       switch (VT.SimpleTy) {
26036       default: break;
26037       // Scalar SSE types.
26038       case MVT::f32:
26039       case MVT::i32:
26040         return std::make_pair(0U, &X86::FR32RegClass);
26041       case MVT::f64:
26042       case MVT::i64:
26043         return std::make_pair(0U, &X86::FR64RegClass);
26044       // Vector types.
26045       case MVT::v16i8:
26046       case MVT::v8i16:
26047       case MVT::v4i32:
26048       case MVT::v2i64:
26049       case MVT::v4f32:
26050       case MVT::v2f64:
26051         return std::make_pair(0U, &X86::VR128RegClass);
26052       // AVX types.
26053       case MVT::v32i8:
26054       case MVT::v16i16:
26055       case MVT::v8i32:
26056       case MVT::v4i64:
26057       case MVT::v8f32:
26058       case MVT::v4f64:
26059         return std::make_pair(0U, &X86::VR256RegClass);
26060       case MVT::v8f64:
26061       case MVT::v16f32:
26062       case MVT::v16i32:
26063       case MVT::v8i64:
26064         return std::make_pair(0U, &X86::VR512RegClass);
26065       }
26066       break;
26067     }
26068   }
26069
26070   // Use the default implementation in TargetLowering to convert the register
26071   // constraint into a member of a register class.
26072   std::pair<unsigned, const TargetRegisterClass*> Res;
26073   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
26074
26075   // Not found as a standard register?
26076   if (!Res.second) {
26077     // Map st(0) -> st(7) -> ST0
26078     if (Constraint.size() == 7 && Constraint[0] == '{' &&
26079         tolower(Constraint[1]) == 's' &&
26080         tolower(Constraint[2]) == 't' &&
26081         Constraint[3] == '(' &&
26082         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
26083         Constraint[5] == ')' &&
26084         Constraint[6] == '}') {
26085
26086       Res.first = X86::FP0+Constraint[4]-'0';
26087       Res.second = &X86::RFP80RegClass;
26088       return Res;
26089     }
26090
26091     // GCC allows "st(0)" to be called just plain "st".
26092     if (StringRef("{st}").equals_lower(Constraint)) {
26093       Res.first = X86::FP0;
26094       Res.second = &X86::RFP80RegClass;
26095       return Res;
26096     }
26097
26098     // flags -> EFLAGS
26099     if (StringRef("{flags}").equals_lower(Constraint)) {
26100       Res.first = X86::EFLAGS;
26101       Res.second = &X86::CCRRegClass;
26102       return Res;
26103     }
26104
26105     // 'A' means EAX + EDX.
26106     if (Constraint == "A") {
26107       Res.first = X86::EAX;
26108       Res.second = &X86::GR32_ADRegClass;
26109       return Res;
26110     }
26111     return Res;
26112   }
26113
26114   // Otherwise, check to see if this is a register class of the wrong value
26115   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
26116   // turn into {ax},{dx}.
26117   // MVT::Other is used to specify clobber names.
26118   if (Res.second->hasType(VT) || VT == MVT::Other)
26119     return Res;   // Correct type already, nothing to do.
26120
26121   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
26122   // return "eax". This should even work for things like getting 64bit integer
26123   // registers when given an f64 type.
26124   const TargetRegisterClass *Class = Res.second;
26125   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
26126       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
26127     unsigned Size = VT.getSizeInBits();
26128     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
26129                                   : Size == 16 ? MVT::i16
26130                                   : Size == 32 ? MVT::i32
26131                                   : Size == 64 ? MVT::i64
26132                                   : MVT::Other;
26133     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
26134     if (DestReg > 0) {
26135       Res.first = DestReg;
26136       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
26137                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
26138                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
26139                  : &X86::GR64RegClass;
26140       assert(Res.second->contains(Res.first) && "Register in register class");
26141     } else {
26142       // No register found/type mismatch.
26143       Res.first = 0;
26144       Res.second = nullptr;
26145     }
26146   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
26147              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
26148              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
26149              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
26150              Class == &X86::VR512RegClass) {
26151     // Handle references to XMM physical registers that got mapped into the
26152     // wrong class.  This can happen with constraints like {xmm0} where the
26153     // target independent register mapper will just pick the first match it can
26154     // find, ignoring the required type.
26155
26156     if (VT == MVT::f32 || VT == MVT::i32)
26157       Res.second = &X86::FR32RegClass;
26158     else if (VT == MVT::f64 || VT == MVT::i64)
26159       Res.second = &X86::FR64RegClass;
26160     else if (X86::VR128RegClass.hasType(VT))
26161       Res.second = &X86::VR128RegClass;
26162     else if (X86::VR256RegClass.hasType(VT))
26163       Res.second = &X86::VR256RegClass;
26164     else if (X86::VR512RegClass.hasType(VT))
26165       Res.second = &X86::VR512RegClass;
26166     else {
26167       // Type mismatch and not a clobber: Return an error;
26168       Res.first = 0;
26169       Res.second = nullptr;
26170     }
26171   }
26172
26173   return Res;
26174 }
26175
26176 int X86TargetLowering::getScalingFactorCost(const DataLayout &DL,
26177                                             const AddrMode &AM, Type *Ty,
26178                                             unsigned AS) const {
26179   // Scaling factors are not free at all.
26180   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
26181   // will take 2 allocations in the out of order engine instead of 1
26182   // for plain addressing mode, i.e. inst (reg1).
26183   // E.g.,
26184   // vaddps (%rsi,%drx), %ymm0, %ymm1
26185   // Requires two allocations (one for the load, one for the computation)
26186   // whereas:
26187   // vaddps (%rsi), %ymm0, %ymm1
26188   // Requires just 1 allocation, i.e., freeing allocations for other operations
26189   // and having less micro operations to execute.
26190   //
26191   // For some X86 architectures, this is even worse because for instance for
26192   // stores, the complex addressing mode forces the instruction to use the
26193   // "load" ports instead of the dedicated "store" port.
26194   // E.g., on Haswell:
26195   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
26196   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
26197   if (isLegalAddressingMode(DL, AM, Ty, AS))
26198     // Scale represents reg2 * scale, thus account for 1
26199     // as soon as we use a second register.
26200     return AM.Scale != 0;
26201   return -1;
26202 }
26203
26204 bool X86TargetLowering::isTargetFTOL() const {
26205   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
26206 }