[X86][SSE] Use the general SMAX/SMIN/UMAX/UMIN opcodes and remove the X86 implementation
[oota-llvm.git] / lib / Target / X86 / X86ISelLowering.cpp
1 //===-- X86ISelLowering.cpp - X86 DAG Lowering Implementation -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the interfaces that X86 uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "X86ISelLowering.h"
16 #include "Utils/X86ShuffleDecode.h"
17 #include "X86CallingConv.h"
18 #include "X86FrameLowering.h"
19 #include "X86InstrBuilder.h"
20 #include "X86MachineFunctionInfo.h"
21 #include "X86TargetMachine.h"
22 #include "X86TargetObjectFile.h"
23 #include "llvm/ADT/SmallBitVector.h"
24 #include "llvm/ADT/SmallSet.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/ADT/StringExtras.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/CodeGen/IntrinsicLowering.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineJumpTableInfo.h"
33 #include "llvm/CodeGen/MachineModuleInfo.h"
34 #include "llvm/CodeGen/MachineRegisterInfo.h"
35 #include "llvm/CodeGen/WinEHFuncInfo.h"
36 #include "llvm/IR/CallSite.h"
37 #include "llvm/IR/CallingConv.h"
38 #include "llvm/IR/Constants.h"
39 #include "llvm/IR/DerivedTypes.h"
40 #include "llvm/IR/Function.h"
41 #include "llvm/IR/GlobalAlias.h"
42 #include "llvm/IR/GlobalVariable.h"
43 #include "llvm/IR/Instructions.h"
44 #include "llvm/IR/Intrinsics.h"
45 #include "llvm/MC/MCAsmInfo.h"
46 #include "llvm/MC/MCContext.h"
47 #include "llvm/MC/MCExpr.h"
48 #include "llvm/MC/MCSymbol.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Debug.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/MathExtras.h"
53 #include "llvm/Target/TargetOptions.h"
54 #include "X86IntrinsicsInfo.h"
55 #include <bitset>
56 #include <numeric>
57 #include <cctype>
58 using namespace llvm;
59
60 #define DEBUG_TYPE "x86-isel"
61
62 STATISTIC(NumTailCalls, "Number of tail calls");
63
64 static cl::opt<bool> ExperimentalVectorWideningLegalization(
65     "x86-experimental-vector-widening-legalization", cl::init(false),
66     cl::desc("Enable an experimental vector type legalization through widening "
67              "rather than promotion."),
68     cl::Hidden);
69
70 // Forward declarations.
71 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
72                        SDValue V2);
73
74 X86TargetLowering::X86TargetLowering(const X86TargetMachine &TM,
75                                      const X86Subtarget &STI)
76     : TargetLowering(TM), Subtarget(&STI) {
77   X86ScalarSSEf64 = Subtarget->hasSSE2();
78   X86ScalarSSEf32 = Subtarget->hasSSE1();
79   TD = getDataLayout();
80
81   // Set up the TargetLowering object.
82   static const MVT IntVTs[] = { MVT::i8, MVT::i16, MVT::i32, MVT::i64 };
83
84   // X86 is weird. It always uses i8 for shift amounts and setcc results.
85   setBooleanContents(ZeroOrOneBooleanContent);
86   // X86-SSE is even stranger. It uses -1 or 0 for vector masks.
87   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
88
89   // For 64-bit, since we have so many registers, use the ILP scheduler.
90   // For 32-bit, use the register pressure specific scheduling.
91   // For Atom, always use ILP scheduling.
92   if (Subtarget->isAtom())
93     setSchedulingPreference(Sched::ILP);
94   else if (Subtarget->is64Bit())
95     setSchedulingPreference(Sched::ILP);
96   else
97     setSchedulingPreference(Sched::RegPressure);
98   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
99   setStackPointerRegisterToSaveRestore(RegInfo->getStackRegister());
100
101   // Bypass expensive divides on Atom when compiling with O2.
102   if (TM.getOptLevel() >= CodeGenOpt::Default) {
103     if (Subtarget->hasSlowDivide32())
104       addBypassSlowDiv(32, 8);
105     if (Subtarget->hasSlowDivide64() && Subtarget->is64Bit())
106       addBypassSlowDiv(64, 16);
107   }
108
109   if (Subtarget->isTargetKnownWindowsMSVC()) {
110     // Setup Windows compiler runtime calls.
111     setLibcallName(RTLIB::SDIV_I64, "_alldiv");
112     setLibcallName(RTLIB::UDIV_I64, "_aulldiv");
113     setLibcallName(RTLIB::SREM_I64, "_allrem");
114     setLibcallName(RTLIB::UREM_I64, "_aullrem");
115     setLibcallName(RTLIB::MUL_I64, "_allmul");
116     setLibcallCallingConv(RTLIB::SDIV_I64, CallingConv::X86_StdCall);
117     setLibcallCallingConv(RTLIB::UDIV_I64, CallingConv::X86_StdCall);
118     setLibcallCallingConv(RTLIB::SREM_I64, CallingConv::X86_StdCall);
119     setLibcallCallingConv(RTLIB::UREM_I64, CallingConv::X86_StdCall);
120     setLibcallCallingConv(RTLIB::MUL_I64, CallingConv::X86_StdCall);
121
122     // The _ftol2 runtime function has an unusual calling conv, which
123     // is modeled by a special pseudo-instruction.
124     setLibcallName(RTLIB::FPTOUINT_F64_I64, nullptr);
125     setLibcallName(RTLIB::FPTOUINT_F32_I64, nullptr);
126     setLibcallName(RTLIB::FPTOUINT_F64_I32, nullptr);
127     setLibcallName(RTLIB::FPTOUINT_F32_I32, nullptr);
128   }
129
130   if (Subtarget->isTargetDarwin()) {
131     // Darwin should use _setjmp/_longjmp instead of setjmp/longjmp.
132     setUseUnderscoreSetJmp(false);
133     setUseUnderscoreLongJmp(false);
134   } else if (Subtarget->isTargetWindowsGNU()) {
135     // MS runtime is weird: it exports _setjmp, but longjmp!
136     setUseUnderscoreSetJmp(true);
137     setUseUnderscoreLongJmp(false);
138   } else {
139     setUseUnderscoreSetJmp(true);
140     setUseUnderscoreLongJmp(true);
141   }
142
143   // Set up the register classes.
144   addRegisterClass(MVT::i8, &X86::GR8RegClass);
145   addRegisterClass(MVT::i16, &X86::GR16RegClass);
146   addRegisterClass(MVT::i32, &X86::GR32RegClass);
147   if (Subtarget->is64Bit())
148     addRegisterClass(MVT::i64, &X86::GR64RegClass);
149
150   for (MVT VT : MVT::integer_valuetypes())
151     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
152
153   // We don't accept any truncstore of integer registers.
154   setTruncStoreAction(MVT::i64, MVT::i32, Expand);
155   setTruncStoreAction(MVT::i64, MVT::i16, Expand);
156   setTruncStoreAction(MVT::i64, MVT::i8 , Expand);
157   setTruncStoreAction(MVT::i32, MVT::i16, Expand);
158   setTruncStoreAction(MVT::i32, MVT::i8 , Expand);
159   setTruncStoreAction(MVT::i16, MVT::i8,  Expand);
160
161   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
162
163   // SETOEQ and SETUNE require checking two conditions.
164   setCondCodeAction(ISD::SETOEQ, MVT::f32, Expand);
165   setCondCodeAction(ISD::SETOEQ, MVT::f64, Expand);
166   setCondCodeAction(ISD::SETOEQ, MVT::f80, Expand);
167   setCondCodeAction(ISD::SETUNE, MVT::f32, Expand);
168   setCondCodeAction(ISD::SETUNE, MVT::f64, Expand);
169   setCondCodeAction(ISD::SETUNE, MVT::f80, Expand);
170
171   // Promote all UINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have this
172   // operation.
173   setOperationAction(ISD::UINT_TO_FP       , MVT::i1   , Promote);
174   setOperationAction(ISD::UINT_TO_FP       , MVT::i8   , Promote);
175   setOperationAction(ISD::UINT_TO_FP       , MVT::i16  , Promote);
176
177   if (Subtarget->is64Bit()) {
178     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Promote);
179     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
180   } else if (!Subtarget->useSoftFloat()) {
181     // We have an algorithm for SSE2->double, and we turn this into a
182     // 64-bit FILD followed by conditional FADD for other targets.
183     setOperationAction(ISD::UINT_TO_FP     , MVT::i64  , Custom);
184     // We have an algorithm for SSE2, and we turn this into a 64-bit
185     // FILD for other targets.
186     setOperationAction(ISD::UINT_TO_FP     , MVT::i32  , Custom);
187   }
188
189   // Promote i1/i8 SINT_TO_FP to larger SINT_TO_FP's, as X86 doesn't have
190   // this operation.
191   setOperationAction(ISD::SINT_TO_FP       , MVT::i1   , Promote);
192   setOperationAction(ISD::SINT_TO_FP       , MVT::i8   , Promote);
193
194   if (!Subtarget->useSoftFloat()) {
195     // SSE has no i16 to fp conversion, only i32
196     if (X86ScalarSSEf32) {
197       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
198       // f32 and f64 cases are Legal, f80 case is not
199       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
200     } else {
201       setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Custom);
202       setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Custom);
203     }
204   } else {
205     setOperationAction(ISD::SINT_TO_FP     , MVT::i16  , Promote);
206     setOperationAction(ISD::SINT_TO_FP     , MVT::i32  , Promote);
207   }
208
209   // In 32-bit mode these are custom lowered.  In 64-bit mode F32 and F64
210   // are Legal, f80 is custom lowered.
211   setOperationAction(ISD::FP_TO_SINT     , MVT::i64  , Custom);
212   setOperationAction(ISD::SINT_TO_FP     , MVT::i64  , Custom);
213
214   // Promote i1/i8 FP_TO_SINT to larger FP_TO_SINTS's, as X86 doesn't have
215   // this operation.
216   setOperationAction(ISD::FP_TO_SINT       , MVT::i1   , Promote);
217   setOperationAction(ISD::FP_TO_SINT       , MVT::i8   , Promote);
218
219   if (X86ScalarSSEf32) {
220     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Promote);
221     // f32 and f64 cases are Legal, f80 case is not
222     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
223   } else {
224     setOperationAction(ISD::FP_TO_SINT     , MVT::i16  , Custom);
225     setOperationAction(ISD::FP_TO_SINT     , MVT::i32  , Custom);
226   }
227
228   // Handle FP_TO_UINT by promoting the destination to a larger signed
229   // conversion.
230   setOperationAction(ISD::FP_TO_UINT       , MVT::i1   , Promote);
231   setOperationAction(ISD::FP_TO_UINT       , MVT::i8   , Promote);
232   setOperationAction(ISD::FP_TO_UINT       , MVT::i16  , Promote);
233
234   if (Subtarget->is64Bit()) {
235     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Expand);
236     setOperationAction(ISD::FP_TO_UINT     , MVT::i32  , Promote);
237   } else if (!Subtarget->useSoftFloat()) {
238     // Since AVX is a superset of SSE3, only check for SSE here.
239     if (Subtarget->hasSSE1() && !Subtarget->hasSSE3())
240       // Expand FP_TO_UINT into a select.
241       // FIXME: We would like to use a Custom expander here eventually to do
242       // the optimal thing for SSE vs. the default expansion in the legalizer.
243       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Expand);
244     else
245       // With SSE3 we can use fisttpll to convert to a signed i64; without
246       // SSE, we're stuck with a fistpll.
247       setOperationAction(ISD::FP_TO_UINT   , MVT::i32  , Custom);
248   }
249
250   if (isTargetFTOL()) {
251     // Use the _ftol2 runtime function, which has a pseudo-instruction
252     // to handle its weird calling convention.
253     setOperationAction(ISD::FP_TO_UINT     , MVT::i64  , Custom);
254   }
255
256   // TODO: when we have SSE, these could be more efficient, by using movd/movq.
257   if (!X86ScalarSSEf64) {
258     setOperationAction(ISD::BITCAST        , MVT::f32  , Expand);
259     setOperationAction(ISD::BITCAST        , MVT::i32  , Expand);
260     if (Subtarget->is64Bit()) {
261       setOperationAction(ISD::BITCAST      , MVT::f64  , Expand);
262       // Without SSE, i64->f64 goes through memory.
263       setOperationAction(ISD::BITCAST      , MVT::i64  , Expand);
264     }
265   }
266
267   // Scalar integer divide and remainder are lowered to use operations that
268   // produce two results, to match the available instructions. This exposes
269   // the two-result form to trivial CSE, which is able to combine x/y and x%y
270   // into a single instruction.
271   //
272   // Scalar integer multiply-high is also lowered to use two-result
273   // operations, to match the available instructions. However, plain multiply
274   // (low) operations are left as Legal, as there are single-result
275   // instructions for this in x86. Using the two-result multiply instructions
276   // when both high and low results are needed must be arranged by dagcombine.
277   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
278     MVT VT = IntVTs[i];
279     setOperationAction(ISD::MULHS, VT, Expand);
280     setOperationAction(ISD::MULHU, VT, Expand);
281     setOperationAction(ISD::SDIV, VT, Expand);
282     setOperationAction(ISD::UDIV, VT, Expand);
283     setOperationAction(ISD::SREM, VT, Expand);
284     setOperationAction(ISD::UREM, VT, Expand);
285
286     // Add/Sub overflow ops with MVT::Glues are lowered to EFLAGS dependences.
287     setOperationAction(ISD::ADDC, VT, Custom);
288     setOperationAction(ISD::ADDE, VT, Custom);
289     setOperationAction(ISD::SUBC, VT, Custom);
290     setOperationAction(ISD::SUBE, VT, Custom);
291   }
292
293   setOperationAction(ISD::BR_JT            , MVT::Other, Expand);
294   setOperationAction(ISD::BRCOND           , MVT::Other, Custom);
295   setOperationAction(ISD::BR_CC            , MVT::f32,   Expand);
296   setOperationAction(ISD::BR_CC            , MVT::f64,   Expand);
297   setOperationAction(ISD::BR_CC            , MVT::f80,   Expand);
298   setOperationAction(ISD::BR_CC            , MVT::i8,    Expand);
299   setOperationAction(ISD::BR_CC            , MVT::i16,   Expand);
300   setOperationAction(ISD::BR_CC            , MVT::i32,   Expand);
301   setOperationAction(ISD::BR_CC            , MVT::i64,   Expand);
302   setOperationAction(ISD::SELECT_CC        , MVT::f32,   Expand);
303   setOperationAction(ISD::SELECT_CC        , MVT::f64,   Expand);
304   setOperationAction(ISD::SELECT_CC        , MVT::f80,   Expand);
305   setOperationAction(ISD::SELECT_CC        , MVT::i8,    Expand);
306   setOperationAction(ISD::SELECT_CC        , MVT::i16,   Expand);
307   setOperationAction(ISD::SELECT_CC        , MVT::i32,   Expand);
308   setOperationAction(ISD::SELECT_CC        , MVT::i64,   Expand);
309   if (Subtarget->is64Bit())
310     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i32, Legal);
311   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16  , Legal);
312   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8   , Legal);
313   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1   , Expand);
314   setOperationAction(ISD::FP_ROUND_INREG   , MVT::f32  , Expand);
315   setOperationAction(ISD::FREM             , MVT::f32  , Expand);
316   setOperationAction(ISD::FREM             , MVT::f64  , Expand);
317   setOperationAction(ISD::FREM             , MVT::f80  , Expand);
318   setOperationAction(ISD::FLT_ROUNDS_      , MVT::i32  , Custom);
319
320   // Promote the i8 variants and force them on up to i32 which has a shorter
321   // encoding.
322   setOperationAction(ISD::CTTZ             , MVT::i8   , Promote);
323   AddPromotedToType (ISD::CTTZ             , MVT::i8   , MVT::i32);
324   setOperationAction(ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , Promote);
325   AddPromotedToType (ISD::CTTZ_ZERO_UNDEF  , MVT::i8   , MVT::i32);
326   if (Subtarget->hasBMI()) {
327     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i16  , Expand);
328     setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32  , Expand);
329     if (Subtarget->is64Bit())
330       setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331   } else {
332     setOperationAction(ISD::CTTZ           , MVT::i16  , Custom);
333     setOperationAction(ISD::CTTZ           , MVT::i32  , Custom);
334     if (Subtarget->is64Bit())
335       setOperationAction(ISD::CTTZ         , MVT::i64  , Custom);
336   }
337
338   if (Subtarget->hasLZCNT()) {
339     // When promoting the i8 variants, force them to i32 for a shorter
340     // encoding.
341     setOperationAction(ISD::CTLZ           , MVT::i8   , Promote);
342     AddPromotedToType (ISD::CTLZ           , MVT::i8   , MVT::i32);
343     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Promote);
344     AddPromotedToType (ISD::CTLZ_ZERO_UNDEF, MVT::i8   , MVT::i32);
345     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Expand);
346     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Expand);
347     if (Subtarget->is64Bit())
348       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
349   } else {
350     setOperationAction(ISD::CTLZ           , MVT::i8   , Custom);
351     setOperationAction(ISD::CTLZ           , MVT::i16  , Custom);
352     setOperationAction(ISD::CTLZ           , MVT::i32  , Custom);
353     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i8   , Custom);
354     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i16  , Custom);
355     setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32  , Custom);
356     if (Subtarget->is64Bit()) {
357       setOperationAction(ISD::CTLZ         , MVT::i64  , Custom);
358       setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Custom);
359     }
360   }
361
362   // Special handling for half-precision floating point conversions.
363   // If we don't have F16C support, then lower half float conversions
364   // into library calls.
365   if (Subtarget->useSoftFloat() || !Subtarget->hasF16C()) {
366     setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
367     setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
368   }
369
370   // There's never any support for operations beyond MVT::f32.
371   setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
372   setOperationAction(ISD::FP16_TO_FP, MVT::f80, Expand);
373   setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
374   setOperationAction(ISD::FP_TO_FP16, MVT::f80, Expand);
375
376   setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
377   setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
378   setLoadExtAction(ISD::EXTLOAD, MVT::f80, MVT::f16, Expand);
379   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
380   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
381   setTruncStoreAction(MVT::f80, MVT::f16, Expand);
382
383   if (Subtarget->hasPOPCNT()) {
384     setOperationAction(ISD::CTPOP          , MVT::i8   , Promote);
385   } else {
386     setOperationAction(ISD::CTPOP          , MVT::i8   , Expand);
387     setOperationAction(ISD::CTPOP          , MVT::i16  , Expand);
388     setOperationAction(ISD::CTPOP          , MVT::i32  , Expand);
389     if (Subtarget->is64Bit())
390       setOperationAction(ISD::CTPOP        , MVT::i64  , Expand);
391   }
392
393   setOperationAction(ISD::READCYCLECOUNTER , MVT::i64  , Custom);
394
395   if (!Subtarget->hasMOVBE())
396     setOperationAction(ISD::BSWAP          , MVT::i16  , Expand);
397
398   // These should be promoted to a larger select which is supported.
399   setOperationAction(ISD::SELECT          , MVT::i1   , Promote);
400   // X86 wants to expand cmov itself.
401   setOperationAction(ISD::SELECT          , MVT::i8   , Custom);
402   setOperationAction(ISD::SELECT          , MVT::i16  , Custom);
403   setOperationAction(ISD::SELECT          , MVT::i32  , Custom);
404   setOperationAction(ISD::SELECT          , MVT::f32  , Custom);
405   setOperationAction(ISD::SELECT          , MVT::f64  , Custom);
406   setOperationAction(ISD::SELECT          , MVT::f80  , Custom);
407   setOperationAction(ISD::SETCC           , MVT::i8   , Custom);
408   setOperationAction(ISD::SETCC           , MVT::i16  , Custom);
409   setOperationAction(ISD::SETCC           , MVT::i32  , Custom);
410   setOperationAction(ISD::SETCC           , MVT::f32  , Custom);
411   setOperationAction(ISD::SETCC           , MVT::f64  , Custom);
412   setOperationAction(ISD::SETCC           , MVT::f80  , Custom);
413   if (Subtarget->is64Bit()) {
414     setOperationAction(ISD::SELECT        , MVT::i64  , Custom);
415     setOperationAction(ISD::SETCC         , MVT::i64  , Custom);
416   }
417   setOperationAction(ISD::EH_RETURN       , MVT::Other, Custom);
418   // NOTE: EH_SJLJ_SETJMP/_LONGJMP supported here is NOT intended to support
419   // SjLj exception handling but a light-weight setjmp/longjmp replacement to
420   // support continuation, user-level threading, and etc.. As a result, no
421   // other SjLj exception interfaces are implemented and please don't build
422   // your own exception handling based on them.
423   // LLVM/Clang supports zero-cost DWARF exception handling.
424   setOperationAction(ISD::EH_SJLJ_SETJMP, MVT::i32, Custom);
425   setOperationAction(ISD::EH_SJLJ_LONGJMP, MVT::Other, Custom);
426
427   // Darwin ABI issue.
428   setOperationAction(ISD::ConstantPool    , MVT::i32  , Custom);
429   setOperationAction(ISD::JumpTable       , MVT::i32  , Custom);
430   setOperationAction(ISD::GlobalAddress   , MVT::i32  , Custom);
431   setOperationAction(ISD::GlobalTLSAddress, MVT::i32  , Custom);
432   if (Subtarget->is64Bit())
433     setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
434   setOperationAction(ISD::ExternalSymbol  , MVT::i32  , Custom);
435   setOperationAction(ISD::BlockAddress    , MVT::i32  , Custom);
436   if (Subtarget->is64Bit()) {
437     setOperationAction(ISD::ConstantPool  , MVT::i64  , Custom);
438     setOperationAction(ISD::JumpTable     , MVT::i64  , Custom);
439     setOperationAction(ISD::GlobalAddress , MVT::i64  , Custom);
440     setOperationAction(ISD::ExternalSymbol, MVT::i64  , Custom);
441     setOperationAction(ISD::BlockAddress  , MVT::i64  , Custom);
442   }
443   // 64-bit addm sub, shl, sra, srl (iff 32-bit x86)
444   setOperationAction(ISD::SHL_PARTS       , MVT::i32  , Custom);
445   setOperationAction(ISD::SRA_PARTS       , MVT::i32  , Custom);
446   setOperationAction(ISD::SRL_PARTS       , MVT::i32  , Custom);
447   if (Subtarget->is64Bit()) {
448     setOperationAction(ISD::SHL_PARTS     , MVT::i64  , Custom);
449     setOperationAction(ISD::SRA_PARTS     , MVT::i64  , Custom);
450     setOperationAction(ISD::SRL_PARTS     , MVT::i64  , Custom);
451   }
452
453   if (Subtarget->hasSSE1())
454     setOperationAction(ISD::PREFETCH      , MVT::Other, Legal);
455
456   setOperationAction(ISD::ATOMIC_FENCE  , MVT::Other, Custom);
457
458   // Expand certain atomics
459   for (unsigned i = 0; i != array_lengthof(IntVTs); ++i) {
460     MVT VT = IntVTs[i];
461     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, VT, Custom);
462     setOperationAction(ISD::ATOMIC_LOAD_SUB, VT, Custom);
463     setOperationAction(ISD::ATOMIC_STORE, VT, Custom);
464   }
465
466   if (Subtarget->hasCmpxchg16b()) {
467     setOperationAction(ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS, MVT::i128, Custom);
468   }
469
470   // FIXME - use subtarget debug flags
471   if (!Subtarget->isTargetDarwin() && !Subtarget->isTargetELF() &&
472       !Subtarget->isTargetCygMing() && !Subtarget->isTargetWin64()) {
473     setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
474   }
475
476   if (Subtarget->is64Bit()) {
477     setExceptionPointerRegister(X86::RAX);
478     setExceptionSelectorRegister(X86::RDX);
479   } else {
480     setExceptionPointerRegister(X86::EAX);
481     setExceptionSelectorRegister(X86::EDX);
482   }
483   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i32, Custom);
484   setOperationAction(ISD::FRAME_TO_ARGS_OFFSET, MVT::i64, Custom);
485
486   setOperationAction(ISD::INIT_TRAMPOLINE, MVT::Other, Custom);
487   setOperationAction(ISD::ADJUST_TRAMPOLINE, MVT::Other, Custom);
488
489   setOperationAction(ISD::TRAP, MVT::Other, Legal);
490   setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
491
492   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
493   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
494   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
495   if (Subtarget->is64Bit() && !Subtarget->isTargetWin64()) {
496     // TargetInfo::X86_64ABIBuiltinVaList
497     setOperationAction(ISD::VAARG           , MVT::Other, Custom);
498     setOperationAction(ISD::VACOPY          , MVT::Other, Custom);
499   } else {
500     // TargetInfo::CharPtrBuiltinVaList
501     setOperationAction(ISD::VAARG           , MVT::Other, Expand);
502     setOperationAction(ISD::VACOPY          , MVT::Other, Expand);
503   }
504
505   setOperationAction(ISD::STACKSAVE,          MVT::Other, Expand);
506   setOperationAction(ISD::STACKRESTORE,       MVT::Other, Expand);
507
508   setOperationAction(ISD::DYNAMIC_STACKALLOC, getPointerTy(), Custom);
509
510   // GC_TRANSITION_START and GC_TRANSITION_END need custom lowering.
511   setOperationAction(ISD::GC_TRANSITION_START, MVT::Other, Custom);
512   setOperationAction(ISD::GC_TRANSITION_END, MVT::Other, Custom);
513
514   if (!Subtarget->useSoftFloat() && X86ScalarSSEf64) {
515     // f32 and f64 use SSE.
516     // Set up the FP register classes.
517     addRegisterClass(MVT::f32, &X86::FR32RegClass);
518     addRegisterClass(MVT::f64, &X86::FR64RegClass);
519
520     // Use ANDPD to simulate FABS.
521     setOperationAction(ISD::FABS , MVT::f64, Custom);
522     setOperationAction(ISD::FABS , MVT::f32, Custom);
523
524     // Use XORP to simulate FNEG.
525     setOperationAction(ISD::FNEG , MVT::f64, Custom);
526     setOperationAction(ISD::FNEG , MVT::f32, Custom);
527
528     // Use ANDPD and ORPD to simulate FCOPYSIGN.
529     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
530     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
531
532     // Lower this to FGETSIGNx86 plus an AND.
533     setOperationAction(ISD::FGETSIGN, MVT::i64, Custom);
534     setOperationAction(ISD::FGETSIGN, MVT::i32, Custom);
535
536     // We don't support sin/cos/fmod
537     setOperationAction(ISD::FSIN   , MVT::f64, Expand);
538     setOperationAction(ISD::FCOS   , MVT::f64, Expand);
539     setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
540     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
541     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
542     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
543
544     // Expand FP immediates into loads from the stack, except for the special
545     // cases we handle.
546     addLegalFPImmediate(APFloat(+0.0)); // xorpd
547     addLegalFPImmediate(APFloat(+0.0f)); // xorps
548   } else if (!Subtarget->useSoftFloat() && X86ScalarSSEf32) {
549     // Use SSE for f32, x87 for f64.
550     // Set up the FP register classes.
551     addRegisterClass(MVT::f32, &X86::FR32RegClass);
552     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
553
554     // Use ANDPS to simulate FABS.
555     setOperationAction(ISD::FABS , MVT::f32, Custom);
556
557     // Use XORP to simulate FNEG.
558     setOperationAction(ISD::FNEG , MVT::f32, Custom);
559
560     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
561
562     // Use ANDPS and ORPS to simulate FCOPYSIGN.
563     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
564     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
565
566     // We don't support sin/cos/fmod
567     setOperationAction(ISD::FSIN   , MVT::f32, Expand);
568     setOperationAction(ISD::FCOS   , MVT::f32, Expand);
569     setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
570
571     // Special cases we handle for FP constants.
572     addLegalFPImmediate(APFloat(+0.0f)); // xorps
573     addLegalFPImmediate(APFloat(+0.0)); // FLD0
574     addLegalFPImmediate(APFloat(+1.0)); // FLD1
575     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
576     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
577
578     if (!TM.Options.UnsafeFPMath) {
579       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
580       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
581       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
582     }
583   } else if (!Subtarget->useSoftFloat()) {
584     // f32 and f64 in x87.
585     // Set up the FP register classes.
586     addRegisterClass(MVT::f64, &X86::RFP64RegClass);
587     addRegisterClass(MVT::f32, &X86::RFP32RegClass);
588
589     setOperationAction(ISD::UNDEF,     MVT::f64, Expand);
590     setOperationAction(ISD::UNDEF,     MVT::f32, Expand);
591     setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
592     setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
593
594     if (!TM.Options.UnsafeFPMath) {
595       setOperationAction(ISD::FSIN   , MVT::f64, Expand);
596       setOperationAction(ISD::FSIN   , MVT::f32, Expand);
597       setOperationAction(ISD::FCOS   , MVT::f64, Expand);
598       setOperationAction(ISD::FCOS   , MVT::f32, Expand);
599       setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
600       setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
601     }
602     addLegalFPImmediate(APFloat(+0.0)); // FLD0
603     addLegalFPImmediate(APFloat(+1.0)); // FLD1
604     addLegalFPImmediate(APFloat(-0.0)); // FLD0/FCHS
605     addLegalFPImmediate(APFloat(-1.0)); // FLD1/FCHS
606     addLegalFPImmediate(APFloat(+0.0f)); // FLD0
607     addLegalFPImmediate(APFloat(+1.0f)); // FLD1
608     addLegalFPImmediate(APFloat(-0.0f)); // FLD0/FCHS
609     addLegalFPImmediate(APFloat(-1.0f)); // FLD1/FCHS
610   }
611
612   // We don't support FMA.
613   setOperationAction(ISD::FMA, MVT::f64, Expand);
614   setOperationAction(ISD::FMA, MVT::f32, Expand);
615
616   // Long double always uses X87.
617   if (!Subtarget->useSoftFloat()) {
618     addRegisterClass(MVT::f80, &X86::RFP80RegClass);
619     setOperationAction(ISD::UNDEF,     MVT::f80, Expand);
620     setOperationAction(ISD::FCOPYSIGN, MVT::f80, Expand);
621     {
622       APFloat TmpFlt = APFloat::getZero(APFloat::x87DoubleExtended);
623       addLegalFPImmediate(TmpFlt);  // FLD0
624       TmpFlt.changeSign();
625       addLegalFPImmediate(TmpFlt);  // FLD0/FCHS
626
627       bool ignored;
628       APFloat TmpFlt2(+1.0);
629       TmpFlt2.convert(APFloat::x87DoubleExtended, APFloat::rmNearestTiesToEven,
630                       &ignored);
631       addLegalFPImmediate(TmpFlt2);  // FLD1
632       TmpFlt2.changeSign();
633       addLegalFPImmediate(TmpFlt2);  // FLD1/FCHS
634     }
635
636     if (!TM.Options.UnsafeFPMath) {
637       setOperationAction(ISD::FSIN   , MVT::f80, Expand);
638       setOperationAction(ISD::FCOS   , MVT::f80, Expand);
639       setOperationAction(ISD::FSINCOS, MVT::f80, Expand);
640     }
641
642     setOperationAction(ISD::FFLOOR, MVT::f80, Expand);
643     setOperationAction(ISD::FCEIL,  MVT::f80, Expand);
644     setOperationAction(ISD::FTRUNC, MVT::f80, Expand);
645     setOperationAction(ISD::FRINT,  MVT::f80, Expand);
646     setOperationAction(ISD::FNEARBYINT, MVT::f80, Expand);
647     setOperationAction(ISD::FMA, MVT::f80, Expand);
648   }
649
650   // Always use a library call for pow.
651   setOperationAction(ISD::FPOW             , MVT::f32  , Expand);
652   setOperationAction(ISD::FPOW             , MVT::f64  , Expand);
653   setOperationAction(ISD::FPOW             , MVT::f80  , Expand);
654
655   setOperationAction(ISD::FLOG, MVT::f80, Expand);
656   setOperationAction(ISD::FLOG2, MVT::f80, Expand);
657   setOperationAction(ISD::FLOG10, MVT::f80, Expand);
658   setOperationAction(ISD::FEXP, MVT::f80, Expand);
659   setOperationAction(ISD::FEXP2, MVT::f80, Expand);
660   setOperationAction(ISD::FMINNUM, MVT::f80, Expand);
661   setOperationAction(ISD::FMAXNUM, MVT::f80, Expand);
662
663   // First set operation action for all vector types to either promote
664   // (for widening) or expand (for scalarization). Then we will selectively
665   // turn on ones that can be effectively codegen'd.
666   for (MVT VT : MVT::vector_valuetypes()) {
667     setOperationAction(ISD::ADD , VT, Expand);
668     setOperationAction(ISD::SUB , VT, Expand);
669     setOperationAction(ISD::FADD, VT, Expand);
670     setOperationAction(ISD::FNEG, VT, Expand);
671     setOperationAction(ISD::FSUB, VT, Expand);
672     setOperationAction(ISD::MUL , VT, Expand);
673     setOperationAction(ISD::FMUL, VT, Expand);
674     setOperationAction(ISD::SDIV, VT, Expand);
675     setOperationAction(ISD::UDIV, VT, Expand);
676     setOperationAction(ISD::FDIV, VT, Expand);
677     setOperationAction(ISD::SREM, VT, Expand);
678     setOperationAction(ISD::UREM, VT, Expand);
679     setOperationAction(ISD::LOAD, VT, Expand);
680     setOperationAction(ISD::VECTOR_SHUFFLE, VT, Expand);
681     setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT,Expand);
682     setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Expand);
683     setOperationAction(ISD::EXTRACT_SUBVECTOR, VT,Expand);
684     setOperationAction(ISD::INSERT_SUBVECTOR, VT,Expand);
685     setOperationAction(ISD::FABS, VT, Expand);
686     setOperationAction(ISD::FSIN, VT, Expand);
687     setOperationAction(ISD::FSINCOS, VT, Expand);
688     setOperationAction(ISD::FCOS, VT, Expand);
689     setOperationAction(ISD::FSINCOS, VT, Expand);
690     setOperationAction(ISD::FREM, VT, Expand);
691     setOperationAction(ISD::FMA,  VT, Expand);
692     setOperationAction(ISD::FPOWI, VT, Expand);
693     setOperationAction(ISD::FSQRT, VT, Expand);
694     setOperationAction(ISD::FCOPYSIGN, VT, Expand);
695     setOperationAction(ISD::FFLOOR, VT, Expand);
696     setOperationAction(ISD::FCEIL, VT, Expand);
697     setOperationAction(ISD::FTRUNC, VT, Expand);
698     setOperationAction(ISD::FRINT, VT, Expand);
699     setOperationAction(ISD::FNEARBYINT, VT, Expand);
700     setOperationAction(ISD::SMUL_LOHI, VT, Expand);
701     setOperationAction(ISD::MULHS, VT, Expand);
702     setOperationAction(ISD::UMUL_LOHI, VT, Expand);
703     setOperationAction(ISD::MULHU, VT, Expand);
704     setOperationAction(ISD::SDIVREM, VT, Expand);
705     setOperationAction(ISD::UDIVREM, VT, Expand);
706     setOperationAction(ISD::FPOW, VT, Expand);
707     setOperationAction(ISD::CTPOP, VT, Expand);
708     setOperationAction(ISD::CTTZ, VT, Expand);
709     setOperationAction(ISD::CTTZ_ZERO_UNDEF, VT, Expand);
710     setOperationAction(ISD::CTLZ, VT, Expand);
711     setOperationAction(ISD::CTLZ_ZERO_UNDEF, VT, Expand);
712     setOperationAction(ISD::SHL, VT, Expand);
713     setOperationAction(ISD::SRA, VT, Expand);
714     setOperationAction(ISD::SRL, VT, Expand);
715     setOperationAction(ISD::ROTL, VT, Expand);
716     setOperationAction(ISD::ROTR, VT, Expand);
717     setOperationAction(ISD::BSWAP, VT, Expand);
718     setOperationAction(ISD::SETCC, VT, Expand);
719     setOperationAction(ISD::FLOG, VT, Expand);
720     setOperationAction(ISD::FLOG2, VT, Expand);
721     setOperationAction(ISD::FLOG10, VT, Expand);
722     setOperationAction(ISD::FEXP, VT, Expand);
723     setOperationAction(ISD::FEXP2, VT, Expand);
724     setOperationAction(ISD::FP_TO_UINT, VT, Expand);
725     setOperationAction(ISD::FP_TO_SINT, VT, Expand);
726     setOperationAction(ISD::UINT_TO_FP, VT, Expand);
727     setOperationAction(ISD::SINT_TO_FP, VT, Expand);
728     setOperationAction(ISD::SIGN_EXTEND_INREG, VT,Expand);
729     setOperationAction(ISD::TRUNCATE, VT, Expand);
730     setOperationAction(ISD::SIGN_EXTEND, VT, Expand);
731     setOperationAction(ISD::ZERO_EXTEND, VT, Expand);
732     setOperationAction(ISD::ANY_EXTEND, VT, Expand);
733     setOperationAction(ISD::VSELECT, VT, Expand);
734     setOperationAction(ISD::SELECT_CC, VT, Expand);
735     for (MVT InnerVT : MVT::vector_valuetypes()) {
736       setTruncStoreAction(InnerVT, VT, Expand);
737
738       setLoadExtAction(ISD::SEXTLOAD, InnerVT, VT, Expand);
739       setLoadExtAction(ISD::ZEXTLOAD, InnerVT, VT, Expand);
740
741       // N.b. ISD::EXTLOAD legality is basically ignored except for i1-like
742       // types, we have to deal with them whether we ask for Expansion or not.
743       // Setting Expand causes its own optimisation problems though, so leave
744       // them legal.
745       if (VT.getVectorElementType() == MVT::i1)
746         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
747
748       // EXTLOAD for MVT::f16 vectors is not legal because f16 vectors are
749       // split/scalarized right now.
750       if (VT.getVectorElementType() == MVT::f16)
751         setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
752     }
753   }
754
755   // FIXME: In order to prevent SSE instructions being expanded to MMX ones
756   // with -msoft-float, disable use of MMX as well.
757   if (!Subtarget->useSoftFloat() && Subtarget->hasMMX()) {
758     addRegisterClass(MVT::x86mmx, &X86::VR64RegClass);
759     // No operations on x86mmx supported, everything uses intrinsics.
760   }
761
762   // MMX-sized vectors (other than x86mmx) are expected to be expanded
763   // into smaller operations.
764   for (MVT MMXTy : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v1i64}) {
765     setOperationAction(ISD::MULHS,              MMXTy,      Expand);
766     setOperationAction(ISD::AND,                MMXTy,      Expand);
767     setOperationAction(ISD::OR,                 MMXTy,      Expand);
768     setOperationAction(ISD::XOR,                MMXTy,      Expand);
769     setOperationAction(ISD::SCALAR_TO_VECTOR,   MMXTy,      Expand);
770     setOperationAction(ISD::SELECT,             MMXTy,      Expand);
771     setOperationAction(ISD::BITCAST,            MMXTy,      Expand);
772   }
773   setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v1i64, Expand);
774
775   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE1()) {
776     addRegisterClass(MVT::v4f32, &X86::VR128RegClass);
777
778     setOperationAction(ISD::FADD,               MVT::v4f32, Legal);
779     setOperationAction(ISD::FSUB,               MVT::v4f32, Legal);
780     setOperationAction(ISD::FMUL,               MVT::v4f32, Legal);
781     setOperationAction(ISD::FDIV,               MVT::v4f32, Legal);
782     setOperationAction(ISD::FSQRT,              MVT::v4f32, Legal);
783     setOperationAction(ISD::FNEG,               MVT::v4f32, Custom);
784     setOperationAction(ISD::FABS,               MVT::v4f32, Custom);
785     setOperationAction(ISD::LOAD,               MVT::v4f32, Legal);
786     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4f32, Custom);
787     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v4f32, Custom);
788     setOperationAction(ISD::VSELECT,            MVT::v4f32, Custom);
789     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
790     setOperationAction(ISD::SELECT,             MVT::v4f32, Custom);
791     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Custom);
792   }
793
794   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE2()) {
795     addRegisterClass(MVT::v2f64, &X86::VR128RegClass);
796
797     // FIXME: Unfortunately, -soft-float and -no-implicit-float mean XMM
798     // registers cannot be used even for integer operations.
799     addRegisterClass(MVT::v16i8, &X86::VR128RegClass);
800     addRegisterClass(MVT::v8i16, &X86::VR128RegClass);
801     addRegisterClass(MVT::v4i32, &X86::VR128RegClass);
802     addRegisterClass(MVT::v2i64, &X86::VR128RegClass);
803
804     setOperationAction(ISD::ADD,                MVT::v16i8, Legal);
805     setOperationAction(ISD::ADD,                MVT::v8i16, Legal);
806     setOperationAction(ISD::ADD,                MVT::v4i32, Legal);
807     setOperationAction(ISD::ADD,                MVT::v2i64, Legal);
808     setOperationAction(ISD::MUL,                MVT::v16i8, Custom);
809     setOperationAction(ISD::MUL,                MVT::v4i32, Custom);
810     setOperationAction(ISD::MUL,                MVT::v2i64, Custom);
811     setOperationAction(ISD::UMUL_LOHI,          MVT::v4i32, Custom);
812     setOperationAction(ISD::SMUL_LOHI,          MVT::v4i32, Custom);
813     setOperationAction(ISD::MULHU,              MVT::v8i16, Legal);
814     setOperationAction(ISD::MULHS,              MVT::v8i16, Legal);
815     setOperationAction(ISD::SUB,                MVT::v16i8, Legal);
816     setOperationAction(ISD::SUB,                MVT::v8i16, Legal);
817     setOperationAction(ISD::SUB,                MVT::v4i32, Legal);
818     setOperationAction(ISD::SUB,                MVT::v2i64, Legal);
819     setOperationAction(ISD::MUL,                MVT::v8i16, Legal);
820     setOperationAction(ISD::FADD,               MVT::v2f64, Legal);
821     setOperationAction(ISD::FSUB,               MVT::v2f64, Legal);
822     setOperationAction(ISD::FMUL,               MVT::v2f64, Legal);
823     setOperationAction(ISD::FDIV,               MVT::v2f64, Legal);
824     setOperationAction(ISD::FSQRT,              MVT::v2f64, Legal);
825     setOperationAction(ISD::FNEG,               MVT::v2f64, Custom);
826     setOperationAction(ISD::FABS,               MVT::v2f64, Custom);
827
828     setOperationAction(ISD::SMAX,               MVT::v8i16, Legal);
829     setOperationAction(ISD::UMAX,               MVT::v16i8, Legal);
830     setOperationAction(ISD::SMIN,               MVT::v8i16, Legal);
831     setOperationAction(ISD::UMIN,               MVT::v16i8, Legal);
832
833     setOperationAction(ISD::SETCC,              MVT::v2i64, Custom);
834     setOperationAction(ISD::SETCC,              MVT::v16i8, Custom);
835     setOperationAction(ISD::SETCC,              MVT::v8i16, Custom);
836     setOperationAction(ISD::SETCC,              MVT::v4i32, Custom);
837
838     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v16i8, Custom);
839     setOperationAction(ISD::SCALAR_TO_VECTOR,   MVT::v8i16, Custom);
840     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
841     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
842     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
843
844     setOperationAction(ISD::CTPOP,              MVT::v16i8, Custom);
845     setOperationAction(ISD::CTPOP,              MVT::v8i16, Custom);
846     setOperationAction(ISD::CTPOP,              MVT::v4i32, Custom);
847     setOperationAction(ISD::CTPOP,              MVT::v2i64, Custom);
848
849     // Custom lower build_vector, vector_shuffle, and extract_vector_elt.
850     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
851       MVT VT = (MVT::SimpleValueType)i;
852       // Do not attempt to custom lower non-power-of-2 vectors
853       if (!isPowerOf2_32(VT.getVectorNumElements()))
854         continue;
855       // Do not attempt to custom lower non-128-bit vectors
856       if (!VT.is128BitVector())
857         continue;
858       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
859       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
860       setOperationAction(ISD::VSELECT,            VT, Custom);
861       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
862     }
863
864     // We support custom legalizing of sext and anyext loads for specific
865     // memory vector types which we can load as a scalar (or sequence of
866     // scalars) and extend in-register to a legal 128-bit vector type. For sext
867     // loads these must work with a single scalar load.
868     for (MVT VT : MVT::integer_vector_valuetypes()) {
869       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i8, Custom);
870       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v4i16, Custom);
871       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v8i8, Custom);
872       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i8, Custom);
873       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i16, Custom);
874       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2i32, Custom);
875       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i8, Custom);
876       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4i16, Custom);
877       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8i8, Custom);
878     }
879
880     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2f64, Custom);
881     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i64, Custom);
882     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2f64, Custom);
883     setOperationAction(ISD::VECTOR_SHUFFLE,     MVT::v2i64, Custom);
884     setOperationAction(ISD::VSELECT,            MVT::v2f64, Custom);
885     setOperationAction(ISD::VSELECT,            MVT::v2i64, Custom);
886     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2f64, Custom);
887     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2f64, Custom);
888
889     if (Subtarget->is64Bit()) {
890       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
891       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
892     }
893
894     // Promote v16i8, v8i16, v4i32 load, select, and, or, xor to v2i64.
895     for (int i = MVT::v16i8; i != MVT::v2i64; ++i) {
896       MVT VT = (MVT::SimpleValueType)i;
897
898       // Do not attempt to promote non-128-bit vectors
899       if (!VT.is128BitVector())
900         continue;
901
902       setOperationAction(ISD::AND,    VT, Promote);
903       AddPromotedToType (ISD::AND,    VT, MVT::v2i64);
904       setOperationAction(ISD::OR,     VT, Promote);
905       AddPromotedToType (ISD::OR,     VT, MVT::v2i64);
906       setOperationAction(ISD::XOR,    VT, Promote);
907       AddPromotedToType (ISD::XOR,    VT, MVT::v2i64);
908       setOperationAction(ISD::LOAD,   VT, Promote);
909       AddPromotedToType (ISD::LOAD,   VT, MVT::v2i64);
910       setOperationAction(ISD::SELECT, VT, Promote);
911       AddPromotedToType (ISD::SELECT, VT, MVT::v2i64);
912     }
913
914     // Custom lower v2i64 and v2f64 selects.
915     setOperationAction(ISD::LOAD,               MVT::v2f64, Legal);
916     setOperationAction(ISD::LOAD,               MVT::v2i64, Legal);
917     setOperationAction(ISD::SELECT,             MVT::v2f64, Custom);
918     setOperationAction(ISD::SELECT,             MVT::v2i64, Custom);
919
920     setOperationAction(ISD::FP_TO_SINT,         MVT::v4i32, Legal);
921     setOperationAction(ISD::SINT_TO_FP,         MVT::v4i32, Legal);
922
923     setOperationAction(ISD::SINT_TO_FP,         MVT::v2i32, Custom);
924
925     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i8,  Custom);
926     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i16, Custom);
927     // As there is no 64-bit GPR available, we need build a special custom
928     // sequence to convert from v2i32 to v2f32.
929     if (!Subtarget->is64Bit())
930       setOperationAction(ISD::UINT_TO_FP,       MVT::v2f32, Custom);
931
932     setOperationAction(ISD::FP_EXTEND,          MVT::v2f32, Custom);
933     setOperationAction(ISD::FP_ROUND,           MVT::v2f32, Custom);
934
935     for (MVT VT : MVT::fp_vector_valuetypes())
936       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v2f32, Legal);
937
938     setOperationAction(ISD::BITCAST,            MVT::v2i32, Custom);
939     setOperationAction(ISD::BITCAST,            MVT::v4i16, Custom);
940     setOperationAction(ISD::BITCAST,            MVT::v8i8,  Custom);
941   }
942
943   if (!Subtarget->useSoftFloat() && Subtarget->hasSSE41()) {
944     for (MVT RoundedTy : {MVT::f32, MVT::f64, MVT::v4f32, MVT::v2f64}) {
945       setOperationAction(ISD::FFLOOR,           RoundedTy,  Legal);
946       setOperationAction(ISD::FCEIL,            RoundedTy,  Legal);
947       setOperationAction(ISD::FTRUNC,           RoundedTy,  Legal);
948       setOperationAction(ISD::FRINT,            RoundedTy,  Legal);
949       setOperationAction(ISD::FNEARBYINT,       RoundedTy,  Legal);
950     }
951
952     setOperationAction(ISD::SMAX,               MVT::v16i8, Legal);
953     setOperationAction(ISD::SMAX,               MVT::v4i32, Legal);
954     setOperationAction(ISD::UMAX,               MVT::v8i16, Legal);
955     setOperationAction(ISD::UMAX,               MVT::v4i32, Legal);
956     setOperationAction(ISD::SMIN,               MVT::v16i8, Legal);
957     setOperationAction(ISD::SMIN,               MVT::v4i32, Legal);
958     setOperationAction(ISD::UMIN,               MVT::v8i16, Legal);
959     setOperationAction(ISD::UMIN,               MVT::v4i32, Legal);
960
961     // FIXME: Do we need to handle scalar-to-vector here?
962     setOperationAction(ISD::MUL,                MVT::v4i32, Legal);
963
964     // We directly match byte blends in the backend as they match the VSELECT
965     // condition form.
966     setOperationAction(ISD::VSELECT,            MVT::v16i8, Legal);
967
968     // SSE41 brings specific instructions for doing vector sign extend even in
969     // cases where we don't have SRA.
970     for (MVT VT : MVT::integer_vector_valuetypes()) {
971       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i8, Custom);
972       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i16, Custom);
973       setLoadExtAction(ISD::SEXTLOAD, VT, MVT::v2i32, Custom);
974     }
975
976     // SSE41 also has vector sign/zero extending loads, PMOV[SZ]X
977     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
978     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
979     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
980     setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
981     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
982     setLoadExtAction(ISD::SEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
983
984     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i16, MVT::v8i8,  Legal);
985     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8,  Legal);
986     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i8,  Legal);
987     setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i16, Legal);
988     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i16, Legal);
989     setLoadExtAction(ISD::ZEXTLOAD, MVT::v2i64, MVT::v2i32, Legal);
990
991     // i8 and i16 vectors are custom because the source register and source
992     // source memory operand types are not the same width.  f32 vectors are
993     // custom since the immediate controlling the insert encodes additional
994     // information.
995     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i8, Custom);
996     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i16, Custom);
997     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4i32, Custom);
998     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v4f32, Custom);
999
1000     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i8, Custom);
1001     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i16, Custom);
1002     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4i32, Custom);
1003     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v4f32, Custom);
1004
1005     // FIXME: these should be Legal, but that's only for the case where
1006     // the index is constant.  For now custom expand to deal with that.
1007     if (Subtarget->is64Bit()) {
1008       setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v2i64, Custom);
1009       setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v2i64, Custom);
1010     }
1011   }
1012
1013   if (Subtarget->hasSSE2()) {
1014     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v2i64, Custom);
1015     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v4i32, Custom);
1016     setOperationAction(ISD::SIGN_EXTEND_VECTOR_INREG, MVT::v8i16, Custom);
1017
1018     setOperationAction(ISD::SRL,               MVT::v8i16, Custom);
1019     setOperationAction(ISD::SRL,               MVT::v16i8, Custom);
1020
1021     setOperationAction(ISD::SHL,               MVT::v8i16, Custom);
1022     setOperationAction(ISD::SHL,               MVT::v16i8, Custom);
1023
1024     setOperationAction(ISD::SRA,               MVT::v8i16, Custom);
1025     setOperationAction(ISD::SRA,               MVT::v16i8, Custom);
1026
1027     // In the customized shift lowering, the legal cases in AVX2 will be
1028     // recognized.
1029     setOperationAction(ISD::SRL,               MVT::v2i64, Custom);
1030     setOperationAction(ISD::SRL,               MVT::v4i32, Custom);
1031
1032     setOperationAction(ISD::SHL,               MVT::v2i64, Custom);
1033     setOperationAction(ISD::SHL,               MVT::v4i32, Custom);
1034
1035     setOperationAction(ISD::SRA,               MVT::v4i32, Custom);
1036   }
1037
1038   if (!Subtarget->useSoftFloat() && Subtarget->hasFp256()) {
1039     addRegisterClass(MVT::v32i8,  &X86::VR256RegClass);
1040     addRegisterClass(MVT::v16i16, &X86::VR256RegClass);
1041     addRegisterClass(MVT::v8i32,  &X86::VR256RegClass);
1042     addRegisterClass(MVT::v8f32,  &X86::VR256RegClass);
1043     addRegisterClass(MVT::v4i64,  &X86::VR256RegClass);
1044     addRegisterClass(MVT::v4f64,  &X86::VR256RegClass);
1045
1046     setOperationAction(ISD::LOAD,               MVT::v8f32, Legal);
1047     setOperationAction(ISD::LOAD,               MVT::v4f64, Legal);
1048     setOperationAction(ISD::LOAD,               MVT::v4i64, Legal);
1049
1050     setOperationAction(ISD::FADD,               MVT::v8f32, Legal);
1051     setOperationAction(ISD::FSUB,               MVT::v8f32, Legal);
1052     setOperationAction(ISD::FMUL,               MVT::v8f32, Legal);
1053     setOperationAction(ISD::FDIV,               MVT::v8f32, Legal);
1054     setOperationAction(ISD::FSQRT,              MVT::v8f32, Legal);
1055     setOperationAction(ISD::FFLOOR,             MVT::v8f32, Legal);
1056     setOperationAction(ISD::FCEIL,              MVT::v8f32, Legal);
1057     setOperationAction(ISD::FTRUNC,             MVT::v8f32, Legal);
1058     setOperationAction(ISD::FRINT,              MVT::v8f32, Legal);
1059     setOperationAction(ISD::FNEARBYINT,         MVT::v8f32, Legal);
1060     setOperationAction(ISD::FNEG,               MVT::v8f32, Custom);
1061     setOperationAction(ISD::FABS,               MVT::v8f32, Custom);
1062
1063     setOperationAction(ISD::FADD,               MVT::v4f64, Legal);
1064     setOperationAction(ISD::FSUB,               MVT::v4f64, Legal);
1065     setOperationAction(ISD::FMUL,               MVT::v4f64, Legal);
1066     setOperationAction(ISD::FDIV,               MVT::v4f64, Legal);
1067     setOperationAction(ISD::FSQRT,              MVT::v4f64, Legal);
1068     setOperationAction(ISD::FFLOOR,             MVT::v4f64, Legal);
1069     setOperationAction(ISD::FCEIL,              MVT::v4f64, Legal);
1070     setOperationAction(ISD::FTRUNC,             MVT::v4f64, Legal);
1071     setOperationAction(ISD::FRINT,              MVT::v4f64, Legal);
1072     setOperationAction(ISD::FNEARBYINT,         MVT::v4f64, Legal);
1073     setOperationAction(ISD::FNEG,               MVT::v4f64, Custom);
1074     setOperationAction(ISD::FABS,               MVT::v4f64, Custom);
1075
1076     // (fp_to_int:v8i16 (v8f32 ..)) requires the result type to be promoted
1077     // even though v8i16 is a legal type.
1078     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i16, Promote);
1079     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i16, Promote);
1080     setOperationAction(ISD::FP_TO_SINT,         MVT::v8i32, Legal);
1081
1082     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i16, Promote);
1083     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i32, Legal);
1084     setOperationAction(ISD::FP_ROUND,           MVT::v4f32, Legal);
1085
1086     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i8,  Custom);
1087     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i16, Custom);
1088
1089     for (MVT VT : MVT::fp_vector_valuetypes())
1090       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v4f32, Legal);
1091
1092     setOperationAction(ISD::SRL,               MVT::v16i16, Custom);
1093     setOperationAction(ISD::SRL,               MVT::v32i8, Custom);
1094
1095     setOperationAction(ISD::SHL,               MVT::v16i16, Custom);
1096     setOperationAction(ISD::SHL,               MVT::v32i8, Custom);
1097
1098     setOperationAction(ISD::SRA,               MVT::v16i16, Custom);
1099     setOperationAction(ISD::SRA,               MVT::v32i8, Custom);
1100
1101     setOperationAction(ISD::SETCC,             MVT::v32i8, Custom);
1102     setOperationAction(ISD::SETCC,             MVT::v16i16, Custom);
1103     setOperationAction(ISD::SETCC,             MVT::v8i32, Custom);
1104     setOperationAction(ISD::SETCC,             MVT::v4i64, Custom);
1105
1106     setOperationAction(ISD::SELECT,            MVT::v4f64, Custom);
1107     setOperationAction(ISD::SELECT,            MVT::v4i64, Custom);
1108     setOperationAction(ISD::SELECT,            MVT::v8f32, Custom);
1109
1110     setOperationAction(ISD::SIGN_EXTEND,       MVT::v4i64, Custom);
1111     setOperationAction(ISD::SIGN_EXTEND,       MVT::v8i32, Custom);
1112     setOperationAction(ISD::SIGN_EXTEND,       MVT::v16i16, Custom);
1113     setOperationAction(ISD::ZERO_EXTEND,       MVT::v4i64, Custom);
1114     setOperationAction(ISD::ZERO_EXTEND,       MVT::v8i32, Custom);
1115     setOperationAction(ISD::ZERO_EXTEND,       MVT::v16i16, Custom);
1116     setOperationAction(ISD::ANY_EXTEND,        MVT::v4i64, Custom);
1117     setOperationAction(ISD::ANY_EXTEND,        MVT::v8i32, Custom);
1118     setOperationAction(ISD::ANY_EXTEND,        MVT::v16i16, Custom);
1119     setOperationAction(ISD::TRUNCATE,          MVT::v16i8, Custom);
1120     setOperationAction(ISD::TRUNCATE,          MVT::v8i16, Custom);
1121     setOperationAction(ISD::TRUNCATE,          MVT::v4i32, Custom);
1122
1123     setOperationAction(ISD::CTPOP,             MVT::v32i8, Custom);
1124     setOperationAction(ISD::CTPOP,             MVT::v16i16, Custom);
1125     setOperationAction(ISD::CTPOP,             MVT::v8i32, Custom);
1126     setOperationAction(ISD::CTPOP,             MVT::v4i64, Custom);
1127
1128     if (Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()) {
1129       setOperationAction(ISD::FMA,             MVT::v8f32, Legal);
1130       setOperationAction(ISD::FMA,             MVT::v4f64, Legal);
1131       setOperationAction(ISD::FMA,             MVT::v4f32, Legal);
1132       setOperationAction(ISD::FMA,             MVT::v2f64, Legal);
1133       setOperationAction(ISD::FMA,             MVT::f32, Legal);
1134       setOperationAction(ISD::FMA,             MVT::f64, Legal);
1135     }
1136
1137     if (Subtarget->hasInt256()) {
1138       setOperationAction(ISD::ADD,             MVT::v4i64, Legal);
1139       setOperationAction(ISD::ADD,             MVT::v8i32, Legal);
1140       setOperationAction(ISD::ADD,             MVT::v16i16, Legal);
1141       setOperationAction(ISD::ADD,             MVT::v32i8, Legal);
1142
1143       setOperationAction(ISD::SUB,             MVT::v4i64, Legal);
1144       setOperationAction(ISD::SUB,             MVT::v8i32, Legal);
1145       setOperationAction(ISD::SUB,             MVT::v16i16, Legal);
1146       setOperationAction(ISD::SUB,             MVT::v32i8, Legal);
1147
1148       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1149       setOperationAction(ISD::MUL,             MVT::v8i32, Legal);
1150       setOperationAction(ISD::MUL,             MVT::v16i16, Legal);
1151       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1152
1153       setOperationAction(ISD::UMUL_LOHI,       MVT::v8i32, Custom);
1154       setOperationAction(ISD::SMUL_LOHI,       MVT::v8i32, Custom);
1155       setOperationAction(ISD::MULHU,           MVT::v16i16, Legal);
1156       setOperationAction(ISD::MULHS,           MVT::v16i16, Legal);
1157
1158       setOperationAction(ISD::SMAX,            MVT::v32i8,  Legal);
1159       setOperationAction(ISD::SMAX,            MVT::v16i16, Legal);
1160       setOperationAction(ISD::SMAX,            MVT::v8i32,  Legal);
1161       setOperationAction(ISD::UMAX,            MVT::v32i8,  Legal);
1162       setOperationAction(ISD::UMAX,            MVT::v16i16, Legal);
1163       setOperationAction(ISD::UMAX,            MVT::v8i32,  Legal);
1164       setOperationAction(ISD::SMIN,            MVT::v32i8,  Legal);
1165       setOperationAction(ISD::SMIN,            MVT::v16i16, Legal);
1166       setOperationAction(ISD::SMIN,            MVT::v8i32,  Legal);
1167       setOperationAction(ISD::UMIN,            MVT::v32i8,  Legal);
1168       setOperationAction(ISD::UMIN,            MVT::v16i16, Legal);
1169       setOperationAction(ISD::UMIN,            MVT::v8i32,  Legal);
1170
1171       // The custom lowering for UINT_TO_FP for v8i32 becomes interesting
1172       // when we have a 256bit-wide blend with immediate.
1173       setOperationAction(ISD::UINT_TO_FP, MVT::v8i32, Custom);
1174
1175       // AVX2 also has wider vector sign/zero extending loads, VPMOV[SZ]X
1176       setLoadExtAction(ISD::SEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1177       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1178       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1179       setLoadExtAction(ISD::SEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1180       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1181       setLoadExtAction(ISD::SEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1182
1183       setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i16, MVT::v16i8, Legal);
1184       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i8,  Legal);
1185       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i8,  Legal);
1186       setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i32,  MVT::v8i16, Legal);
1187       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i16, Legal);
1188       setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i64,  MVT::v4i32, Legal);
1189     } else {
1190       setOperationAction(ISD::ADD,             MVT::v4i64, Custom);
1191       setOperationAction(ISD::ADD,             MVT::v8i32, Custom);
1192       setOperationAction(ISD::ADD,             MVT::v16i16, Custom);
1193       setOperationAction(ISD::ADD,             MVT::v32i8, Custom);
1194
1195       setOperationAction(ISD::SUB,             MVT::v4i64, Custom);
1196       setOperationAction(ISD::SUB,             MVT::v8i32, Custom);
1197       setOperationAction(ISD::SUB,             MVT::v16i16, Custom);
1198       setOperationAction(ISD::SUB,             MVT::v32i8, Custom);
1199
1200       setOperationAction(ISD::MUL,             MVT::v4i64, Custom);
1201       setOperationAction(ISD::MUL,             MVT::v8i32, Custom);
1202       setOperationAction(ISD::MUL,             MVT::v16i16, Custom);
1203       setOperationAction(ISD::MUL,             MVT::v32i8, Custom);
1204     }
1205
1206     // In the customized shift lowering, the legal cases in AVX2 will be
1207     // recognized.
1208     setOperationAction(ISD::SRL,               MVT::v4i64, Custom);
1209     setOperationAction(ISD::SRL,               MVT::v8i32, Custom);
1210
1211     setOperationAction(ISD::SHL,               MVT::v4i64, Custom);
1212     setOperationAction(ISD::SHL,               MVT::v8i32, Custom);
1213
1214     setOperationAction(ISD::SRA,               MVT::v8i32, Custom);
1215
1216     // Custom lower several nodes for 256-bit types.
1217     for (MVT VT : MVT::vector_valuetypes()) {
1218       if (VT.getScalarSizeInBits() >= 32) {
1219         setOperationAction(ISD::MLOAD,  VT, Legal);
1220         setOperationAction(ISD::MSTORE, VT, Legal);
1221       }
1222       // Extract subvector is special because the value type
1223       // (result) is 128-bit but the source is 256-bit wide.
1224       if (VT.is128BitVector()) {
1225         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1226       }
1227       // Do not attempt to custom lower other non-256-bit vectors
1228       if (!VT.is256BitVector())
1229         continue;
1230
1231       setOperationAction(ISD::BUILD_VECTOR,       VT, Custom);
1232       setOperationAction(ISD::VECTOR_SHUFFLE,     VT, Custom);
1233       setOperationAction(ISD::VSELECT,            VT, Custom);
1234       setOperationAction(ISD::INSERT_VECTOR_ELT,  VT, Custom);
1235       setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
1236       setOperationAction(ISD::SCALAR_TO_VECTOR,   VT, Custom);
1237       setOperationAction(ISD::INSERT_SUBVECTOR,   VT, Custom);
1238       setOperationAction(ISD::CONCAT_VECTORS,     VT, Custom);
1239     }
1240
1241     if (Subtarget->hasInt256())
1242       setOperationAction(ISD::VSELECT,         MVT::v32i8, Legal);
1243
1244
1245     // Promote v32i8, v16i16, v8i32 select, and, or, xor to v4i64.
1246     for (int i = MVT::v32i8; i != MVT::v4i64; ++i) {
1247       MVT VT = (MVT::SimpleValueType)i;
1248
1249       // Do not attempt to promote non-256-bit vectors
1250       if (!VT.is256BitVector())
1251         continue;
1252
1253       setOperationAction(ISD::AND,    VT, Promote);
1254       AddPromotedToType (ISD::AND,    VT, MVT::v4i64);
1255       setOperationAction(ISD::OR,     VT, Promote);
1256       AddPromotedToType (ISD::OR,     VT, MVT::v4i64);
1257       setOperationAction(ISD::XOR,    VT, Promote);
1258       AddPromotedToType (ISD::XOR,    VT, MVT::v4i64);
1259       setOperationAction(ISD::LOAD,   VT, Promote);
1260       AddPromotedToType (ISD::LOAD,   VT, MVT::v4i64);
1261       setOperationAction(ISD::SELECT, VT, Promote);
1262       AddPromotedToType (ISD::SELECT, VT, MVT::v4i64);
1263     }
1264   }
1265
1266   if (!Subtarget->useSoftFloat() && Subtarget->hasAVX512()) {
1267     addRegisterClass(MVT::v16i32, &X86::VR512RegClass);
1268     addRegisterClass(MVT::v16f32, &X86::VR512RegClass);
1269     addRegisterClass(MVT::v8i64,  &X86::VR512RegClass);
1270     addRegisterClass(MVT::v8f64,  &X86::VR512RegClass);
1271
1272     addRegisterClass(MVT::i1,     &X86::VK1RegClass);
1273     addRegisterClass(MVT::v8i1,   &X86::VK8RegClass);
1274     addRegisterClass(MVT::v16i1,  &X86::VK16RegClass);
1275
1276     for (MVT VT : MVT::fp_vector_valuetypes())
1277       setLoadExtAction(ISD::EXTLOAD, VT, MVT::v8f32, Legal);
1278
1279     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1280     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i8, Legal);
1281     setLoadExtAction(ISD::ZEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1282     setLoadExtAction(ISD::SEXTLOAD, MVT::v16i32, MVT::v16i16, Legal);
1283     setLoadExtAction(ISD::ZEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1284     setLoadExtAction(ISD::SEXTLOAD, MVT::v32i16, MVT::v32i8, Legal);
1285     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1286     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i8,  Legal);
1287     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1288     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i16,  Legal);
1289     setLoadExtAction(ISD::ZEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1290     setLoadExtAction(ISD::SEXTLOAD, MVT::v8i64,  MVT::v8i32,  Legal);
1291
1292     setOperationAction(ISD::BR_CC,              MVT::i1,    Expand);
1293     setOperationAction(ISD::SETCC,              MVT::i1,    Custom);
1294     setOperationAction(ISD::XOR,                MVT::i1,    Legal);
1295     setOperationAction(ISD::OR,                 MVT::i1,    Legal);
1296     setOperationAction(ISD::AND,                MVT::i1,    Legal);
1297     setOperationAction(ISD::SUB,                MVT::i1,    Custom);
1298     setOperationAction(ISD::ADD,                MVT::i1,    Custom);
1299     setOperationAction(ISD::MUL,                MVT::i1,    Custom);
1300     setOperationAction(ISD::LOAD,               MVT::v16f32, Legal);
1301     setOperationAction(ISD::LOAD,               MVT::v8f64, Legal);
1302     setOperationAction(ISD::LOAD,               MVT::v8i64, Legal);
1303     setOperationAction(ISD::LOAD,               MVT::v16i32, Legal);
1304     setOperationAction(ISD::LOAD,               MVT::v16i1, Legal);
1305
1306     setOperationAction(ISD::FADD,               MVT::v16f32, Legal);
1307     setOperationAction(ISD::FSUB,               MVT::v16f32, Legal);
1308     setOperationAction(ISD::FMUL,               MVT::v16f32, Legal);
1309     setOperationAction(ISD::FDIV,               MVT::v16f32, Legal);
1310     setOperationAction(ISD::FSQRT,              MVT::v16f32, Legal);
1311     setOperationAction(ISD::FNEG,               MVT::v16f32, Custom);
1312
1313     setOperationAction(ISD::FADD,               MVT::v8f64, Legal);
1314     setOperationAction(ISD::FSUB,               MVT::v8f64, Legal);
1315     setOperationAction(ISD::FMUL,               MVT::v8f64, Legal);
1316     setOperationAction(ISD::FDIV,               MVT::v8f64, Legal);
1317     setOperationAction(ISD::FSQRT,              MVT::v8f64, Legal);
1318     setOperationAction(ISD::FNEG,               MVT::v8f64, Custom);
1319     setOperationAction(ISD::FMA,                MVT::v8f64, Legal);
1320     setOperationAction(ISD::FMA,                MVT::v16f32, Legal);
1321
1322     setOperationAction(ISD::FP_TO_SINT,         MVT::i32, Legal);
1323     setOperationAction(ISD::FP_TO_UINT,         MVT::i32, Legal);
1324     setOperationAction(ISD::SINT_TO_FP,         MVT::i32, Legal);
1325     setOperationAction(ISD::UINT_TO_FP,         MVT::i32, Legal);
1326     if (Subtarget->is64Bit()) {
1327       setOperationAction(ISD::FP_TO_UINT,       MVT::i64, Legal);
1328       setOperationAction(ISD::FP_TO_SINT,       MVT::i64, Legal);
1329       setOperationAction(ISD::SINT_TO_FP,       MVT::i64, Legal);
1330       setOperationAction(ISD::UINT_TO_FP,       MVT::i64, Legal);
1331     }
1332     setOperationAction(ISD::FP_TO_SINT,         MVT::v16i32, Legal);
1333     setOperationAction(ISD::FP_TO_UINT,         MVT::v16i32, Legal);
1334     setOperationAction(ISD::FP_TO_UINT,         MVT::v8i32, Legal);
1335     setOperationAction(ISD::FP_TO_UINT,         MVT::v4i32, Legal);
1336     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i32, Legal);
1337     setOperationAction(ISD::SINT_TO_FP,         MVT::v8i1,   Custom);
1338     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i1,  Custom);
1339     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i8,  Promote);
1340     setOperationAction(ISD::SINT_TO_FP,         MVT::v16i16, Promote);
1341     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i32, Legal);
1342     setOperationAction(ISD::UINT_TO_FP,         MVT::v8i32, Legal);
1343     setOperationAction(ISD::UINT_TO_FP,         MVT::v4i32, Legal);
1344     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i8, Custom);
1345     setOperationAction(ISD::UINT_TO_FP,         MVT::v16i16, Custom);
1346     setOperationAction(ISD::FP_ROUND,           MVT::v8f32, Legal);
1347     setOperationAction(ISD::FP_EXTEND,          MVT::v8f32, Legal);
1348
1349     setOperationAction(ISD::TRUNCATE,           MVT::i1, Custom);
1350     setOperationAction(ISD::TRUNCATE,           MVT::v16i8, Custom);
1351     setOperationAction(ISD::TRUNCATE,           MVT::v8i32, Custom);
1352     if (Subtarget->hasDQI()) {
1353       setOperationAction(ISD::TRUNCATE,           MVT::v2i1, Custom);
1354       setOperationAction(ISD::TRUNCATE,           MVT::v4i1, Custom);
1355     }
1356     setOperationAction(ISD::TRUNCATE,           MVT::v8i1, Custom);
1357     setOperationAction(ISD::TRUNCATE,           MVT::v16i1, Custom);
1358     setOperationAction(ISD::TRUNCATE,           MVT::v16i16, Custom);
1359     setOperationAction(ISD::ZERO_EXTEND,        MVT::v16i32, Custom);
1360     setOperationAction(ISD::ZERO_EXTEND,        MVT::v8i64, Custom);
1361     setOperationAction(ISD::ANY_EXTEND,         MVT::v16i32, Custom);
1362     setOperationAction(ISD::ANY_EXTEND,         MVT::v8i64, Custom);
1363     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i32, Custom);
1364     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i64, Custom);
1365     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i8, Custom);
1366     setOperationAction(ISD::SIGN_EXTEND,        MVT::v8i16, Custom);
1367     setOperationAction(ISD::SIGN_EXTEND,        MVT::v16i16, Custom);
1368     if (Subtarget->hasDQI()) {
1369       setOperationAction(ISD::SIGN_EXTEND,        MVT::v4i32, Custom);
1370       setOperationAction(ISD::SIGN_EXTEND,        MVT::v2i64, Custom);
1371     }
1372     setOperationAction(ISD::FFLOOR,             MVT::v16f32, Legal);
1373     setOperationAction(ISD::FFLOOR,             MVT::v8f64, Legal);
1374     setOperationAction(ISD::FCEIL,              MVT::v16f32, Legal);
1375     setOperationAction(ISD::FCEIL,              MVT::v8f64, Legal);
1376     setOperationAction(ISD::FTRUNC,             MVT::v16f32, Legal);
1377     setOperationAction(ISD::FTRUNC,             MVT::v8f64, Legal);
1378     setOperationAction(ISD::FRINT,              MVT::v16f32, Legal);
1379     setOperationAction(ISD::FRINT,              MVT::v8f64, Legal);
1380     setOperationAction(ISD::FNEARBYINT,         MVT::v16f32, Legal);
1381     setOperationAction(ISD::FNEARBYINT,         MVT::v8f64, Legal);
1382
1383     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8f64,  Custom);
1384     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i64,  Custom);
1385     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16f32,  Custom);
1386     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i32,  Custom);
1387     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v16i1, Legal);
1388
1389     setOperationAction(ISD::SETCC,              MVT::v16i1, Custom);
1390     setOperationAction(ISD::SETCC,              MVT::v8i1, Custom);
1391
1392     setOperationAction(ISD::MUL,              MVT::v8i64, Custom);
1393
1394     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v8i1,  Custom);
1395     setOperationAction(ISD::EXTRACT_VECTOR_ELT, MVT::v16i1, Custom);
1396     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v16i1, Custom);
1397     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v8i1, Custom);
1398     setOperationAction(ISD::BUILD_VECTOR,       MVT::v8i1, Custom);
1399     setOperationAction(ISD::BUILD_VECTOR,       MVT::v16i1, Custom);
1400     setOperationAction(ISD::SELECT,             MVT::v8f64, Custom);
1401     setOperationAction(ISD::SELECT,             MVT::v8i64, Custom);
1402     setOperationAction(ISD::SELECT,             MVT::v16f32, Custom);
1403     setOperationAction(ISD::SELECT,             MVT::v16i1, Custom);
1404     setOperationAction(ISD::SELECT,             MVT::v8i1,  Custom);
1405
1406     setOperationAction(ISD::SMAX,               MVT::v16i32, Legal);
1407     setOperationAction(ISD::SMAX,               MVT::v8i64, Legal);
1408     setOperationAction(ISD::UMAX,               MVT::v16i32, Legal);
1409     setOperationAction(ISD::UMAX,               MVT::v8i64, Legal);
1410     setOperationAction(ISD::SMIN,               MVT::v16i32, Legal);
1411     setOperationAction(ISD::SMIN,               MVT::v8i64, Legal);
1412     setOperationAction(ISD::UMIN,               MVT::v16i32, Legal);
1413     setOperationAction(ISD::UMIN,               MVT::v8i64, Legal);
1414
1415     setOperationAction(ISD::ADD,                MVT::v8i64, Legal);
1416     setOperationAction(ISD::ADD,                MVT::v16i32, Legal);
1417
1418     setOperationAction(ISD::SUB,                MVT::v8i64, Legal);
1419     setOperationAction(ISD::SUB,                MVT::v16i32, Legal);
1420
1421     setOperationAction(ISD::MUL,                MVT::v16i32, Legal);
1422
1423     setOperationAction(ISD::SRL,                MVT::v8i64, Custom);
1424     setOperationAction(ISD::SRL,                MVT::v16i32, Custom);
1425
1426     setOperationAction(ISD::SHL,                MVT::v8i64, Custom);
1427     setOperationAction(ISD::SHL,                MVT::v16i32, Custom);
1428
1429     setOperationAction(ISD::SRA,                MVT::v8i64, Custom);
1430     setOperationAction(ISD::SRA,                MVT::v16i32, Custom);
1431
1432     setOperationAction(ISD::AND,                MVT::v8i64, Legal);
1433     setOperationAction(ISD::OR,                 MVT::v8i64, Legal);
1434     setOperationAction(ISD::XOR,                MVT::v8i64, Legal);
1435     setOperationAction(ISD::AND,                MVT::v16i32, Legal);
1436     setOperationAction(ISD::OR,                 MVT::v16i32, Legal);
1437     setOperationAction(ISD::XOR,                MVT::v16i32, Legal);
1438
1439     if (Subtarget->hasCDI()) {
1440       setOperationAction(ISD::CTLZ,             MVT::v8i64, Legal);
1441       setOperationAction(ISD::CTLZ,             MVT::v16i32, Legal);
1442     }
1443     if (Subtarget->hasDQI()) {
1444       setOperationAction(ISD::MUL,             MVT::v2i64, Legal);
1445       setOperationAction(ISD::MUL,             MVT::v4i64, Legal);
1446       setOperationAction(ISD::MUL,             MVT::v8i64, Legal);
1447     }
1448     // Custom lower several nodes.
1449     for (MVT VT : MVT::vector_valuetypes()) {
1450       unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1451       if (EltSize == 1) {
1452         setOperationAction(ISD::AND, VT, Legal);
1453         setOperationAction(ISD::OR,  VT, Legal);
1454         setOperationAction(ISD::XOR,  VT, Legal);
1455       }
1456       if (EltSize >= 32 && VT.getSizeInBits() <= 512) {
1457         setOperationAction(ISD::MGATHER,  VT, Custom);
1458         setOperationAction(ISD::MSCATTER, VT, Custom);
1459       }
1460       // Extract subvector is special because the value type
1461       // (result) is 256/128-bit but the source is 512-bit wide.
1462       if (VT.is128BitVector() || VT.is256BitVector()) {
1463         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
1464       }
1465       if (VT.getVectorElementType() == MVT::i1)
1466         setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Legal);
1467
1468       // Do not attempt to custom lower other non-512-bit vectors
1469       if (!VT.is512BitVector())
1470         continue;
1471
1472       if (EltSize >= 32) {
1473         setOperationAction(ISD::VECTOR_SHUFFLE,      VT, Custom);
1474         setOperationAction(ISD::INSERT_VECTOR_ELT,   VT, Custom);
1475         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1476         setOperationAction(ISD::VSELECT,             VT, Legal);
1477         setOperationAction(ISD::EXTRACT_VECTOR_ELT,  VT, Custom);
1478         setOperationAction(ISD::SCALAR_TO_VECTOR,    VT, Custom);
1479         setOperationAction(ISD::INSERT_SUBVECTOR,    VT, Custom);
1480         setOperationAction(ISD::MLOAD,               VT, Legal);
1481         setOperationAction(ISD::MSTORE,              VT, Legal);
1482       }
1483     }
1484     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1485       MVT VT = (MVT::SimpleValueType)i;
1486
1487       // Do not attempt to promote non-512-bit vectors.
1488       if (!VT.is512BitVector())
1489         continue;
1490
1491       setOperationAction(ISD::SELECT, VT, Promote);
1492       AddPromotedToType (ISD::SELECT, VT, MVT::v8i64);
1493     }
1494   }// has  AVX-512
1495
1496   if (!Subtarget->useSoftFloat() && Subtarget->hasBWI()) {
1497     addRegisterClass(MVT::v32i16, &X86::VR512RegClass);
1498     addRegisterClass(MVT::v64i8,  &X86::VR512RegClass);
1499
1500     addRegisterClass(MVT::v32i1,  &X86::VK32RegClass);
1501     addRegisterClass(MVT::v64i1,  &X86::VK64RegClass);
1502
1503     setOperationAction(ISD::LOAD,               MVT::v32i16, Legal);
1504     setOperationAction(ISD::LOAD,               MVT::v64i8, Legal);
1505     setOperationAction(ISD::SETCC,              MVT::v32i1, Custom);
1506     setOperationAction(ISD::SETCC,              MVT::v64i1, Custom);
1507     setOperationAction(ISD::ADD,                MVT::v32i16, Legal);
1508     setOperationAction(ISD::ADD,                MVT::v64i8, Legal);
1509     setOperationAction(ISD::SUB,                MVT::v32i16, Legal);
1510     setOperationAction(ISD::SUB,                MVT::v64i8, Legal);
1511     setOperationAction(ISD::MUL,                MVT::v32i16, Legal);
1512     setOperationAction(ISD::MULHS,              MVT::v32i16, Legal);
1513     setOperationAction(ISD::MULHU,              MVT::v32i16, Legal);
1514     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v32i1, Custom);
1515     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v64i1, Custom);
1516     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v32i1, Custom);
1517     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v64i1, Custom);
1518     setOperationAction(ISD::SELECT,             MVT::v32i1, Custom);
1519     setOperationAction(ISD::SELECT,             MVT::v64i1, Custom);
1520     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i8, Custom);
1521     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i8, Custom);
1522     setOperationAction(ISD::SIGN_EXTEND,        MVT::v32i16, Custom);
1523     setOperationAction(ISD::ZERO_EXTEND,        MVT::v32i16, Custom);
1524     setOperationAction(ISD::SIGN_EXTEND,        MVT::v64i8, Custom);
1525     setOperationAction(ISD::ZERO_EXTEND,        MVT::v64i8, Custom);
1526     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v32i1, Custom);
1527     setOperationAction(ISD::INSERT_VECTOR_ELT,  MVT::v64i1, Custom);
1528     setOperationAction(ISD::VSELECT,            MVT::v32i16, Legal);
1529     setOperationAction(ISD::VSELECT,            MVT::v64i8, Legal);
1530     setOperationAction(ISD::TRUNCATE,           MVT::v32i1, Custom);
1531     setOperationAction(ISD::TRUNCATE,           MVT::v64i1, Custom);
1532
1533     setOperationAction(ISD::SMAX,               MVT::v64i8, Legal);
1534     setOperationAction(ISD::SMAX,               MVT::v32i16, Legal);
1535     setOperationAction(ISD::UMAX,               MVT::v64i8, Legal);
1536     setOperationAction(ISD::UMAX,               MVT::v32i16, Legal);
1537     setOperationAction(ISD::SMIN,               MVT::v64i8, Legal);
1538     setOperationAction(ISD::SMIN,               MVT::v32i16, Legal);
1539     setOperationAction(ISD::UMIN,               MVT::v64i8, Legal);
1540     setOperationAction(ISD::UMIN,               MVT::v32i16, Legal);
1541
1542     for (int i = MVT::v32i8; i != MVT::v8i64; ++i) {
1543       const MVT VT = (MVT::SimpleValueType)i;
1544
1545       const unsigned EltSize = VT.getVectorElementType().getSizeInBits();
1546
1547       // Do not attempt to promote non-512-bit vectors.
1548       if (!VT.is512BitVector())
1549         continue;
1550
1551       if (EltSize < 32) {
1552         setOperationAction(ISD::BUILD_VECTOR,        VT, Custom);
1553         setOperationAction(ISD::VSELECT,             VT, Legal);
1554       }
1555     }
1556   }
1557
1558   if (!Subtarget->useSoftFloat() && Subtarget->hasVLX()) {
1559     addRegisterClass(MVT::v4i1,   &X86::VK4RegClass);
1560     addRegisterClass(MVT::v2i1,   &X86::VK2RegClass);
1561
1562     setOperationAction(ISD::SETCC,              MVT::v4i1, Custom);
1563     setOperationAction(ISD::SETCC,              MVT::v2i1, Custom);
1564     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v4i1, Custom);
1565     setOperationAction(ISD::CONCAT_VECTORS,     MVT::v8i1, Custom);
1566     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v8i1, Custom);
1567     setOperationAction(ISD::INSERT_SUBVECTOR,   MVT::v4i1, Custom);
1568     setOperationAction(ISD::SELECT,             MVT::v4i1, Custom);
1569     setOperationAction(ISD::SELECT,             MVT::v2i1, Custom);
1570     setOperationAction(ISD::BUILD_VECTOR,       MVT::v4i1, Custom);
1571     setOperationAction(ISD::BUILD_VECTOR,       MVT::v2i1, Custom);
1572
1573     setOperationAction(ISD::AND,                MVT::v8i32, Legal);
1574     setOperationAction(ISD::OR,                 MVT::v8i32, Legal);
1575     setOperationAction(ISD::XOR,                MVT::v8i32, Legal);
1576     setOperationAction(ISD::AND,                MVT::v4i32, Legal);
1577     setOperationAction(ISD::OR,                 MVT::v4i32, Legal);
1578     setOperationAction(ISD::XOR,                MVT::v4i32, Legal);
1579     setOperationAction(ISD::SRA,                MVT::v2i64, Custom);
1580     setOperationAction(ISD::SRA,                MVT::v4i64, Custom);
1581
1582     setOperationAction(ISD::SMAX,               MVT::v2i64, Legal);
1583     setOperationAction(ISD::SMAX,               MVT::v4i64, Legal);
1584     setOperationAction(ISD::UMAX,               MVT::v2i64, Legal);
1585     setOperationAction(ISD::UMAX,               MVT::v4i64, Legal);
1586     setOperationAction(ISD::SMIN,               MVT::v2i64, Legal);
1587     setOperationAction(ISD::SMIN,               MVT::v4i64, Legal);
1588     setOperationAction(ISD::UMIN,               MVT::v2i64, Legal);
1589     setOperationAction(ISD::UMIN,               MVT::v4i64, Legal);
1590   }
1591
1592   // We want to custom lower some of our intrinsics.
1593   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
1594   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::Other, Custom);
1595   setOperationAction(ISD::INTRINSIC_VOID, MVT::Other, Custom);
1596   if (!Subtarget->is64Bit())
1597     setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
1598
1599   // Only custom-lower 64-bit SADDO and friends on 64-bit because we don't
1600   // handle type legalization for these operations here.
1601   //
1602   // FIXME: We really should do custom legalization for addition and
1603   // subtraction on x86-32 once PR3203 is fixed.  We really can't do much better
1604   // than generic legalization for 64-bit multiplication-with-overflow, though.
1605   for (unsigned i = 0, e = 3+Subtarget->is64Bit(); i != e; ++i) {
1606     // Add/Sub/Mul with overflow operations are custom lowered.
1607     MVT VT = IntVTs[i];
1608     setOperationAction(ISD::SADDO, VT, Custom);
1609     setOperationAction(ISD::UADDO, VT, Custom);
1610     setOperationAction(ISD::SSUBO, VT, Custom);
1611     setOperationAction(ISD::USUBO, VT, Custom);
1612     setOperationAction(ISD::SMULO, VT, Custom);
1613     setOperationAction(ISD::UMULO, VT, Custom);
1614   }
1615
1616
1617   if (!Subtarget->is64Bit()) {
1618     // These libcalls are not available in 32-bit.
1619     setLibcallName(RTLIB::SHL_I128, nullptr);
1620     setLibcallName(RTLIB::SRL_I128, nullptr);
1621     setLibcallName(RTLIB::SRA_I128, nullptr);
1622   }
1623
1624   // Combine sin / cos into one node or libcall if possible.
1625   if (Subtarget->hasSinCos()) {
1626     setLibcallName(RTLIB::SINCOS_F32, "sincosf");
1627     setLibcallName(RTLIB::SINCOS_F64, "sincos");
1628     if (Subtarget->isTargetDarwin()) {
1629       // For MacOSX, we don't want the normal expansion of a libcall to sincos.
1630       // We want to issue a libcall to __sincos_stret to avoid memory traffic.
1631       setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
1632       setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
1633     }
1634   }
1635
1636   if (Subtarget->isTargetWin64()) {
1637     setOperationAction(ISD::SDIV, MVT::i128, Custom);
1638     setOperationAction(ISD::UDIV, MVT::i128, Custom);
1639     setOperationAction(ISD::SREM, MVT::i128, Custom);
1640     setOperationAction(ISD::UREM, MVT::i128, Custom);
1641     setOperationAction(ISD::SDIVREM, MVT::i128, Custom);
1642     setOperationAction(ISD::UDIVREM, MVT::i128, Custom);
1643   }
1644
1645   // We have target-specific dag combine patterns for the following nodes:
1646   setTargetDAGCombine(ISD::VECTOR_SHUFFLE);
1647   setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
1648   setTargetDAGCombine(ISD::BITCAST);
1649   setTargetDAGCombine(ISD::VSELECT);
1650   setTargetDAGCombine(ISD::SELECT);
1651   setTargetDAGCombine(ISD::SHL);
1652   setTargetDAGCombine(ISD::SRA);
1653   setTargetDAGCombine(ISD::SRL);
1654   setTargetDAGCombine(ISD::OR);
1655   setTargetDAGCombine(ISD::AND);
1656   setTargetDAGCombine(ISD::ADD);
1657   setTargetDAGCombine(ISD::FADD);
1658   setTargetDAGCombine(ISD::FSUB);
1659   setTargetDAGCombine(ISD::FMA);
1660   setTargetDAGCombine(ISD::SUB);
1661   setTargetDAGCombine(ISD::LOAD);
1662   setTargetDAGCombine(ISD::MLOAD);
1663   setTargetDAGCombine(ISD::STORE);
1664   setTargetDAGCombine(ISD::MSTORE);
1665   setTargetDAGCombine(ISD::ZERO_EXTEND);
1666   setTargetDAGCombine(ISD::ANY_EXTEND);
1667   setTargetDAGCombine(ISD::SIGN_EXTEND);
1668   setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
1669   setTargetDAGCombine(ISD::SINT_TO_FP);
1670   setTargetDAGCombine(ISD::UINT_TO_FP);
1671   setTargetDAGCombine(ISD::SETCC);
1672   setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
1673   setTargetDAGCombine(ISD::BUILD_VECTOR);
1674   setTargetDAGCombine(ISD::MUL);
1675   setTargetDAGCombine(ISD::XOR);
1676
1677   computeRegisterProperties(Subtarget->getRegisterInfo());
1678
1679   // On Darwin, -Os means optimize for size without hurting performance,
1680   // do not reduce the limit.
1681   MaxStoresPerMemset = 16; // For @llvm.memset -> sequence of stores
1682   MaxStoresPerMemsetOptSize = Subtarget->isTargetDarwin() ? 16 : 8;
1683   MaxStoresPerMemcpy = 8; // For @llvm.memcpy -> sequence of stores
1684   MaxStoresPerMemcpyOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1685   MaxStoresPerMemmove = 8; // For @llvm.memmove -> sequence of stores
1686   MaxStoresPerMemmoveOptSize = Subtarget->isTargetDarwin() ? 8 : 4;
1687   setPrefLoopAlignment(4); // 2^4 bytes.
1688
1689   // Predictable cmov don't hurt on atom because it's in-order.
1690   PredictableSelectIsExpensive = !Subtarget->isAtom();
1691   EnableExtLdPromotion = true;
1692   setPrefFunctionAlignment(4); // 2^4 bytes.
1693
1694   verifyIntrinsicTables();
1695 }
1696
1697 // This has so far only been implemented for 64-bit MachO.
1698 bool X86TargetLowering::useLoadStackGuardNode() const {
1699   return Subtarget->isTargetMachO() && Subtarget->is64Bit();
1700 }
1701
1702 TargetLoweringBase::LegalizeTypeAction
1703 X86TargetLowering::getPreferredVectorAction(EVT VT) const {
1704   if (ExperimentalVectorWideningLegalization &&
1705       VT.getVectorNumElements() != 1 &&
1706       VT.getVectorElementType().getSimpleVT() != MVT::i1)
1707     return TypeWidenVector;
1708
1709   return TargetLoweringBase::getPreferredVectorAction(VT);
1710 }
1711
1712 EVT X86TargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
1713   if (!VT.isVector())
1714     return Subtarget->hasAVX512() ? MVT::i1: MVT::i8;
1715
1716   const unsigned NumElts = VT.getVectorNumElements();
1717   const EVT EltVT = VT.getVectorElementType();
1718   if (VT.is512BitVector()) {
1719     if (Subtarget->hasAVX512())
1720       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1721           EltVT == MVT::f32 || EltVT == MVT::f64)
1722         switch(NumElts) {
1723         case  8: return MVT::v8i1;
1724         case 16: return MVT::v16i1;
1725       }
1726     if (Subtarget->hasBWI())
1727       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1728         switch(NumElts) {
1729         case 32: return MVT::v32i1;
1730         case 64: return MVT::v64i1;
1731       }
1732   }
1733
1734   if (VT.is256BitVector() || VT.is128BitVector()) {
1735     if (Subtarget->hasVLX())
1736       if (EltVT == MVT::i32 || EltVT == MVT::i64 ||
1737           EltVT == MVT::f32 || EltVT == MVT::f64)
1738         switch(NumElts) {
1739         case 2: return MVT::v2i1;
1740         case 4: return MVT::v4i1;
1741         case 8: return MVT::v8i1;
1742       }
1743     if (Subtarget->hasBWI() && Subtarget->hasVLX())
1744       if (EltVT == MVT::i8 || EltVT == MVT::i16)
1745         switch(NumElts) {
1746         case  8: return MVT::v8i1;
1747         case 16: return MVT::v16i1;
1748         case 32: return MVT::v32i1;
1749       }
1750   }
1751
1752   return VT.changeVectorElementTypeToInteger();
1753 }
1754
1755 /// Helper for getByValTypeAlignment to determine
1756 /// the desired ByVal argument alignment.
1757 static void getMaxByValAlign(Type *Ty, unsigned &MaxAlign) {
1758   if (MaxAlign == 16)
1759     return;
1760   if (VectorType *VTy = dyn_cast<VectorType>(Ty)) {
1761     if (VTy->getBitWidth() == 128)
1762       MaxAlign = 16;
1763   } else if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
1764     unsigned EltAlign = 0;
1765     getMaxByValAlign(ATy->getElementType(), EltAlign);
1766     if (EltAlign > MaxAlign)
1767       MaxAlign = EltAlign;
1768   } else if (StructType *STy = dyn_cast<StructType>(Ty)) {
1769     for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
1770       unsigned EltAlign = 0;
1771       getMaxByValAlign(STy->getElementType(i), EltAlign);
1772       if (EltAlign > MaxAlign)
1773         MaxAlign = EltAlign;
1774       if (MaxAlign == 16)
1775         break;
1776     }
1777   }
1778 }
1779
1780 /// Return the desired alignment for ByVal aggregate
1781 /// function arguments in the caller parameter area. For X86, aggregates
1782 /// that contain SSE vectors are placed at 16-byte boundaries while the rest
1783 /// are at 4-byte boundaries.
1784 unsigned X86TargetLowering::getByValTypeAlignment(Type *Ty) const {
1785   if (Subtarget->is64Bit()) {
1786     // Max of 8 and alignment of type.
1787     unsigned TyAlign = TD->getABITypeAlignment(Ty);
1788     if (TyAlign > 8)
1789       return TyAlign;
1790     return 8;
1791   }
1792
1793   unsigned Align = 4;
1794   if (Subtarget->hasSSE1())
1795     getMaxByValAlign(Ty, Align);
1796   return Align;
1797 }
1798
1799 /// Returns the target specific optimal type for load
1800 /// and store operations as a result of memset, memcpy, and memmove
1801 /// lowering. If DstAlign is zero that means it's safe to destination
1802 /// alignment can satisfy any constraint. Similarly if SrcAlign is zero it
1803 /// means there isn't a need to check it against alignment requirement,
1804 /// probably because the source does not need to be loaded. If 'IsMemset' is
1805 /// true, that means it's expanding a memset. If 'ZeroMemset' is true, that
1806 /// means it's a memset of zero. 'MemcpyStrSrc' indicates whether the memcpy
1807 /// source is constant so it does not need to be loaded.
1808 /// It returns EVT::Other if the type should be determined using generic
1809 /// target-independent logic.
1810 EVT
1811 X86TargetLowering::getOptimalMemOpType(uint64_t Size,
1812                                        unsigned DstAlign, unsigned SrcAlign,
1813                                        bool IsMemset, bool ZeroMemset,
1814                                        bool MemcpyStrSrc,
1815                                        MachineFunction &MF) const {
1816   const Function *F = MF.getFunction();
1817   if ((!IsMemset || ZeroMemset) &&
1818       !F->hasFnAttribute(Attribute::NoImplicitFloat)) {
1819     if (Size >= 16 &&
1820         (Subtarget->isUnalignedMemAccessFast() ||
1821          ((DstAlign == 0 || DstAlign >= 16) &&
1822           (SrcAlign == 0 || SrcAlign >= 16)))) {
1823       if (Size >= 32) {
1824         if (Subtarget->hasInt256())
1825           return MVT::v8i32;
1826         if (Subtarget->hasFp256())
1827           return MVT::v8f32;
1828       }
1829       if (Subtarget->hasSSE2())
1830         return MVT::v4i32;
1831       if (Subtarget->hasSSE1())
1832         return MVT::v4f32;
1833     } else if (!MemcpyStrSrc && Size >= 8 &&
1834                !Subtarget->is64Bit() &&
1835                Subtarget->hasSSE2()) {
1836       // Do not use f64 to lower memcpy if source is string constant. It's
1837       // better to use i32 to avoid the loads.
1838       return MVT::f64;
1839     }
1840   }
1841   if (Subtarget->is64Bit() && Size >= 8)
1842     return MVT::i64;
1843   return MVT::i32;
1844 }
1845
1846 bool X86TargetLowering::isSafeMemOpType(MVT VT) const {
1847   if (VT == MVT::f32)
1848     return X86ScalarSSEf32;
1849   else if (VT == MVT::f64)
1850     return X86ScalarSSEf64;
1851   return true;
1852 }
1853
1854 bool
1855 X86TargetLowering::allowsMisalignedMemoryAccesses(EVT VT,
1856                                                   unsigned,
1857                                                   unsigned,
1858                                                   bool *Fast) const {
1859   if (Fast)
1860     *Fast = Subtarget->isUnalignedMemAccessFast();
1861   return true;
1862 }
1863
1864 /// Return the entry encoding for a jump table in the
1865 /// current function.  The returned value is a member of the
1866 /// MachineJumpTableInfo::JTEntryKind enum.
1867 unsigned X86TargetLowering::getJumpTableEncoding() const {
1868   // In GOT pic mode, each entry in the jump table is emitted as a @GOTOFF
1869   // symbol.
1870   if (getTargetMachine().getRelocationModel() == Reloc::PIC_ &&
1871       Subtarget->isPICStyleGOT())
1872     return MachineJumpTableInfo::EK_Custom32;
1873
1874   // Otherwise, use the normal jump table encoding heuristics.
1875   return TargetLowering::getJumpTableEncoding();
1876 }
1877
1878 bool X86TargetLowering::useSoftFloat() const {
1879   return Subtarget->useSoftFloat();
1880 }
1881
1882 const MCExpr *
1883 X86TargetLowering::LowerCustomJumpTableEntry(const MachineJumpTableInfo *MJTI,
1884                                              const MachineBasicBlock *MBB,
1885                                              unsigned uid,MCContext &Ctx) const{
1886   assert(MBB->getParent()->getTarget().getRelocationModel() == Reloc::PIC_ &&
1887          Subtarget->isPICStyleGOT());
1888   // In 32-bit ELF systems, our jump table entries are formed with @GOTOFF
1889   // entries.
1890   return MCSymbolRefExpr::create(MBB->getSymbol(),
1891                                  MCSymbolRefExpr::VK_GOTOFF, Ctx);
1892 }
1893
1894 /// Returns relocation base for the given PIC jumptable.
1895 SDValue X86TargetLowering::getPICJumpTableRelocBase(SDValue Table,
1896                                                     SelectionDAG &DAG) const {
1897   if (!Subtarget->is64Bit())
1898     // This doesn't have SDLoc associated with it, but is not really the
1899     // same as a Register.
1900     return DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy());
1901   return Table;
1902 }
1903
1904 /// This returns the relocation base for the given PIC jumptable,
1905 /// the same as getPICJumpTableRelocBase, but as an MCExpr.
1906 const MCExpr *X86TargetLowering::
1907 getPICJumpTableRelocBaseExpr(const MachineFunction *MF, unsigned JTI,
1908                              MCContext &Ctx) const {
1909   // X86-64 uses RIP relative addressing based on the jump table label.
1910   if (Subtarget->isPICStyleRIPRel())
1911     return TargetLowering::getPICJumpTableRelocBaseExpr(MF, JTI, Ctx);
1912
1913   // Otherwise, the reference is relative to the PIC base.
1914   return MCSymbolRefExpr::create(MF->getPICBaseSymbol(), Ctx);
1915 }
1916
1917 std::pair<const TargetRegisterClass *, uint8_t>
1918 X86TargetLowering::findRepresentativeClass(const TargetRegisterInfo *TRI,
1919                                            MVT VT) const {
1920   const TargetRegisterClass *RRC = nullptr;
1921   uint8_t Cost = 1;
1922   switch (VT.SimpleTy) {
1923   default:
1924     return TargetLowering::findRepresentativeClass(TRI, VT);
1925   case MVT::i8: case MVT::i16: case MVT::i32: case MVT::i64:
1926     RRC = Subtarget->is64Bit() ? &X86::GR64RegClass : &X86::GR32RegClass;
1927     break;
1928   case MVT::x86mmx:
1929     RRC = &X86::VR64RegClass;
1930     break;
1931   case MVT::f32: case MVT::f64:
1932   case MVT::v16i8: case MVT::v8i16: case MVT::v4i32: case MVT::v2i64:
1933   case MVT::v4f32: case MVT::v2f64:
1934   case MVT::v32i8: case MVT::v8i32: case MVT::v4i64: case MVT::v8f32:
1935   case MVT::v4f64:
1936     RRC = &X86::VR128RegClass;
1937     break;
1938   }
1939   return std::make_pair(RRC, Cost);
1940 }
1941
1942 bool X86TargetLowering::getStackCookieLocation(unsigned &AddressSpace,
1943                                                unsigned &Offset) const {
1944   if (!Subtarget->isTargetLinux())
1945     return false;
1946
1947   if (Subtarget->is64Bit()) {
1948     // %fs:0x28, unless we're using a Kernel code model, in which case it's %gs:
1949     Offset = 0x28;
1950     if (getTargetMachine().getCodeModel() == CodeModel::Kernel)
1951       AddressSpace = 256;
1952     else
1953       AddressSpace = 257;
1954   } else {
1955     // %gs:0x14 on i386
1956     Offset = 0x14;
1957     AddressSpace = 256;
1958   }
1959   return true;
1960 }
1961
1962 bool X86TargetLowering::isNoopAddrSpaceCast(unsigned SrcAS,
1963                                             unsigned DestAS) const {
1964   assert(SrcAS != DestAS && "Expected different address spaces!");
1965
1966   return SrcAS < 256 && DestAS < 256;
1967 }
1968
1969 //===----------------------------------------------------------------------===//
1970 //               Return Value Calling Convention Implementation
1971 //===----------------------------------------------------------------------===//
1972
1973 #include "X86GenCallingConv.inc"
1974
1975 bool
1976 X86TargetLowering::CanLowerReturn(CallingConv::ID CallConv,
1977                                   MachineFunction &MF, bool isVarArg,
1978                         const SmallVectorImpl<ISD::OutputArg> &Outs,
1979                         LLVMContext &Context) const {
1980   SmallVector<CCValAssign, 16> RVLocs;
1981   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
1982   return CCInfo.CheckReturn(Outs, RetCC_X86);
1983 }
1984
1985 const MCPhysReg *X86TargetLowering::getScratchRegisters(CallingConv::ID) const {
1986   static const MCPhysReg ScratchRegs[] = { X86::R11, 0 };
1987   return ScratchRegs;
1988 }
1989
1990 SDValue
1991 X86TargetLowering::LowerReturn(SDValue Chain,
1992                                CallingConv::ID CallConv, bool isVarArg,
1993                                const SmallVectorImpl<ISD::OutputArg> &Outs,
1994                                const SmallVectorImpl<SDValue> &OutVals,
1995                                SDLoc dl, SelectionDAG &DAG) const {
1996   MachineFunction &MF = DAG.getMachineFunction();
1997   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
1998
1999   SmallVector<CCValAssign, 16> RVLocs;
2000   CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
2001   CCInfo.AnalyzeReturn(Outs, RetCC_X86);
2002
2003   SDValue Flag;
2004   SmallVector<SDValue, 6> RetOps;
2005   RetOps.push_back(Chain); // Operand #0 = Chain (updated below)
2006   // Operand #1 = Bytes To Pop
2007   RetOps.push_back(DAG.getTargetConstant(FuncInfo->getBytesToPopOnReturn(), dl,
2008                    MVT::i16));
2009
2010   // Copy the result values into the output registers.
2011   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2012     CCValAssign &VA = RVLocs[i];
2013     assert(VA.isRegLoc() && "Can only return in registers!");
2014     SDValue ValToCopy = OutVals[i];
2015     EVT ValVT = ValToCopy.getValueType();
2016
2017     // Promote values to the appropriate types.
2018     if (VA.getLocInfo() == CCValAssign::SExt)
2019       ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2020     else if (VA.getLocInfo() == CCValAssign::ZExt)
2021       ValToCopy = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), ValToCopy);
2022     else if (VA.getLocInfo() == CCValAssign::AExt) {
2023       if (ValVT.isVector() && ValVT.getScalarType() == MVT::i1)
2024         ValToCopy = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), ValToCopy);
2025       else
2026         ValToCopy = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), ValToCopy);
2027     }
2028     else if (VA.getLocInfo() == CCValAssign::BCvt)
2029       ValToCopy = DAG.getBitcast(VA.getLocVT(), ValToCopy);
2030
2031     assert(VA.getLocInfo() != CCValAssign::FPExt &&
2032            "Unexpected FP-extend for return value.");
2033
2034     // If this is x86-64, and we disabled SSE, we can't return FP values,
2035     // or SSE or MMX vectors.
2036     if ((ValVT == MVT::f32 || ValVT == MVT::f64 ||
2037          VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) &&
2038           (Subtarget->is64Bit() && !Subtarget->hasSSE1())) {
2039       report_fatal_error("SSE register return with SSE disabled");
2040     }
2041     // Likewise we can't return F64 values with SSE1 only.  gcc does so, but
2042     // llvm-gcc has never done it right and no one has noticed, so this
2043     // should be OK for now.
2044     if (ValVT == MVT::f64 &&
2045         (Subtarget->is64Bit() && !Subtarget->hasSSE2()))
2046       report_fatal_error("SSE2 register return with SSE2 disabled");
2047
2048     // Returns in ST0/ST1 are handled specially: these are pushed as operands to
2049     // the RET instruction and handled by the FP Stackifier.
2050     if (VA.getLocReg() == X86::FP0 ||
2051         VA.getLocReg() == X86::FP1) {
2052       // If this is a copy from an xmm register to ST(0), use an FPExtend to
2053       // change the value to the FP stack register class.
2054       if (isScalarFPTypeInSSEReg(VA.getValVT()))
2055         ValToCopy = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f80, ValToCopy);
2056       RetOps.push_back(ValToCopy);
2057       // Don't emit a copytoreg.
2058       continue;
2059     }
2060
2061     // 64-bit vector (MMX) values are returned in XMM0 / XMM1 except for v1i64
2062     // which is returned in RAX / RDX.
2063     if (Subtarget->is64Bit()) {
2064       if (ValVT == MVT::x86mmx) {
2065         if (VA.getLocReg() == X86::XMM0 || VA.getLocReg() == X86::XMM1) {
2066           ValToCopy = DAG.getBitcast(MVT::i64, ValToCopy);
2067           ValToCopy = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
2068                                   ValToCopy);
2069           // If we don't have SSE2 available, convert to v4f32 so the generated
2070           // register is legal.
2071           if (!Subtarget->hasSSE2())
2072             ValToCopy = DAG.getBitcast(MVT::v4f32, ValToCopy);
2073         }
2074       }
2075     }
2076
2077     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), ValToCopy, Flag);
2078     Flag = Chain.getValue(1);
2079     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2080   }
2081
2082   // All x86 ABIs require that for returning structs by value we copy
2083   // the sret argument into %rax/%eax (depending on ABI) for the return.
2084   // We saved the argument into a virtual register in the entry block,
2085   // so now we copy the value out and into %rax/%eax.
2086   //
2087   // Checking Function.hasStructRetAttr() here is insufficient because the IR
2088   // may not have an explicit sret argument. If FuncInfo.CanLowerReturn is
2089   // false, then an sret argument may be implicitly inserted in the SelDAG. In
2090   // either case FuncInfo->setSRetReturnReg() will have been called.
2091   if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
2092     SDValue Val = DAG.getCopyFromReg(Chain, dl, SRetReg, getPointerTy());
2093
2094     unsigned RetValReg
2095         = (Subtarget->is64Bit() && !Subtarget->isTarget64BitILP32()) ?
2096           X86::RAX : X86::EAX;
2097     Chain = DAG.getCopyToReg(Chain, dl, RetValReg, Val, Flag);
2098     Flag = Chain.getValue(1);
2099
2100     // RAX/EAX now acts like a return value.
2101     RetOps.push_back(DAG.getRegister(RetValReg, getPointerTy()));
2102   }
2103
2104   RetOps[0] = Chain;  // Update chain.
2105
2106   // Add the flag if we have it.
2107   if (Flag.getNode())
2108     RetOps.push_back(Flag);
2109
2110   return DAG.getNode(X86ISD::RET_FLAG, dl, MVT::Other, RetOps);
2111 }
2112
2113 bool X86TargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
2114   if (N->getNumValues() != 1)
2115     return false;
2116   if (!N->hasNUsesOfValue(1, 0))
2117     return false;
2118
2119   SDValue TCChain = Chain;
2120   SDNode *Copy = *N->use_begin();
2121   if (Copy->getOpcode() == ISD::CopyToReg) {
2122     // If the copy has a glue operand, we conservatively assume it isn't safe to
2123     // perform a tail call.
2124     if (Copy->getOperand(Copy->getNumOperands()-1).getValueType() == MVT::Glue)
2125       return false;
2126     TCChain = Copy->getOperand(0);
2127   } else if (Copy->getOpcode() != ISD::FP_EXTEND)
2128     return false;
2129
2130   bool HasRet = false;
2131   for (SDNode::use_iterator UI = Copy->use_begin(), UE = Copy->use_end();
2132        UI != UE; ++UI) {
2133     if (UI->getOpcode() != X86ISD::RET_FLAG)
2134       return false;
2135     // If we are returning more than one value, we can definitely
2136     // not make a tail call see PR19530
2137     if (UI->getNumOperands() > 4)
2138       return false;
2139     if (UI->getNumOperands() == 4 &&
2140         UI->getOperand(UI->getNumOperands()-1).getValueType() != MVT::Glue)
2141       return false;
2142     HasRet = true;
2143   }
2144
2145   if (!HasRet)
2146     return false;
2147
2148   Chain = TCChain;
2149   return true;
2150 }
2151
2152 EVT
2153 X86TargetLowering::getTypeForExtArgOrReturn(LLVMContext &Context, EVT VT,
2154                                             ISD::NodeType ExtendKind) const {
2155   MVT ReturnMVT;
2156   // TODO: Is this also valid on 32-bit?
2157   if (Subtarget->is64Bit() && VT == MVT::i1 && ExtendKind == ISD::ZERO_EXTEND)
2158     ReturnMVT = MVT::i8;
2159   else
2160     ReturnMVT = MVT::i32;
2161
2162   EVT MinVT = getRegisterType(Context, ReturnMVT);
2163   return VT.bitsLT(MinVT) ? MinVT : VT;
2164 }
2165
2166 /// Lower the result values of a call into the
2167 /// appropriate copies out of appropriate physical registers.
2168 ///
2169 SDValue
2170 X86TargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2171                                    CallingConv::ID CallConv, bool isVarArg,
2172                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2173                                    SDLoc dl, SelectionDAG &DAG,
2174                                    SmallVectorImpl<SDValue> &InVals) const {
2175
2176   // Assign locations to each value returned by this call.
2177   SmallVector<CCValAssign, 16> RVLocs;
2178   bool Is64Bit = Subtarget->is64Bit();
2179   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
2180                  *DAG.getContext());
2181   CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
2182
2183   // Copy all of the result registers out of their specified physreg.
2184   for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
2185     CCValAssign &VA = RVLocs[i];
2186     EVT CopyVT = VA.getLocVT();
2187
2188     // If this is x86-64, and we disabled SSE, we can't return FP values
2189     if ((CopyVT == MVT::f32 || CopyVT == MVT::f64) &&
2190         ((Is64Bit || Ins[i].Flags.isInReg()) && !Subtarget->hasSSE1())) {
2191       report_fatal_error("SSE register return with SSE disabled");
2192     }
2193
2194     // If we prefer to use the value in xmm registers, copy it out as f80 and
2195     // use a truncate to move it from fp stack reg to xmm reg.
2196     bool RoundAfterCopy = false;
2197     if ((VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1) &&
2198         isScalarFPTypeInSSEReg(VA.getValVT())) {
2199       CopyVT = MVT::f80;
2200       RoundAfterCopy = (CopyVT != VA.getLocVT());
2201     }
2202
2203     Chain = DAG.getCopyFromReg(Chain, dl, VA.getLocReg(),
2204                                CopyVT, InFlag).getValue(1);
2205     SDValue Val = Chain.getValue(0);
2206
2207     if (RoundAfterCopy)
2208       Val = DAG.getNode(ISD::FP_ROUND, dl, VA.getValVT(), Val,
2209                         // This truncation won't change the value.
2210                         DAG.getIntPtrConstant(1, dl));
2211
2212     if (VA.isExtInLoc() && VA.getValVT().getScalarType() == MVT::i1)
2213       Val = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val);
2214
2215     InFlag = Chain.getValue(2);
2216     InVals.push_back(Val);
2217   }
2218
2219   return Chain;
2220 }
2221
2222 //===----------------------------------------------------------------------===//
2223 //                C & StdCall & Fast Calling Convention implementation
2224 //===----------------------------------------------------------------------===//
2225 //  StdCall calling convention seems to be standard for many Windows' API
2226 //  routines and around. It differs from C calling convention just a little:
2227 //  callee should clean up the stack, not caller. Symbols should be also
2228 //  decorated in some fancy way :) It doesn't support any vector arguments.
2229 //  For info on fast calling convention see Fast Calling Convention (tail call)
2230 //  implementation LowerX86_32FastCCCallTo.
2231
2232 /// CallIsStructReturn - Determines whether a call uses struct return
2233 /// semantics.
2234 enum StructReturnType {
2235   NotStructReturn,
2236   RegStructReturn,
2237   StackStructReturn
2238 };
2239 static StructReturnType
2240 callIsStructReturn(const SmallVectorImpl<ISD::OutputArg> &Outs) {
2241   if (Outs.empty())
2242     return NotStructReturn;
2243
2244   const ISD::ArgFlagsTy &Flags = Outs[0].Flags;
2245   if (!Flags.isSRet())
2246     return NotStructReturn;
2247   if (Flags.isInReg())
2248     return RegStructReturn;
2249   return StackStructReturn;
2250 }
2251
2252 /// Determines whether a function uses struct return semantics.
2253 static StructReturnType
2254 argsAreStructReturn(const SmallVectorImpl<ISD::InputArg> &Ins) {
2255   if (Ins.empty())
2256     return NotStructReturn;
2257
2258   const ISD::ArgFlagsTy &Flags = Ins[0].Flags;
2259   if (!Flags.isSRet())
2260     return NotStructReturn;
2261   if (Flags.isInReg())
2262     return RegStructReturn;
2263   return StackStructReturn;
2264 }
2265
2266 /// Make a copy of an aggregate at address specified by "Src" to address
2267 /// "Dst" with size and alignment information specified by the specific
2268 /// parameter attribute. The copy will be passed as a byval function parameter.
2269 static SDValue
2270 CreateCopyOfByValArgument(SDValue Src, SDValue Dst, SDValue Chain,
2271                           ISD::ArgFlagsTy Flags, SelectionDAG &DAG,
2272                           SDLoc dl) {
2273   SDValue SizeNode = DAG.getConstant(Flags.getByValSize(), dl, MVT::i32);
2274
2275   return DAG.getMemcpy(Chain, dl, Dst, Src, SizeNode, Flags.getByValAlign(),
2276                        /*isVolatile*/false, /*AlwaysInline=*/true,
2277                        /*isTailCall*/false,
2278                        MachinePointerInfo(), MachinePointerInfo());
2279 }
2280
2281 /// Return true if the calling convention is one that
2282 /// supports tail call optimization.
2283 static bool IsTailCallConvention(CallingConv::ID CC) {
2284   return (CC == CallingConv::Fast || CC == CallingConv::GHC ||
2285           CC == CallingConv::HiPE);
2286 }
2287
2288 /// \brief Return true if the calling convention is a C calling convention.
2289 static bool IsCCallConvention(CallingConv::ID CC) {
2290   return (CC == CallingConv::C || CC == CallingConv::X86_64_Win64 ||
2291           CC == CallingConv::X86_64_SysV);
2292 }
2293
2294 bool X86TargetLowering::mayBeEmittedAsTailCall(CallInst *CI) const {
2295   auto Attr =
2296       CI->getParent()->getParent()->getFnAttribute("disable-tail-calls");
2297   if (!CI->isTailCall() || Attr.getValueAsString() == "true")
2298     return false;
2299
2300   CallSite CS(CI);
2301   CallingConv::ID CalleeCC = CS.getCallingConv();
2302   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
2303     return false;
2304
2305   return true;
2306 }
2307
2308 /// Return true if the function is being made into
2309 /// a tailcall target by changing its ABI.
2310 static bool FuncIsMadeTailCallSafe(CallingConv::ID CC,
2311                                    bool GuaranteedTailCallOpt) {
2312   return GuaranteedTailCallOpt && IsTailCallConvention(CC);
2313 }
2314
2315 SDValue
2316 X86TargetLowering::LowerMemArgument(SDValue Chain,
2317                                     CallingConv::ID CallConv,
2318                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2319                                     SDLoc dl, SelectionDAG &DAG,
2320                                     const CCValAssign &VA,
2321                                     MachineFrameInfo *MFI,
2322                                     unsigned i) const {
2323   // Create the nodes corresponding to a load from this parameter slot.
2324   ISD::ArgFlagsTy Flags = Ins[i].Flags;
2325   bool AlwaysUseMutable = FuncIsMadeTailCallSafe(
2326       CallConv, DAG.getTarget().Options.GuaranteedTailCallOpt);
2327   bool isImmutable = !AlwaysUseMutable && !Flags.isByVal();
2328   EVT ValVT;
2329
2330   // If value is passed by pointer we have address passed instead of the value
2331   // itself.
2332   bool ExtendedInMem = VA.isExtInLoc() &&
2333     VA.getValVT().getScalarType() == MVT::i1;
2334
2335   if (VA.getLocInfo() == CCValAssign::Indirect || ExtendedInMem)
2336     ValVT = VA.getLocVT();
2337   else
2338     ValVT = VA.getValVT();
2339
2340   // FIXME: For now, all byval parameter objects are marked mutable. This can be
2341   // changed with more analysis.
2342   // In case of tail call optimization mark all arguments mutable. Since they
2343   // could be overwritten by lowering of arguments in case of a tail call.
2344   if (Flags.isByVal()) {
2345     unsigned Bytes = Flags.getByValSize();
2346     if (Bytes == 0) Bytes = 1; // Don't create zero-sized stack objects.
2347     int FI = MFI->CreateFixedObject(Bytes, VA.getLocMemOffset(), isImmutable);
2348     return DAG.getFrameIndex(FI, getPointerTy());
2349   } else {
2350     int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2351                                     VA.getLocMemOffset(), isImmutable);
2352     SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2353     SDValue Val =  DAG.getLoad(ValVT, dl, Chain, FIN,
2354                                MachinePointerInfo::getFixedStack(FI),
2355                                false, false, false, 0);
2356     return ExtendedInMem ?
2357       DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Val) : Val;
2358   }
2359 }
2360
2361 // FIXME: Get this from tablegen.
2362 static ArrayRef<MCPhysReg> get64BitArgumentGPRs(CallingConv::ID CallConv,
2363                                                 const X86Subtarget *Subtarget) {
2364   assert(Subtarget->is64Bit());
2365
2366   if (Subtarget->isCallingConvWin64(CallConv)) {
2367     static const MCPhysReg GPR64ArgRegsWin64[] = {
2368       X86::RCX, X86::RDX, X86::R8,  X86::R9
2369     };
2370     return makeArrayRef(std::begin(GPR64ArgRegsWin64), std::end(GPR64ArgRegsWin64));
2371   }
2372
2373   static const MCPhysReg GPR64ArgRegs64Bit[] = {
2374     X86::RDI, X86::RSI, X86::RDX, X86::RCX, X86::R8, X86::R9
2375   };
2376   return makeArrayRef(std::begin(GPR64ArgRegs64Bit), std::end(GPR64ArgRegs64Bit));
2377 }
2378
2379 // FIXME: Get this from tablegen.
2380 static ArrayRef<MCPhysReg> get64BitArgumentXMMs(MachineFunction &MF,
2381                                                 CallingConv::ID CallConv,
2382                                                 const X86Subtarget *Subtarget) {
2383   assert(Subtarget->is64Bit());
2384   if (Subtarget->isCallingConvWin64(CallConv)) {
2385     // The XMM registers which might contain var arg parameters are shadowed
2386     // in their paired GPR.  So we only need to save the GPR to their home
2387     // slots.
2388     // TODO: __vectorcall will change this.
2389     return None;
2390   }
2391
2392   const Function *Fn = MF.getFunction();
2393   bool NoImplicitFloatOps = Fn->hasFnAttribute(Attribute::NoImplicitFloat);
2394   bool isSoftFloat = Subtarget->useSoftFloat();
2395   assert(!(isSoftFloat && NoImplicitFloatOps) &&
2396          "SSE register cannot be used when SSE is disabled!");
2397   if (isSoftFloat || NoImplicitFloatOps || !Subtarget->hasSSE1())
2398     // Kernel mode asks for SSE to be disabled, so there are no XMM argument
2399     // registers.
2400     return None;
2401
2402   static const MCPhysReg XMMArgRegs64Bit[] = {
2403     X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
2404     X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
2405   };
2406   return makeArrayRef(std::begin(XMMArgRegs64Bit), std::end(XMMArgRegs64Bit));
2407 }
2408
2409 SDValue
2410 X86TargetLowering::LowerFormalArguments(SDValue Chain,
2411                                         CallingConv::ID CallConv,
2412                                         bool isVarArg,
2413                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2414                                         SDLoc dl,
2415                                         SelectionDAG &DAG,
2416                                         SmallVectorImpl<SDValue> &InVals)
2417                                           const {
2418   MachineFunction &MF = DAG.getMachineFunction();
2419   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
2420   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
2421
2422   const Function* Fn = MF.getFunction();
2423   if (Fn->hasExternalLinkage() &&
2424       Subtarget->isTargetCygMing() &&
2425       Fn->getName() == "main")
2426     FuncInfo->setForceFramePointer(true);
2427
2428   MachineFrameInfo *MFI = MF.getFrameInfo();
2429   bool Is64Bit = Subtarget->is64Bit();
2430   bool IsWin64 = Subtarget->isCallingConvWin64(CallConv);
2431
2432   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2433          "Var args not supported with calling convention fastcc, ghc or hipe");
2434
2435   // Assign locations to all of the incoming arguments.
2436   SmallVector<CCValAssign, 16> ArgLocs;
2437   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2438
2439   // Allocate shadow area for Win64
2440   if (IsWin64)
2441     CCInfo.AllocateStack(32, 8);
2442
2443   CCInfo.AnalyzeFormalArguments(Ins, CC_X86);
2444
2445   unsigned LastVal = ~0U;
2446   SDValue ArgValue;
2447   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2448     CCValAssign &VA = ArgLocs[i];
2449     // TODO: If an arg is passed in two places (e.g. reg and stack), skip later
2450     // places.
2451     assert(VA.getValNo() != LastVal &&
2452            "Don't support value assigned to multiple locs yet");
2453     (void)LastVal;
2454     LastVal = VA.getValNo();
2455
2456     if (VA.isRegLoc()) {
2457       EVT RegVT = VA.getLocVT();
2458       const TargetRegisterClass *RC;
2459       if (RegVT == MVT::i32)
2460         RC = &X86::GR32RegClass;
2461       else if (Is64Bit && RegVT == MVT::i64)
2462         RC = &X86::GR64RegClass;
2463       else if (RegVT == MVT::f32)
2464         RC = &X86::FR32RegClass;
2465       else if (RegVT == MVT::f64)
2466         RC = &X86::FR64RegClass;
2467       else if (RegVT.is512BitVector())
2468         RC = &X86::VR512RegClass;
2469       else if (RegVT.is256BitVector())
2470         RC = &X86::VR256RegClass;
2471       else if (RegVT.is128BitVector())
2472         RC = &X86::VR128RegClass;
2473       else if (RegVT == MVT::x86mmx)
2474         RC = &X86::VR64RegClass;
2475       else if (RegVT == MVT::i1)
2476         RC = &X86::VK1RegClass;
2477       else if (RegVT == MVT::v8i1)
2478         RC = &X86::VK8RegClass;
2479       else if (RegVT == MVT::v16i1)
2480         RC = &X86::VK16RegClass;
2481       else if (RegVT == MVT::v32i1)
2482         RC = &X86::VK32RegClass;
2483       else if (RegVT == MVT::v64i1)
2484         RC = &X86::VK64RegClass;
2485       else
2486         llvm_unreachable("Unknown argument type!");
2487
2488       unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
2489       ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
2490
2491       // If this is an 8 or 16-bit value, it is really passed promoted to 32
2492       // bits.  Insert an assert[sz]ext to capture this, then truncate to the
2493       // right size.
2494       if (VA.getLocInfo() == CCValAssign::SExt)
2495         ArgValue = DAG.getNode(ISD::AssertSext, dl, RegVT, ArgValue,
2496                                DAG.getValueType(VA.getValVT()));
2497       else if (VA.getLocInfo() == CCValAssign::ZExt)
2498         ArgValue = DAG.getNode(ISD::AssertZext, dl, RegVT, ArgValue,
2499                                DAG.getValueType(VA.getValVT()));
2500       else if (VA.getLocInfo() == CCValAssign::BCvt)
2501         ArgValue = DAG.getBitcast(VA.getValVT(), ArgValue);
2502
2503       if (VA.isExtInLoc()) {
2504         // Handle MMX values passed in XMM regs.
2505         if (RegVT.isVector() && VA.getValVT().getScalarType() != MVT::i1)
2506           ArgValue = DAG.getNode(X86ISD::MOVDQ2Q, dl, VA.getValVT(), ArgValue);
2507         else
2508           ArgValue = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), ArgValue);
2509       }
2510     } else {
2511       assert(VA.isMemLoc());
2512       ArgValue = LowerMemArgument(Chain, CallConv, Ins, dl, DAG, VA, MFI, i);
2513     }
2514
2515     // If value is passed via pointer - do a load.
2516     if (VA.getLocInfo() == CCValAssign::Indirect)
2517       ArgValue = DAG.getLoad(VA.getValVT(), dl, Chain, ArgValue,
2518                              MachinePointerInfo(), false, false, false, 0);
2519
2520     InVals.push_back(ArgValue);
2521   }
2522
2523   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2524     // All x86 ABIs require that for returning structs by value we copy the
2525     // sret argument into %rax/%eax (depending on ABI) for the return. Save
2526     // the argument into a virtual register so that we can access it from the
2527     // return points.
2528     if (Ins[i].Flags.isSRet()) {
2529       unsigned Reg = FuncInfo->getSRetReturnReg();
2530       if (!Reg) {
2531         MVT PtrTy = getPointerTy();
2532         Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
2533         FuncInfo->setSRetReturnReg(Reg);
2534       }
2535       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[i]);
2536       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
2537       break;
2538     }
2539   }
2540
2541   unsigned StackSize = CCInfo.getNextStackOffset();
2542   // Align stack specially for tail calls.
2543   if (FuncIsMadeTailCallSafe(CallConv,
2544                              MF.getTarget().Options.GuaranteedTailCallOpt))
2545     StackSize = GetAlignedArgumentStackSize(StackSize, DAG);
2546
2547   // If the function takes variable number of arguments, make a frame index for
2548   // the start of the first vararg value... for expansion of llvm.va_start. We
2549   // can skip this if there are no va_start calls.
2550   if (MFI->hasVAStart() &&
2551       (Is64Bit || (CallConv != CallingConv::X86_FastCall &&
2552                    CallConv != CallingConv::X86_ThisCall))) {
2553     FuncInfo->setVarArgsFrameIndex(
2554         MFI->CreateFixedObject(1, StackSize, true));
2555   }
2556
2557   MachineModuleInfo &MMI = MF.getMMI();
2558   const Function *WinEHParent = nullptr;
2559   if (IsWin64 && MMI.hasWinEHFuncInfo(Fn))
2560     WinEHParent = MMI.getWinEHParent(Fn);
2561   bool IsWinEHOutlined = WinEHParent && WinEHParent != Fn;
2562   bool IsWinEHParent = WinEHParent && WinEHParent == Fn;
2563
2564   // Figure out if XMM registers are in use.
2565   assert(!(Subtarget->useSoftFloat() &&
2566            Fn->hasFnAttribute(Attribute::NoImplicitFloat)) &&
2567          "SSE register cannot be used when SSE is disabled!");
2568
2569   // 64-bit calling conventions support varargs and register parameters, so we
2570   // have to do extra work to spill them in the prologue.
2571   if (Is64Bit && isVarArg && MFI->hasVAStart()) {
2572     // Find the first unallocated argument registers.
2573     ArrayRef<MCPhysReg> ArgGPRs = get64BitArgumentGPRs(CallConv, Subtarget);
2574     ArrayRef<MCPhysReg> ArgXMMs = get64BitArgumentXMMs(MF, CallConv, Subtarget);
2575     unsigned NumIntRegs = CCInfo.getFirstUnallocated(ArgGPRs);
2576     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(ArgXMMs);
2577     assert(!(NumXMMRegs && !Subtarget->hasSSE1()) &&
2578            "SSE register cannot be used when SSE is disabled!");
2579
2580     // Gather all the live in physical registers.
2581     SmallVector<SDValue, 6> LiveGPRs;
2582     SmallVector<SDValue, 8> LiveXMMRegs;
2583     SDValue ALVal;
2584     for (MCPhysReg Reg : ArgGPRs.slice(NumIntRegs)) {
2585       unsigned GPR = MF.addLiveIn(Reg, &X86::GR64RegClass);
2586       LiveGPRs.push_back(
2587           DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64));
2588     }
2589     if (!ArgXMMs.empty()) {
2590       unsigned AL = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2591       ALVal = DAG.getCopyFromReg(Chain, dl, AL, MVT::i8);
2592       for (MCPhysReg Reg : ArgXMMs.slice(NumXMMRegs)) {
2593         unsigned XMMReg = MF.addLiveIn(Reg, &X86::VR128RegClass);
2594         LiveXMMRegs.push_back(
2595             DAG.getCopyFromReg(Chain, dl, XMMReg, MVT::v4f32));
2596       }
2597     }
2598
2599     if (IsWin64) {
2600       // Get to the caller-allocated home save location.  Add 8 to account
2601       // for the return address.
2602       int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2603       FuncInfo->setRegSaveFrameIndex(
2604           MFI->CreateFixedObject(1, NumIntRegs * 8 + HomeOffset, false));
2605       // Fixup to set vararg frame on shadow area (4 x i64).
2606       if (NumIntRegs < 4)
2607         FuncInfo->setVarArgsFrameIndex(FuncInfo->getRegSaveFrameIndex());
2608     } else {
2609       // For X86-64, if there are vararg parameters that are passed via
2610       // registers, then we must store them to their spots on the stack so
2611       // they may be loaded by deferencing the result of va_next.
2612       FuncInfo->setVarArgsGPOffset(NumIntRegs * 8);
2613       FuncInfo->setVarArgsFPOffset(ArgGPRs.size() * 8 + NumXMMRegs * 16);
2614       FuncInfo->setRegSaveFrameIndex(MFI->CreateStackObject(
2615           ArgGPRs.size() * 8 + ArgXMMs.size() * 16, 16, false));
2616     }
2617
2618     // Store the integer parameter registers.
2619     SmallVector<SDValue, 8> MemOps;
2620     SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
2621                                       getPointerTy());
2622     unsigned Offset = FuncInfo->getVarArgsGPOffset();
2623     for (SDValue Val : LiveGPRs) {
2624       SDValue FIN = DAG.getNode(ISD::ADD, dl, getPointerTy(), RSFIN,
2625                                 DAG.getIntPtrConstant(Offset, dl));
2626       SDValue Store =
2627         DAG.getStore(Val.getValue(1), dl, Val, FIN,
2628                      MachinePointerInfo::getFixedStack(
2629                        FuncInfo->getRegSaveFrameIndex(), Offset),
2630                      false, false, 0);
2631       MemOps.push_back(Store);
2632       Offset += 8;
2633     }
2634
2635     if (!ArgXMMs.empty() && NumXMMRegs != ArgXMMs.size()) {
2636       // Now store the XMM (fp + vector) parameter registers.
2637       SmallVector<SDValue, 12> SaveXMMOps;
2638       SaveXMMOps.push_back(Chain);
2639       SaveXMMOps.push_back(ALVal);
2640       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2641                              FuncInfo->getRegSaveFrameIndex(), dl));
2642       SaveXMMOps.push_back(DAG.getIntPtrConstant(
2643                              FuncInfo->getVarArgsFPOffset(), dl));
2644       SaveXMMOps.insert(SaveXMMOps.end(), LiveXMMRegs.begin(),
2645                         LiveXMMRegs.end());
2646       MemOps.push_back(DAG.getNode(X86ISD::VASTART_SAVE_XMM_REGS, dl,
2647                                    MVT::Other, SaveXMMOps));
2648     }
2649
2650     if (!MemOps.empty())
2651       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOps);
2652   } else if (IsWinEHOutlined) {
2653     // Get to the caller-allocated home save location.  Add 8 to account
2654     // for the return address.
2655     int HomeOffset = TFI.getOffsetOfLocalArea() + 8;
2656     FuncInfo->setRegSaveFrameIndex(MFI->CreateFixedObject(
2657         /*Size=*/1, /*SPOffset=*/HomeOffset + 8, /*Immutable=*/false));
2658
2659     MMI.getWinEHFuncInfo(Fn)
2660         .CatchHandlerParentFrameObjIdx[const_cast<Function *>(Fn)] =
2661         FuncInfo->getRegSaveFrameIndex();
2662
2663     // Store the second integer parameter (rdx) into rsp+16 relative to the
2664     // stack pointer at the entry of the function.
2665     SDValue RSFIN =
2666         DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(), getPointerTy());
2667     unsigned GPR = MF.addLiveIn(X86::RDX, &X86::GR64RegClass);
2668     SDValue Val = DAG.getCopyFromReg(Chain, dl, GPR, MVT::i64);
2669     Chain = DAG.getStore(
2670         Val.getValue(1), dl, Val, RSFIN,
2671         MachinePointerInfo::getFixedStack(FuncInfo->getRegSaveFrameIndex()),
2672         /*isVolatile=*/true, /*isNonTemporal=*/false, /*Alignment=*/0);
2673   }
2674
2675   if (isVarArg && MFI->hasMustTailInVarArgFunc()) {
2676     // Find the largest legal vector type.
2677     MVT VecVT = MVT::Other;
2678     // FIXME: Only some x86_32 calling conventions support AVX512.
2679     if (Subtarget->hasAVX512() &&
2680         (Is64Bit || (CallConv == CallingConv::X86_VectorCall ||
2681                      CallConv == CallingConv::Intel_OCL_BI)))
2682       VecVT = MVT::v16f32;
2683     else if (Subtarget->hasAVX())
2684       VecVT = MVT::v8f32;
2685     else if (Subtarget->hasSSE2())
2686       VecVT = MVT::v4f32;
2687
2688     // We forward some GPRs and some vector types.
2689     SmallVector<MVT, 2> RegParmTypes;
2690     MVT IntVT = Is64Bit ? MVT::i64 : MVT::i32;
2691     RegParmTypes.push_back(IntVT);
2692     if (VecVT != MVT::Other)
2693       RegParmTypes.push_back(VecVT);
2694
2695     // Compute the set of forwarded registers. The rest are scratch.
2696     SmallVectorImpl<ForwardedRegister> &Forwards =
2697         FuncInfo->getForwardedMustTailRegParms();
2698     CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes, CC_X86);
2699
2700     // Conservatively forward AL on x86_64, since it might be used for varargs.
2701     if (Is64Bit && !CCInfo.isAllocated(X86::AL)) {
2702       unsigned ALVReg = MF.addLiveIn(X86::AL, &X86::GR8RegClass);
2703       Forwards.push_back(ForwardedRegister(ALVReg, X86::AL, MVT::i8));
2704     }
2705
2706     // Copy all forwards from physical to virtual registers.
2707     for (ForwardedRegister &F : Forwards) {
2708       // FIXME: Can we use a less constrained schedule?
2709       SDValue RegVal = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
2710       F.VReg = MF.getRegInfo().createVirtualRegister(getRegClassFor(F.VT));
2711       Chain = DAG.getCopyToReg(Chain, dl, F.VReg, RegVal);
2712     }
2713   }
2714
2715   // Some CCs need callee pop.
2716   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
2717                        MF.getTarget().Options.GuaranteedTailCallOpt)) {
2718     FuncInfo->setBytesToPopOnReturn(StackSize); // Callee pops everything.
2719   } else {
2720     FuncInfo->setBytesToPopOnReturn(0); // Callee pops nothing.
2721     // If this is an sret function, the return should pop the hidden pointer.
2722     if (!Is64Bit && !IsTailCallConvention(CallConv) &&
2723         !Subtarget->getTargetTriple().isOSMSVCRT() &&
2724         argsAreStructReturn(Ins) == StackStructReturn)
2725       FuncInfo->setBytesToPopOnReturn(4);
2726   }
2727
2728   if (!Is64Bit) {
2729     // RegSaveFrameIndex is X86-64 only.
2730     FuncInfo->setRegSaveFrameIndex(0xAAAAAAA);
2731     if (CallConv == CallingConv::X86_FastCall ||
2732         CallConv == CallingConv::X86_ThisCall)
2733       // fastcc functions can't have varargs.
2734       FuncInfo->setVarArgsFrameIndex(0xAAAAAAA);
2735   }
2736
2737   FuncInfo->setArgumentStackSize(StackSize);
2738
2739   if (IsWinEHParent) {
2740     int UnwindHelpFI = MFI->CreateStackObject(8, 8, /*isSS=*/false);
2741     SDValue StackSlot = DAG.getFrameIndex(UnwindHelpFI, MVT::i64);
2742     MMI.getWinEHFuncInfo(MF.getFunction()).UnwindHelpFrameIdx = UnwindHelpFI;
2743     SDValue Neg2 = DAG.getConstant(-2, dl, MVT::i64);
2744     Chain = DAG.getStore(Chain, dl, Neg2, StackSlot,
2745                          MachinePointerInfo::getFixedStack(UnwindHelpFI),
2746                          /*isVolatile=*/true,
2747                          /*isNonTemporal=*/false, /*Alignment=*/0);
2748   }
2749
2750   return Chain;
2751 }
2752
2753 SDValue
2754 X86TargetLowering::LowerMemOpCallTo(SDValue Chain,
2755                                     SDValue StackPtr, SDValue Arg,
2756                                     SDLoc dl, SelectionDAG &DAG,
2757                                     const CCValAssign &VA,
2758                                     ISD::ArgFlagsTy Flags) const {
2759   unsigned LocMemOffset = VA.getLocMemOffset();
2760   SDValue PtrOff = DAG.getIntPtrConstant(LocMemOffset, dl);
2761   PtrOff = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, PtrOff);
2762   if (Flags.isByVal())
2763     return CreateCopyOfByValArgument(Arg, PtrOff, Chain, Flags, DAG, dl);
2764
2765   return DAG.getStore(Chain, dl, Arg, PtrOff,
2766                       MachinePointerInfo::getStack(LocMemOffset),
2767                       false, false, 0);
2768 }
2769
2770 /// Emit a load of return address if tail call
2771 /// optimization is performed and it is required.
2772 SDValue
2773 X86TargetLowering::EmitTailCallLoadRetAddr(SelectionDAG &DAG,
2774                                            SDValue &OutRetAddr, SDValue Chain,
2775                                            bool IsTailCall, bool Is64Bit,
2776                                            int FPDiff, SDLoc dl) const {
2777   // Adjust the Return address stack slot.
2778   EVT VT = getPointerTy();
2779   OutRetAddr = getReturnAddressFrameIndex(DAG);
2780
2781   // Load the "old" Return address.
2782   OutRetAddr = DAG.getLoad(VT, dl, Chain, OutRetAddr, MachinePointerInfo(),
2783                            false, false, false, 0);
2784   return SDValue(OutRetAddr.getNode(), 1);
2785 }
2786
2787 /// Emit a store of the return address if tail call
2788 /// optimization is performed and it is required (FPDiff!=0).
2789 static SDValue EmitTailCallStoreRetAddr(SelectionDAG &DAG, MachineFunction &MF,
2790                                         SDValue Chain, SDValue RetAddrFrIdx,
2791                                         EVT PtrVT, unsigned SlotSize,
2792                                         int FPDiff, SDLoc dl) {
2793   // Store the return address to the appropriate stack slot.
2794   if (!FPDiff) return Chain;
2795   // Calculate the new stack slot for the return address.
2796   int NewReturnAddrFI =
2797     MF.getFrameInfo()->CreateFixedObject(SlotSize, (int64_t)FPDiff - SlotSize,
2798                                          false);
2799   SDValue NewRetAddrFrIdx = DAG.getFrameIndex(NewReturnAddrFI, PtrVT);
2800   Chain = DAG.getStore(Chain, dl, RetAddrFrIdx, NewRetAddrFrIdx,
2801                        MachinePointerInfo::getFixedStack(NewReturnAddrFI),
2802                        false, false, 0);
2803   return Chain;
2804 }
2805
2806 SDValue
2807 X86TargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2808                              SmallVectorImpl<SDValue> &InVals) const {
2809   SelectionDAG &DAG                     = CLI.DAG;
2810   SDLoc &dl                             = CLI.DL;
2811   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2812   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2813   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2814   SDValue Chain                         = CLI.Chain;
2815   SDValue Callee                        = CLI.Callee;
2816   CallingConv::ID CallConv              = CLI.CallConv;
2817   bool &isTailCall                      = CLI.IsTailCall;
2818   bool isVarArg                         = CLI.IsVarArg;
2819
2820   MachineFunction &MF = DAG.getMachineFunction();
2821   bool Is64Bit        = Subtarget->is64Bit();
2822   bool IsWin64        = Subtarget->isCallingConvWin64(CallConv);
2823   StructReturnType SR = callIsStructReturn(Outs);
2824   bool IsSibcall      = false;
2825   X86MachineFunctionInfo *X86Info = MF.getInfo<X86MachineFunctionInfo>();
2826   auto Attr = MF.getFunction()->getFnAttribute("disable-tail-calls");
2827
2828   if (Attr.getValueAsString() == "true")
2829     isTailCall = false;
2830
2831   if (Subtarget->isPICStyleGOT() &&
2832       !MF.getTarget().Options.GuaranteedTailCallOpt) {
2833     // If we are using a GOT, disable tail calls to external symbols with
2834     // default visibility. Tail calling such a symbol requires using a GOT
2835     // relocation, which forces early binding of the symbol. This breaks code
2836     // that require lazy function symbol resolution. Using musttail or
2837     // GuaranteedTailCallOpt will override this.
2838     GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
2839     if (!G || (!G->getGlobal()->hasLocalLinkage() &&
2840                G->getGlobal()->hasDefaultVisibility()))
2841       isTailCall = false;
2842   }
2843
2844   bool IsMustTail = CLI.CS && CLI.CS->isMustTailCall();
2845   if (IsMustTail) {
2846     // Force this to be a tail call.  The verifier rules are enough to ensure
2847     // that we can lower this successfully without moving the return address
2848     // around.
2849     isTailCall = true;
2850   } else if (isTailCall) {
2851     // Check if it's really possible to do a tail call.
2852     isTailCall = IsEligibleForTailCallOptimization(Callee, CallConv,
2853                     isVarArg, SR != NotStructReturn,
2854                     MF.getFunction()->hasStructRetAttr(), CLI.RetTy,
2855                     Outs, OutVals, Ins, DAG);
2856
2857     // Sibcalls are automatically detected tailcalls which do not require
2858     // ABI changes.
2859     if (!MF.getTarget().Options.GuaranteedTailCallOpt && isTailCall)
2860       IsSibcall = true;
2861
2862     if (isTailCall)
2863       ++NumTailCalls;
2864   }
2865
2866   assert(!(isVarArg && IsTailCallConvention(CallConv)) &&
2867          "Var args not supported with calling convention fastcc, ghc or hipe");
2868
2869   // Analyze operands of the call, assigning locations to each operand.
2870   SmallVector<CCValAssign, 16> ArgLocs;
2871   CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
2872
2873   // Allocate shadow area for Win64
2874   if (IsWin64)
2875     CCInfo.AllocateStack(32, 8);
2876
2877   CCInfo.AnalyzeCallOperands(Outs, CC_X86);
2878
2879   // Get a count of how many bytes are to be pushed on the stack.
2880   unsigned NumBytes = CCInfo.getNextStackOffset();
2881   if (IsSibcall)
2882     // This is a sibcall. The memory operands are available in caller's
2883     // own caller's stack.
2884     NumBytes = 0;
2885   else if (MF.getTarget().Options.GuaranteedTailCallOpt &&
2886            IsTailCallConvention(CallConv))
2887     NumBytes = GetAlignedArgumentStackSize(NumBytes, DAG);
2888
2889   int FPDiff = 0;
2890   if (isTailCall && !IsSibcall && !IsMustTail) {
2891     // Lower arguments at fp - stackoffset + fpdiff.
2892     unsigned NumBytesCallerPushed = X86Info->getBytesToPopOnReturn();
2893
2894     FPDiff = NumBytesCallerPushed - NumBytes;
2895
2896     // Set the delta of movement of the returnaddr stackslot.
2897     // But only set if delta is greater than previous delta.
2898     if (FPDiff < X86Info->getTCReturnAddrDelta())
2899       X86Info->setTCReturnAddrDelta(FPDiff);
2900   }
2901
2902   unsigned NumBytesToPush = NumBytes;
2903   unsigned NumBytesToPop = NumBytes;
2904
2905   // If we have an inalloca argument, all stack space has already been allocated
2906   // for us and be right at the top of the stack.  We don't support multiple
2907   // arguments passed in memory when using inalloca.
2908   if (!Outs.empty() && Outs.back().Flags.isInAlloca()) {
2909     NumBytesToPush = 0;
2910     if (!ArgLocs.back().isMemLoc())
2911       report_fatal_error("cannot use inalloca attribute on a register "
2912                          "parameter");
2913     if (ArgLocs.back().getLocMemOffset() != 0)
2914       report_fatal_error("any parameter with the inalloca attribute must be "
2915                          "the only memory argument");
2916   }
2917
2918   if (!IsSibcall)
2919     Chain = DAG.getCALLSEQ_START(
2920         Chain, DAG.getIntPtrConstant(NumBytesToPush, dl, true), dl);
2921
2922   SDValue RetAddrFrIdx;
2923   // Load return address for tail calls.
2924   if (isTailCall && FPDiff)
2925     Chain = EmitTailCallLoadRetAddr(DAG, RetAddrFrIdx, Chain, isTailCall,
2926                                     Is64Bit, FPDiff, dl);
2927
2928   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
2929   SmallVector<SDValue, 8> MemOpChains;
2930   SDValue StackPtr;
2931
2932   // Walk the register/memloc assignments, inserting copies/loads.  In the case
2933   // of tail call optimization arguments are handle later.
2934   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
2935   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2936     // Skip inalloca arguments, they have already been written.
2937     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2938     if (Flags.isInAlloca())
2939       continue;
2940
2941     CCValAssign &VA = ArgLocs[i];
2942     EVT RegVT = VA.getLocVT();
2943     SDValue Arg = OutVals[i];
2944     bool isByVal = Flags.isByVal();
2945
2946     // Promote the value if needed.
2947     switch (VA.getLocInfo()) {
2948     default: llvm_unreachable("Unknown loc info!");
2949     case CCValAssign::Full: break;
2950     case CCValAssign::SExt:
2951       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2952       break;
2953     case CCValAssign::ZExt:
2954       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, RegVT, Arg);
2955       break;
2956     case CCValAssign::AExt:
2957       if (Arg.getValueType().isVector() &&
2958           Arg.getValueType().getScalarType() == MVT::i1)
2959         Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, RegVT, Arg);
2960       else if (RegVT.is128BitVector()) {
2961         // Special case: passing MMX values in XMM registers.
2962         Arg = DAG.getBitcast(MVT::i64, Arg);
2963         Arg = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64, Arg);
2964         Arg = getMOVL(DAG, dl, MVT::v2i64, DAG.getUNDEF(MVT::v2i64), Arg);
2965       } else
2966         Arg = DAG.getNode(ISD::ANY_EXTEND, dl, RegVT, Arg);
2967       break;
2968     case CCValAssign::BCvt:
2969       Arg = DAG.getBitcast(RegVT, Arg);
2970       break;
2971     case CCValAssign::Indirect: {
2972       // Store the argument.
2973       SDValue SpillSlot = DAG.CreateStackTemporary(VA.getValVT());
2974       int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
2975       Chain = DAG.getStore(Chain, dl, Arg, SpillSlot,
2976                            MachinePointerInfo::getFixedStack(FI),
2977                            false, false, 0);
2978       Arg = SpillSlot;
2979       break;
2980     }
2981     }
2982
2983     if (VA.isRegLoc()) {
2984       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2985       if (isVarArg && IsWin64) {
2986         // Win64 ABI requires argument XMM reg to be copied to the corresponding
2987         // shadow reg if callee is a varargs function.
2988         unsigned ShadowReg = 0;
2989         switch (VA.getLocReg()) {
2990         case X86::XMM0: ShadowReg = X86::RCX; break;
2991         case X86::XMM1: ShadowReg = X86::RDX; break;
2992         case X86::XMM2: ShadowReg = X86::R8; break;
2993         case X86::XMM3: ShadowReg = X86::R9; break;
2994         }
2995         if (ShadowReg)
2996           RegsToPass.push_back(std::make_pair(ShadowReg, Arg));
2997       }
2998     } else if (!IsSibcall && (!isTailCall || isByVal)) {
2999       assert(VA.isMemLoc());
3000       if (!StackPtr.getNode())
3001         StackPtr = DAG.getCopyFromReg(Chain, dl, RegInfo->getStackRegister(),
3002                                       getPointerTy());
3003       MemOpChains.push_back(LowerMemOpCallTo(Chain, StackPtr, Arg,
3004                                              dl, DAG, VA, Flags));
3005     }
3006   }
3007
3008   if (!MemOpChains.empty())
3009     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains);
3010
3011   if (Subtarget->isPICStyleGOT()) {
3012     // ELF / PIC requires GOT in the EBX register before function calls via PLT
3013     // GOT pointer.
3014     if (!isTailCall) {
3015       RegsToPass.push_back(std::make_pair(unsigned(X86::EBX),
3016                DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), getPointerTy())));
3017     } else {
3018       // If we are tail calling and generating PIC/GOT style code load the
3019       // address of the callee into ECX. The value in ecx is used as target of
3020       // the tail jump. This is done to circumvent the ebx/callee-saved problem
3021       // for tail calls on PIC/GOT architectures. Normally we would just put the
3022       // address of GOT into ebx and then call target@PLT. But for tail calls
3023       // ebx would be restored (since ebx is callee saved) before jumping to the
3024       // target@PLT.
3025
3026       // Note: The actual moving to ECX is done further down.
3027       GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee);
3028       if (G && !G->getGlobal()->hasLocalLinkage() &&
3029           G->getGlobal()->hasDefaultVisibility())
3030         Callee = LowerGlobalAddress(Callee, DAG);
3031       else if (isa<ExternalSymbolSDNode>(Callee))
3032         Callee = LowerExternalSymbol(Callee, DAG);
3033     }
3034   }
3035
3036   if (Is64Bit && isVarArg && !IsWin64 && !IsMustTail) {
3037     // From AMD64 ABI document:
3038     // For calls that may call functions that use varargs or stdargs
3039     // (prototype-less calls or calls to functions containing ellipsis (...) in
3040     // the declaration) %al is used as hidden argument to specify the number
3041     // of SSE registers used. The contents of %al do not need to match exactly
3042     // the number of registers, but must be an ubound on the number of SSE
3043     // registers used and is in the range 0 - 8 inclusive.
3044
3045     // Count the number of XMM registers allocated.
3046     static const MCPhysReg XMMArgRegs[] = {
3047       X86::XMM0, X86::XMM1, X86::XMM2, X86::XMM3,
3048       X86::XMM4, X86::XMM5, X86::XMM6, X86::XMM7
3049     };
3050     unsigned NumXMMRegs = CCInfo.getFirstUnallocated(XMMArgRegs);
3051     assert((Subtarget->hasSSE1() || !NumXMMRegs)
3052            && "SSE registers cannot be used when SSE is disabled");
3053
3054     RegsToPass.push_back(std::make_pair(unsigned(X86::AL),
3055                                         DAG.getConstant(NumXMMRegs, dl,
3056                                                         MVT::i8)));
3057   }
3058
3059   if (isVarArg && IsMustTail) {
3060     const auto &Forwards = X86Info->getForwardedMustTailRegParms();
3061     for (const auto &F : Forwards) {
3062       SDValue Val = DAG.getCopyFromReg(Chain, dl, F.VReg, F.VT);
3063       RegsToPass.push_back(std::make_pair(unsigned(F.PReg), Val));
3064     }
3065   }
3066
3067   // For tail calls lower the arguments to the 'real' stack slots.  Sibcalls
3068   // don't need this because the eligibility check rejects calls that require
3069   // shuffling arguments passed in memory.
3070   if (!IsSibcall && isTailCall) {
3071     // Force all the incoming stack arguments to be loaded from the stack
3072     // before any new outgoing arguments are stored to the stack, because the
3073     // outgoing stack slots may alias the incoming argument stack slots, and
3074     // the alias isn't otherwise explicit. This is slightly more conservative
3075     // than necessary, because it means that each store effectively depends
3076     // on every argument instead of just those arguments it would clobber.
3077     SDValue ArgChain = DAG.getStackArgumentTokenFactor(Chain);
3078
3079     SmallVector<SDValue, 8> MemOpChains2;
3080     SDValue FIN;
3081     int FI = 0;
3082     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3083       CCValAssign &VA = ArgLocs[i];
3084       if (VA.isRegLoc())
3085         continue;
3086       assert(VA.isMemLoc());
3087       SDValue Arg = OutVals[i];
3088       ISD::ArgFlagsTy Flags = Outs[i].Flags;
3089       // Skip inalloca arguments.  They don't require any work.
3090       if (Flags.isInAlloca())
3091         continue;
3092       // Create frame index.
3093       int32_t Offset = VA.getLocMemOffset()+FPDiff;
3094       uint32_t OpSize = (VA.getLocVT().getSizeInBits()+7)/8;
3095       FI = MF.getFrameInfo()->CreateFixedObject(OpSize, Offset, true);
3096       FIN = DAG.getFrameIndex(FI, getPointerTy());
3097
3098       if (Flags.isByVal()) {
3099         // Copy relative to framepointer.
3100         SDValue Source = DAG.getIntPtrConstant(VA.getLocMemOffset(), dl);
3101         if (!StackPtr.getNode())
3102           StackPtr = DAG.getCopyFromReg(Chain, dl,
3103                                         RegInfo->getStackRegister(),
3104                                         getPointerTy());
3105         Source = DAG.getNode(ISD::ADD, dl, getPointerTy(), StackPtr, Source);
3106
3107         MemOpChains2.push_back(CreateCopyOfByValArgument(Source, FIN,
3108                                                          ArgChain,
3109                                                          Flags, DAG, dl));
3110       } else {
3111         // Store relative to framepointer.
3112         MemOpChains2.push_back(
3113           DAG.getStore(ArgChain, dl, Arg, FIN,
3114                        MachinePointerInfo::getFixedStack(FI),
3115                        false, false, 0));
3116       }
3117     }
3118
3119     if (!MemOpChains2.empty())
3120       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, MemOpChains2);
3121
3122     // Store the return address to the appropriate stack slot.
3123     Chain = EmitTailCallStoreRetAddr(DAG, MF, Chain, RetAddrFrIdx,
3124                                      getPointerTy(), RegInfo->getSlotSize(),
3125                                      FPDiff, dl);
3126   }
3127
3128   // Build a sequence of copy-to-reg nodes chained together with token chain
3129   // and flag operands which copy the outgoing args into registers.
3130   SDValue InFlag;
3131   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3132     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3133                              RegsToPass[i].second, InFlag);
3134     InFlag = Chain.getValue(1);
3135   }
3136
3137   if (DAG.getTarget().getCodeModel() == CodeModel::Large) {
3138     assert(Is64Bit && "Large code model is only legal in 64-bit mode.");
3139     // In the 64-bit large code model, we have to make all calls
3140     // through a register, since the call instruction's 32-bit
3141     // pc-relative offset may not be large enough to hold the whole
3142     // address.
3143   } else if (Callee->getOpcode() == ISD::GlobalAddress) {
3144     // If the callee is a GlobalAddress node (quite common, every direct call
3145     // is) turn it into a TargetGlobalAddress node so that legalize doesn't hack
3146     // it.
3147     GlobalAddressSDNode* G = cast<GlobalAddressSDNode>(Callee);
3148
3149     // We should use extra load for direct calls to dllimported functions in
3150     // non-JIT mode.
3151     const GlobalValue *GV = G->getGlobal();
3152     if (!GV->hasDLLImportStorageClass()) {
3153       unsigned char OpFlags = 0;
3154       bool ExtraLoad = false;
3155       unsigned WrapperKind = ISD::DELETED_NODE;
3156
3157       // On ELF targets, in both X86-64 and X86-32 mode, direct calls to
3158       // external symbols most go through the PLT in PIC mode.  If the symbol
3159       // has hidden or protected visibility, or if it is static or local, then
3160       // we don't need to use the PLT - we can directly call it.
3161       if (Subtarget->isTargetELF() &&
3162           DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
3163           GV->hasDefaultVisibility() && !GV->hasLocalLinkage()) {
3164         OpFlags = X86II::MO_PLT;
3165       } else if (Subtarget->isPICStyleStubAny() &&
3166                  !GV->isStrongDefinitionForLinker() &&
3167                  (!Subtarget->getTargetTriple().isMacOSX() ||
3168                   Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3169         // PC-relative references to external symbols should go through $stub,
3170         // unless we're building with the leopard linker or later, which
3171         // automatically synthesizes these stubs.
3172         OpFlags = X86II::MO_DARWIN_STUB;
3173       } else if (Subtarget->isPICStyleRIPRel() && isa<Function>(GV) &&
3174                  cast<Function>(GV)->hasFnAttribute(Attribute::NonLazyBind)) {
3175         // If the function is marked as non-lazy, generate an indirect call
3176         // which loads from the GOT directly. This avoids runtime overhead
3177         // at the cost of eager binding (and one extra byte of encoding).
3178         OpFlags = X86II::MO_GOTPCREL;
3179         WrapperKind = X86ISD::WrapperRIP;
3180         ExtraLoad = true;
3181       }
3182
3183       Callee = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(),
3184                                           G->getOffset(), OpFlags);
3185
3186       // Add a wrapper if needed.
3187       if (WrapperKind != ISD::DELETED_NODE)
3188         Callee = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Callee);
3189       // Add extra indirection if needed.
3190       if (ExtraLoad)
3191         Callee = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Callee,
3192                              MachinePointerInfo::getGOT(),
3193                              false, false, false, 0);
3194     }
3195   } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3196     unsigned char OpFlags = 0;
3197
3198     // On ELF targets, in either X86-64 or X86-32 mode, direct calls to
3199     // external symbols should go through the PLT.
3200     if (Subtarget->isTargetELF() &&
3201         DAG.getTarget().getRelocationModel() == Reloc::PIC_) {
3202       OpFlags = X86II::MO_PLT;
3203     } else if (Subtarget->isPICStyleStubAny() &&
3204                (!Subtarget->getTargetTriple().isMacOSX() ||
3205                 Subtarget->getTargetTriple().isMacOSXVersionLT(10, 5))) {
3206       // PC-relative references to external symbols should go through $stub,
3207       // unless we're building with the leopard linker or later, which
3208       // automatically synthesizes these stubs.
3209       OpFlags = X86II::MO_DARWIN_STUB;
3210     }
3211
3212     Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3213                                          OpFlags);
3214   } else if (Subtarget->isTarget64BitILP32() &&
3215              Callee->getValueType(0) == MVT::i32) {
3216     // Zero-extend the 32-bit Callee address into a 64-bit according to x32 ABI
3217     Callee = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, Callee);
3218   }
3219
3220   // Returns a chain & a flag for retval copy to use.
3221   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3222   SmallVector<SDValue, 8> Ops;
3223
3224   if (!IsSibcall && isTailCall) {
3225     Chain = DAG.getCALLSEQ_END(Chain,
3226                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3227                                DAG.getIntPtrConstant(0, dl, true), InFlag, dl);
3228     InFlag = Chain.getValue(1);
3229   }
3230
3231   Ops.push_back(Chain);
3232   Ops.push_back(Callee);
3233
3234   if (isTailCall)
3235     Ops.push_back(DAG.getConstant(FPDiff, dl, MVT::i32));
3236
3237   // Add argument registers to the end of the list so that they are known live
3238   // into the call.
3239   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3240     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3241                                   RegsToPass[i].second.getValueType()));
3242
3243   // Add a register mask operand representing the call-preserved registers.
3244   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
3245   const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
3246   assert(Mask && "Missing call preserved mask for calling convention");
3247   Ops.push_back(DAG.getRegisterMask(Mask));
3248
3249   if (InFlag.getNode())
3250     Ops.push_back(InFlag);
3251
3252   if (isTailCall) {
3253     // We used to do:
3254     //// If this is the first return lowered for this function, add the regs
3255     //// to the liveout set for the function.
3256     // This isn't right, although it's probably harmless on x86; liveouts
3257     // should be computed from returns not tail calls.  Consider a void
3258     // function making a tail call to a function returning int.
3259     MF.getFrameInfo()->setHasTailCall();
3260     return DAG.getNode(X86ISD::TC_RETURN, dl, NodeTys, Ops);
3261   }
3262
3263   Chain = DAG.getNode(X86ISD::CALL, dl, NodeTys, Ops);
3264   InFlag = Chain.getValue(1);
3265
3266   // Create the CALLSEQ_END node.
3267   unsigned NumBytesForCalleeToPop;
3268   if (X86::isCalleePop(CallConv, Is64Bit, isVarArg,
3269                        DAG.getTarget().Options.GuaranteedTailCallOpt))
3270     NumBytesForCalleeToPop = NumBytes;    // Callee pops everything
3271   else if (!Is64Bit && !IsTailCallConvention(CallConv) &&
3272            !Subtarget->getTargetTriple().isOSMSVCRT() &&
3273            SR == StackStructReturn)
3274     // If this is a call to a struct-return function, the callee
3275     // pops the hidden struct pointer, so we have to push it back.
3276     // This is common for Darwin/X86, Linux & Mingw32 targets.
3277     // For MSVC Win32 targets, the caller pops the hidden struct pointer.
3278     NumBytesForCalleeToPop = 4;
3279   else
3280     NumBytesForCalleeToPop = 0;  // Callee pops nothing.
3281
3282   // Returns a flag for retval copy to use.
3283   if (!IsSibcall) {
3284     Chain = DAG.getCALLSEQ_END(Chain,
3285                                DAG.getIntPtrConstant(NumBytesToPop, dl, true),
3286                                DAG.getIntPtrConstant(NumBytesForCalleeToPop, dl,
3287                                                      true),
3288                                InFlag, dl);
3289     InFlag = Chain.getValue(1);
3290   }
3291
3292   // Handle result values, copying them out of physregs into vregs that we
3293   // return.
3294   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3295                          Ins, dl, DAG, InVals);
3296 }
3297
3298 //===----------------------------------------------------------------------===//
3299 //                Fast Calling Convention (tail call) implementation
3300 //===----------------------------------------------------------------------===//
3301
3302 //  Like std call, callee cleans arguments, convention except that ECX is
3303 //  reserved for storing the tail called function address. Only 2 registers are
3304 //  free for argument passing (inreg). Tail call optimization is performed
3305 //  provided:
3306 //                * tailcallopt is enabled
3307 //                * caller/callee are fastcc
3308 //  On X86_64 architecture with GOT-style position independent code only local
3309 //  (within module) calls are supported at the moment.
3310 //  To keep the stack aligned according to platform abi the function
3311 //  GetAlignedArgumentStackSize ensures that argument delta is always multiples
3312 //  of stack alignment. (Dynamic linkers need this - darwin's dyld for example)
3313 //  If a tail called function callee has more arguments than the caller the
3314 //  caller needs to make sure that there is room to move the RETADDR to. This is
3315 //  achieved by reserving an area the size of the argument delta right after the
3316 //  original RETADDR, but before the saved framepointer or the spilled registers
3317 //  e.g. caller(arg1, arg2) calls callee(arg1, arg2,arg3,arg4)
3318 //  stack layout:
3319 //    arg1
3320 //    arg2
3321 //    RETADDR
3322 //    [ new RETADDR
3323 //      move area ]
3324 //    (possible EBP)
3325 //    ESI
3326 //    EDI
3327 //    local1 ..
3328
3329 /// GetAlignedArgumentStackSize - Make the stack size align e.g 16n + 12 aligned
3330 /// for a 16 byte align requirement.
3331 unsigned
3332 X86TargetLowering::GetAlignedArgumentStackSize(unsigned StackSize,
3333                                                SelectionDAG& DAG) const {
3334   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3335   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
3336   unsigned StackAlignment = TFI.getStackAlignment();
3337   uint64_t AlignMask = StackAlignment - 1;
3338   int64_t Offset = StackSize;
3339   unsigned SlotSize = RegInfo->getSlotSize();
3340   if ( (Offset & AlignMask) <= (StackAlignment - SlotSize) ) {
3341     // Number smaller than 12 so just add the difference.
3342     Offset += ((StackAlignment - SlotSize) - (Offset & AlignMask));
3343   } else {
3344     // Mask out lower bits, add stackalignment once plus the 12 bytes.
3345     Offset = ((~AlignMask) & Offset) + StackAlignment +
3346       (StackAlignment-SlotSize);
3347   }
3348   return Offset;
3349 }
3350
3351 /// MatchingStackOffset - Return true if the given stack call argument is
3352 /// already available in the same position (relatively) of the caller's
3353 /// incoming argument stack.
3354 static
3355 bool MatchingStackOffset(SDValue Arg, unsigned Offset, ISD::ArgFlagsTy Flags,
3356                          MachineFrameInfo *MFI, const MachineRegisterInfo *MRI,
3357                          const X86InstrInfo *TII) {
3358   unsigned Bytes = Arg.getValueType().getSizeInBits() / 8;
3359   int FI = INT_MAX;
3360   if (Arg.getOpcode() == ISD::CopyFromReg) {
3361     unsigned VR = cast<RegisterSDNode>(Arg.getOperand(1))->getReg();
3362     if (!TargetRegisterInfo::isVirtualRegister(VR))
3363       return false;
3364     MachineInstr *Def = MRI->getVRegDef(VR);
3365     if (!Def)
3366       return false;
3367     if (!Flags.isByVal()) {
3368       if (!TII->isLoadFromStackSlot(Def, FI))
3369         return false;
3370     } else {
3371       unsigned Opcode = Def->getOpcode();
3372       if ((Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
3373            Opcode == X86::LEA64_32r) &&
3374           Def->getOperand(1).isFI()) {
3375         FI = Def->getOperand(1).getIndex();
3376         Bytes = Flags.getByValSize();
3377       } else
3378         return false;
3379     }
3380   } else if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Arg)) {
3381     if (Flags.isByVal())
3382       // ByVal argument is passed in as a pointer but it's now being
3383       // dereferenced. e.g.
3384       // define @foo(%struct.X* %A) {
3385       //   tail call @bar(%struct.X* byval %A)
3386       // }
3387       return false;
3388     SDValue Ptr = Ld->getBasePtr();
3389     FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr);
3390     if (!FINode)
3391       return false;
3392     FI = FINode->getIndex();
3393   } else if (Arg.getOpcode() == ISD::FrameIndex && Flags.isByVal()) {
3394     FrameIndexSDNode *FINode = cast<FrameIndexSDNode>(Arg);
3395     FI = FINode->getIndex();
3396     Bytes = Flags.getByValSize();
3397   } else
3398     return false;
3399
3400   assert(FI != INT_MAX);
3401   if (!MFI->isFixedObjectIndex(FI))
3402     return false;
3403   return Offset == MFI->getObjectOffset(FI) && Bytes == MFI->getObjectSize(FI);
3404 }
3405
3406 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
3407 /// for tail call optimization. Targets which want to do tail call
3408 /// optimization should implement this function.
3409 bool
3410 X86TargetLowering::IsEligibleForTailCallOptimization(SDValue Callee,
3411                                                      CallingConv::ID CalleeCC,
3412                                                      bool isVarArg,
3413                                                      bool isCalleeStructRet,
3414                                                      bool isCallerStructRet,
3415                                                      Type *RetTy,
3416                                     const SmallVectorImpl<ISD::OutputArg> &Outs,
3417                                     const SmallVectorImpl<SDValue> &OutVals,
3418                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3419                                                      SelectionDAG &DAG) const {
3420   if (!IsTailCallConvention(CalleeCC) && !IsCCallConvention(CalleeCC))
3421     return false;
3422
3423   // If -tailcallopt is specified, make fastcc functions tail-callable.
3424   const MachineFunction &MF = DAG.getMachineFunction();
3425   const Function *CallerF = MF.getFunction();
3426
3427   // If the function return type is x86_fp80 and the callee return type is not,
3428   // then the FP_EXTEND of the call result is not a nop. It's not safe to
3429   // perform a tailcall optimization here.
3430   if (CallerF->getReturnType()->isX86_FP80Ty() && !RetTy->isX86_FP80Ty())
3431     return false;
3432
3433   CallingConv::ID CallerCC = CallerF->getCallingConv();
3434   bool CCMatch = CallerCC == CalleeCC;
3435   bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
3436   bool IsCallerWin64 = Subtarget->isCallingConvWin64(CallerCC);
3437
3438   // Win64 functions have extra shadow space for argument homing. Don't do the
3439   // sibcall if the caller and callee have mismatched expectations for this
3440   // space.
3441   if (IsCalleeWin64 != IsCallerWin64)
3442     return false;
3443
3444   if (DAG.getTarget().Options.GuaranteedTailCallOpt) {
3445     if (IsTailCallConvention(CalleeCC) && CCMatch)
3446       return true;
3447     return false;
3448   }
3449
3450   // Look for obvious safe cases to perform tail call optimization that do not
3451   // require ABI changes. This is what gcc calls sibcall.
3452
3453   // Can't do sibcall if stack needs to be dynamically re-aligned. PEI needs to
3454   // emit a special epilogue.
3455   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3456   if (RegInfo->needsStackRealignment(MF))
3457     return false;
3458
3459   // Also avoid sibcall optimization if either caller or callee uses struct
3460   // return semantics.
3461   if (isCalleeStructRet || isCallerStructRet)
3462     return false;
3463
3464   // An stdcall/thiscall caller is expected to clean up its arguments; the
3465   // callee isn't going to do that.
3466   // FIXME: this is more restrictive than needed. We could produce a tailcall
3467   // when the stack adjustment matches. For example, with a thiscall that takes
3468   // only one argument.
3469   if (!CCMatch && (CallerCC == CallingConv::X86_StdCall ||
3470                    CallerCC == CallingConv::X86_ThisCall))
3471     return false;
3472
3473   // Do not sibcall optimize vararg calls unless all arguments are passed via
3474   // registers.
3475   if (isVarArg && !Outs.empty()) {
3476
3477     // Optimizing for varargs on Win64 is unlikely to be safe without
3478     // additional testing.
3479     if (IsCalleeWin64 || IsCallerWin64)
3480       return false;
3481
3482     SmallVector<CCValAssign, 16> ArgLocs;
3483     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3484                    *DAG.getContext());
3485
3486     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3487     for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i)
3488       if (!ArgLocs[i].isRegLoc())
3489         return false;
3490   }
3491
3492   // If the call result is in ST0 / ST1, it needs to be popped off the x87
3493   // stack.  Therefore, if it's not used by the call it is not safe to optimize
3494   // this into a sibcall.
3495   bool Unused = false;
3496   for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
3497     if (!Ins[i].Used) {
3498       Unused = true;
3499       break;
3500     }
3501   }
3502   if (Unused) {
3503     SmallVector<CCValAssign, 16> RVLocs;
3504     CCState CCInfo(CalleeCC, false, DAG.getMachineFunction(), RVLocs,
3505                    *DAG.getContext());
3506     CCInfo.AnalyzeCallResult(Ins, RetCC_X86);
3507     for (unsigned i = 0, e = RVLocs.size(); i != e; ++i) {
3508       CCValAssign &VA = RVLocs[i];
3509       if (VA.getLocReg() == X86::FP0 || VA.getLocReg() == X86::FP1)
3510         return false;
3511     }
3512   }
3513
3514   // If the calling conventions do not match, then we'd better make sure the
3515   // results are returned in the same way as what the caller expects.
3516   if (!CCMatch) {
3517     SmallVector<CCValAssign, 16> RVLocs1;
3518     CCState CCInfo1(CalleeCC, false, DAG.getMachineFunction(), RVLocs1,
3519                     *DAG.getContext());
3520     CCInfo1.AnalyzeCallResult(Ins, RetCC_X86);
3521
3522     SmallVector<CCValAssign, 16> RVLocs2;
3523     CCState CCInfo2(CallerCC, false, DAG.getMachineFunction(), RVLocs2,
3524                     *DAG.getContext());
3525     CCInfo2.AnalyzeCallResult(Ins, RetCC_X86);
3526
3527     if (RVLocs1.size() != RVLocs2.size())
3528       return false;
3529     for (unsigned i = 0, e = RVLocs1.size(); i != e; ++i) {
3530       if (RVLocs1[i].isRegLoc() != RVLocs2[i].isRegLoc())
3531         return false;
3532       if (RVLocs1[i].getLocInfo() != RVLocs2[i].getLocInfo())
3533         return false;
3534       if (RVLocs1[i].isRegLoc()) {
3535         if (RVLocs1[i].getLocReg() != RVLocs2[i].getLocReg())
3536           return false;
3537       } else {
3538         if (RVLocs1[i].getLocMemOffset() != RVLocs2[i].getLocMemOffset())
3539           return false;
3540       }
3541     }
3542   }
3543
3544   // If the callee takes no arguments then go on to check the results of the
3545   // call.
3546   if (!Outs.empty()) {
3547     // Check if stack adjustment is needed. For now, do not do this if any
3548     // argument is passed on the stack.
3549     SmallVector<CCValAssign, 16> ArgLocs;
3550     CCState CCInfo(CalleeCC, isVarArg, DAG.getMachineFunction(), ArgLocs,
3551                    *DAG.getContext());
3552
3553     // Allocate shadow area for Win64
3554     if (IsCalleeWin64)
3555       CCInfo.AllocateStack(32, 8);
3556
3557     CCInfo.AnalyzeCallOperands(Outs, CC_X86);
3558     if (CCInfo.getNextStackOffset()) {
3559       MachineFunction &MF = DAG.getMachineFunction();
3560       if (MF.getInfo<X86MachineFunctionInfo>()->getBytesToPopOnReturn())
3561         return false;
3562
3563       // Check if the arguments are already laid out in the right way as
3564       // the caller's fixed stack objects.
3565       MachineFrameInfo *MFI = MF.getFrameInfo();
3566       const MachineRegisterInfo *MRI = &MF.getRegInfo();
3567       const X86InstrInfo *TII = Subtarget->getInstrInfo();
3568       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3569         CCValAssign &VA = ArgLocs[i];
3570         SDValue Arg = OutVals[i];
3571         ISD::ArgFlagsTy Flags = Outs[i].Flags;
3572         if (VA.getLocInfo() == CCValAssign::Indirect)
3573           return false;
3574         if (!VA.isRegLoc()) {
3575           if (!MatchingStackOffset(Arg, VA.getLocMemOffset(), Flags,
3576                                    MFI, MRI, TII))
3577             return false;
3578         }
3579       }
3580     }
3581
3582     // If the tailcall address may be in a register, then make sure it's
3583     // possible to register allocate for it. In 32-bit, the call address can
3584     // only target EAX, EDX, or ECX since the tail call must be scheduled after
3585     // callee-saved registers are restored. These happen to be the same
3586     // registers used to pass 'inreg' arguments so watch out for those.
3587     if (!Subtarget->is64Bit() &&
3588         ((!isa<GlobalAddressSDNode>(Callee) &&
3589           !isa<ExternalSymbolSDNode>(Callee)) ||
3590          DAG.getTarget().getRelocationModel() == Reloc::PIC_)) {
3591       unsigned NumInRegs = 0;
3592       // In PIC we need an extra register to formulate the address computation
3593       // for the callee.
3594       unsigned MaxInRegs =
3595         (DAG.getTarget().getRelocationModel() == Reloc::PIC_) ? 2 : 3;
3596
3597       for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3598         CCValAssign &VA = ArgLocs[i];
3599         if (!VA.isRegLoc())
3600           continue;
3601         unsigned Reg = VA.getLocReg();
3602         switch (Reg) {
3603         default: break;
3604         case X86::EAX: case X86::EDX: case X86::ECX:
3605           if (++NumInRegs == MaxInRegs)
3606             return false;
3607           break;
3608         }
3609       }
3610     }
3611   }
3612
3613   return true;
3614 }
3615
3616 FastISel *
3617 X86TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
3618                                   const TargetLibraryInfo *libInfo) const {
3619   return X86::createFastISel(funcInfo, libInfo);
3620 }
3621
3622 //===----------------------------------------------------------------------===//
3623 //                           Other Lowering Hooks
3624 //===----------------------------------------------------------------------===//
3625
3626 static bool MayFoldLoad(SDValue Op) {
3627   return Op.hasOneUse() && ISD::isNormalLoad(Op.getNode());
3628 }
3629
3630 static bool MayFoldIntoStore(SDValue Op) {
3631   return Op.hasOneUse() && ISD::isNormalStore(*Op.getNode()->use_begin());
3632 }
3633
3634 static bool isTargetShuffle(unsigned Opcode) {
3635   switch(Opcode) {
3636   default: return false;
3637   case X86ISD::BLENDI:
3638   case X86ISD::PSHUFB:
3639   case X86ISD::PSHUFD:
3640   case X86ISD::PSHUFHW:
3641   case X86ISD::PSHUFLW:
3642   case X86ISD::SHUFP:
3643   case X86ISD::PALIGNR:
3644   case X86ISD::MOVLHPS:
3645   case X86ISD::MOVLHPD:
3646   case X86ISD::MOVHLPS:
3647   case X86ISD::MOVLPS:
3648   case X86ISD::MOVLPD:
3649   case X86ISD::MOVSHDUP:
3650   case X86ISD::MOVSLDUP:
3651   case X86ISD::MOVDDUP:
3652   case X86ISD::MOVSS:
3653   case X86ISD::MOVSD:
3654   case X86ISD::UNPCKL:
3655   case X86ISD::UNPCKH:
3656   case X86ISD::VPERMILPI:
3657   case X86ISD::VPERM2X128:
3658   case X86ISD::VPERMI:
3659     return true;
3660   }
3661 }
3662
3663 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3664                                     SDValue V1, unsigned TargetMask,
3665                                     SelectionDAG &DAG) {
3666   switch(Opc) {
3667   default: llvm_unreachable("Unknown x86 shuffle node");
3668   case X86ISD::PSHUFD:
3669   case X86ISD::PSHUFHW:
3670   case X86ISD::PSHUFLW:
3671   case X86ISD::VPERMILPI:
3672   case X86ISD::VPERMI:
3673     return DAG.getNode(Opc, dl, VT, V1,
3674                        DAG.getConstant(TargetMask, dl, MVT::i8));
3675   }
3676 }
3677
3678 static SDValue getTargetShuffleNode(unsigned Opc, SDLoc dl, EVT VT,
3679                                     SDValue V1, SDValue V2, SelectionDAG &DAG) {
3680   switch(Opc) {
3681   default: llvm_unreachable("Unknown x86 shuffle node");
3682   case X86ISD::MOVLHPS:
3683   case X86ISD::MOVLHPD:
3684   case X86ISD::MOVHLPS:
3685   case X86ISD::MOVLPS:
3686   case X86ISD::MOVLPD:
3687   case X86ISD::MOVSS:
3688   case X86ISD::MOVSD:
3689   case X86ISD::UNPCKL:
3690   case X86ISD::UNPCKH:
3691     return DAG.getNode(Opc, dl, VT, V1, V2);
3692   }
3693 }
3694
3695 SDValue X86TargetLowering::getReturnAddressFrameIndex(SelectionDAG &DAG) const {
3696   MachineFunction &MF = DAG.getMachineFunction();
3697   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
3698   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
3699   int ReturnAddrIndex = FuncInfo->getRAIndex();
3700
3701   if (ReturnAddrIndex == 0) {
3702     // Set up a frame object for the return address.
3703     unsigned SlotSize = RegInfo->getSlotSize();
3704     ReturnAddrIndex = MF.getFrameInfo()->CreateFixedObject(SlotSize,
3705                                                            -(int64_t)SlotSize,
3706                                                            false);
3707     FuncInfo->setRAIndex(ReturnAddrIndex);
3708   }
3709
3710   return DAG.getFrameIndex(ReturnAddrIndex, getPointerTy());
3711 }
3712
3713 bool X86::isOffsetSuitableForCodeModel(int64_t Offset, CodeModel::Model M,
3714                                        bool hasSymbolicDisplacement) {
3715   // Offset should fit into 32 bit immediate field.
3716   if (!isInt<32>(Offset))
3717     return false;
3718
3719   // If we don't have a symbolic displacement - we don't have any extra
3720   // restrictions.
3721   if (!hasSymbolicDisplacement)
3722     return true;
3723
3724   // FIXME: Some tweaks might be needed for medium code model.
3725   if (M != CodeModel::Small && M != CodeModel::Kernel)
3726     return false;
3727
3728   // For small code model we assume that latest object is 16MB before end of 31
3729   // bits boundary. We may also accept pretty large negative constants knowing
3730   // that all objects are in the positive half of address space.
3731   if (M == CodeModel::Small && Offset < 16*1024*1024)
3732     return true;
3733
3734   // For kernel code model we know that all object resist in the negative half
3735   // of 32bits address space. We may not accept negative offsets, since they may
3736   // be just off and we may accept pretty large positive ones.
3737   if (M == CodeModel::Kernel && Offset >= 0)
3738     return true;
3739
3740   return false;
3741 }
3742
3743 /// isCalleePop - Determines whether the callee is required to pop its
3744 /// own arguments. Callee pop is necessary to support tail calls.
3745 bool X86::isCalleePop(CallingConv::ID CallingConv,
3746                       bool is64Bit, bool IsVarArg, bool TailCallOpt) {
3747   switch (CallingConv) {
3748   default:
3749     return false;
3750   case CallingConv::X86_StdCall:
3751   case CallingConv::X86_FastCall:
3752   case CallingConv::X86_ThisCall:
3753     return !is64Bit;
3754   case CallingConv::Fast:
3755   case CallingConv::GHC:
3756   case CallingConv::HiPE:
3757     if (IsVarArg)
3758       return false;
3759     return TailCallOpt;
3760   }
3761 }
3762
3763 /// \brief Return true if the condition is an unsigned comparison operation.
3764 static bool isX86CCUnsigned(unsigned X86CC) {
3765   switch (X86CC) {
3766   default: llvm_unreachable("Invalid integer condition!");
3767   case X86::COND_E:     return true;
3768   case X86::COND_G:     return false;
3769   case X86::COND_GE:    return false;
3770   case X86::COND_L:     return false;
3771   case X86::COND_LE:    return false;
3772   case X86::COND_NE:    return true;
3773   case X86::COND_B:     return true;
3774   case X86::COND_A:     return true;
3775   case X86::COND_BE:    return true;
3776   case X86::COND_AE:    return true;
3777   }
3778   llvm_unreachable("covered switch fell through?!");
3779 }
3780
3781 /// TranslateX86CC - do a one to one translation of a ISD::CondCode to the X86
3782 /// specific condition code, returning the condition code and the LHS/RHS of the
3783 /// comparison to make.
3784 static unsigned TranslateX86CC(ISD::CondCode SetCCOpcode, SDLoc DL, bool isFP,
3785                                SDValue &LHS, SDValue &RHS, SelectionDAG &DAG) {
3786   if (!isFP) {
3787     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
3788       if (SetCCOpcode == ISD::SETGT && RHSC->isAllOnesValue()) {
3789         // X > -1   -> X == 0, jump !sign.
3790         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3791         return X86::COND_NS;
3792       }
3793       if (SetCCOpcode == ISD::SETLT && RHSC->isNullValue()) {
3794         // X < 0   -> X == 0, jump on sign.
3795         return X86::COND_S;
3796       }
3797       if (SetCCOpcode == ISD::SETLT && RHSC->getZExtValue() == 1) {
3798         // X < 1   -> X <= 0
3799         RHS = DAG.getConstant(0, DL, RHS.getValueType());
3800         return X86::COND_LE;
3801       }
3802     }
3803
3804     switch (SetCCOpcode) {
3805     default: llvm_unreachable("Invalid integer condition!");
3806     case ISD::SETEQ:  return X86::COND_E;
3807     case ISD::SETGT:  return X86::COND_G;
3808     case ISD::SETGE:  return X86::COND_GE;
3809     case ISD::SETLT:  return X86::COND_L;
3810     case ISD::SETLE:  return X86::COND_LE;
3811     case ISD::SETNE:  return X86::COND_NE;
3812     case ISD::SETULT: return X86::COND_B;
3813     case ISD::SETUGT: return X86::COND_A;
3814     case ISD::SETULE: return X86::COND_BE;
3815     case ISD::SETUGE: return X86::COND_AE;
3816     }
3817   }
3818
3819   // First determine if it is required or is profitable to flip the operands.
3820
3821   // If LHS is a foldable load, but RHS is not, flip the condition.
3822   if (ISD::isNON_EXTLoad(LHS.getNode()) &&
3823       !ISD::isNON_EXTLoad(RHS.getNode())) {
3824     SetCCOpcode = getSetCCSwappedOperands(SetCCOpcode);
3825     std::swap(LHS, RHS);
3826   }
3827
3828   switch (SetCCOpcode) {
3829   default: break;
3830   case ISD::SETOLT:
3831   case ISD::SETOLE:
3832   case ISD::SETUGT:
3833   case ISD::SETUGE:
3834     std::swap(LHS, RHS);
3835     break;
3836   }
3837
3838   // On a floating point condition, the flags are set as follows:
3839   // ZF  PF  CF   op
3840   //  0 | 0 | 0 | X > Y
3841   //  0 | 0 | 1 | X < Y
3842   //  1 | 0 | 0 | X == Y
3843   //  1 | 1 | 1 | unordered
3844   switch (SetCCOpcode) {
3845   default: llvm_unreachable("Condcode should be pre-legalized away");
3846   case ISD::SETUEQ:
3847   case ISD::SETEQ:   return X86::COND_E;
3848   case ISD::SETOLT:              // flipped
3849   case ISD::SETOGT:
3850   case ISD::SETGT:   return X86::COND_A;
3851   case ISD::SETOLE:              // flipped
3852   case ISD::SETOGE:
3853   case ISD::SETGE:   return X86::COND_AE;
3854   case ISD::SETUGT:              // flipped
3855   case ISD::SETULT:
3856   case ISD::SETLT:   return X86::COND_B;
3857   case ISD::SETUGE:              // flipped
3858   case ISD::SETULE:
3859   case ISD::SETLE:   return X86::COND_BE;
3860   case ISD::SETONE:
3861   case ISD::SETNE:   return X86::COND_NE;
3862   case ISD::SETUO:   return X86::COND_P;
3863   case ISD::SETO:    return X86::COND_NP;
3864   case ISD::SETOEQ:
3865   case ISD::SETUNE:  return X86::COND_INVALID;
3866   }
3867 }
3868
3869 /// hasFPCMov - is there a floating point cmov for the specific X86 condition
3870 /// code. Current x86 isa includes the following FP cmov instructions:
3871 /// fcmovb, fcomvbe, fcomve, fcmovu, fcmovae, fcmova, fcmovne, fcmovnu.
3872 static bool hasFPCMov(unsigned X86CC) {
3873   switch (X86CC) {
3874   default:
3875     return false;
3876   case X86::COND_B:
3877   case X86::COND_BE:
3878   case X86::COND_E:
3879   case X86::COND_P:
3880   case X86::COND_A:
3881   case X86::COND_AE:
3882   case X86::COND_NE:
3883   case X86::COND_NP:
3884     return true;
3885   }
3886 }
3887
3888 /// isFPImmLegal - Returns true if the target can instruction select the
3889 /// specified FP immediate natively. If false, the legalizer will
3890 /// materialize the FP immediate as a load from a constant pool.
3891 bool X86TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3892   for (unsigned i = 0, e = LegalFPImmediates.size(); i != e; ++i) {
3893     if (Imm.bitwiseIsEqual(LegalFPImmediates[i]))
3894       return true;
3895   }
3896   return false;
3897 }
3898
3899 bool X86TargetLowering::shouldReduceLoadWidth(SDNode *Load,
3900                                               ISD::LoadExtType ExtTy,
3901                                               EVT NewVT) const {
3902   // "ELF Handling for Thread-Local Storage" specifies that R_X86_64_GOTTPOFF
3903   // relocation target a movq or addq instruction: don't let the load shrink.
3904   SDValue BasePtr = cast<LoadSDNode>(Load)->getBasePtr();
3905   if (BasePtr.getOpcode() == X86ISD::WrapperRIP)
3906     if (const auto *GA = dyn_cast<GlobalAddressSDNode>(BasePtr.getOperand(0)))
3907       return GA->getTargetFlags() != X86II::MO_GOTTPOFF;
3908   return true;
3909 }
3910
3911 /// \brief Returns true if it is beneficial to convert a load of a constant
3912 /// to just the constant itself.
3913 bool X86TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
3914                                                           Type *Ty) const {
3915   assert(Ty->isIntegerTy());
3916
3917   unsigned BitSize = Ty->getPrimitiveSizeInBits();
3918   if (BitSize == 0 || BitSize > 64)
3919     return false;
3920   return true;
3921 }
3922
3923 bool X86TargetLowering::isExtractSubvectorCheap(EVT ResVT,
3924                                                 unsigned Index) const {
3925   if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
3926     return false;
3927
3928   return (Index == 0 || Index == ResVT.getVectorNumElements());
3929 }
3930
3931 bool X86TargetLowering::isCheapToSpeculateCttz() const {
3932   // Speculate cttz only if we can directly use TZCNT.
3933   return Subtarget->hasBMI();
3934 }
3935
3936 bool X86TargetLowering::isCheapToSpeculateCtlz() const {
3937   // Speculate ctlz only if we can directly use LZCNT.
3938   return Subtarget->hasLZCNT();
3939 }
3940
3941 /// isUndefOrInRange - Return true if Val is undef or if its value falls within
3942 /// the specified range (L, H].
3943 static bool isUndefOrInRange(int Val, int Low, int Hi) {
3944   return (Val < 0) || (Val >= Low && Val < Hi);
3945 }
3946
3947 /// isUndefOrEqual - Val is either less than zero (undef) or equal to the
3948 /// specified value.
3949 static bool isUndefOrEqual(int Val, int CmpVal) {
3950   return (Val < 0 || Val == CmpVal);
3951 }
3952
3953 /// isSequentialOrUndefInRange - Return true if every element in Mask, beginning
3954 /// from position Pos and ending in Pos+Size, falls within the specified
3955 /// sequential range (Low, Low+Size]. or is undef.
3956 static bool isSequentialOrUndefInRange(ArrayRef<int> Mask,
3957                                        unsigned Pos, unsigned Size, int Low) {
3958   for (unsigned i = Pos, e = Pos+Size; i != e; ++i, ++Low)
3959     if (!isUndefOrEqual(Mask[i], Low))
3960       return false;
3961   return true;
3962 }
3963
3964 /// isVEXTRACTIndex - Return true if the specified
3965 /// EXTRACT_SUBVECTOR operand specifies a vector extract that is
3966 /// suitable for instruction that extract 128 or 256 bit vectors
3967 static bool isVEXTRACTIndex(SDNode *N, unsigned vecWidth) {
3968   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3969   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
3970     return false;
3971
3972   // The index should be aligned on a vecWidth-bit boundary.
3973   uint64_t Index =
3974     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
3975
3976   MVT VT = N->getSimpleValueType(0);
3977   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3978   bool Result = (Index * ElSize) % vecWidth == 0;
3979
3980   return Result;
3981 }
3982
3983 /// isVINSERTIndex - Return true if the specified INSERT_SUBVECTOR
3984 /// operand specifies a subvector insert that is suitable for input to
3985 /// insertion of 128 or 256-bit subvectors
3986 static bool isVINSERTIndex(SDNode *N, unsigned vecWidth) {
3987   assert((vecWidth == 128 || vecWidth == 256) && "Unexpected vector width");
3988   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
3989     return false;
3990   // The index should be aligned on a vecWidth-bit boundary.
3991   uint64_t Index =
3992     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
3993
3994   MVT VT = N->getSimpleValueType(0);
3995   unsigned ElSize = VT.getVectorElementType().getSizeInBits();
3996   bool Result = (Index * ElSize) % vecWidth == 0;
3997
3998   return Result;
3999 }
4000
4001 bool X86::isVINSERT128Index(SDNode *N) {
4002   return isVINSERTIndex(N, 128);
4003 }
4004
4005 bool X86::isVINSERT256Index(SDNode *N) {
4006   return isVINSERTIndex(N, 256);
4007 }
4008
4009 bool X86::isVEXTRACT128Index(SDNode *N) {
4010   return isVEXTRACTIndex(N, 128);
4011 }
4012
4013 bool X86::isVEXTRACT256Index(SDNode *N) {
4014   return isVEXTRACTIndex(N, 256);
4015 }
4016
4017 static unsigned getExtractVEXTRACTImmediate(SDNode *N, unsigned vecWidth) {
4018   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4019   if (!isa<ConstantSDNode>(N->getOperand(1).getNode()))
4020     llvm_unreachable("Illegal extract subvector for VEXTRACT");
4021
4022   uint64_t Index =
4023     cast<ConstantSDNode>(N->getOperand(1).getNode())->getZExtValue();
4024
4025   MVT VecVT = N->getOperand(0).getSimpleValueType();
4026   MVT ElVT = VecVT.getVectorElementType();
4027
4028   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4029   return Index / NumElemsPerChunk;
4030 }
4031
4032 static unsigned getInsertVINSERTImmediate(SDNode *N, unsigned vecWidth) {
4033   assert((vecWidth == 128 || vecWidth == 256) && "Unsupported vector width");
4034   if (!isa<ConstantSDNode>(N->getOperand(2).getNode()))
4035     llvm_unreachable("Illegal insert subvector for VINSERT");
4036
4037   uint64_t Index =
4038     cast<ConstantSDNode>(N->getOperand(2).getNode())->getZExtValue();
4039
4040   MVT VecVT = N->getSimpleValueType(0);
4041   MVT ElVT = VecVT.getVectorElementType();
4042
4043   unsigned NumElemsPerChunk = vecWidth / ElVT.getSizeInBits();
4044   return Index / NumElemsPerChunk;
4045 }
4046
4047 /// getExtractVEXTRACT128Immediate - Return the appropriate immediate
4048 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF128
4049 /// and VINSERTI128 instructions.
4050 unsigned X86::getExtractVEXTRACT128Immediate(SDNode *N) {
4051   return getExtractVEXTRACTImmediate(N, 128);
4052 }
4053
4054 /// getExtractVEXTRACT256Immediate - Return the appropriate immediate
4055 /// to extract the specified EXTRACT_SUBVECTOR index with VEXTRACTF64x4
4056 /// and VINSERTI64x4 instructions.
4057 unsigned X86::getExtractVEXTRACT256Immediate(SDNode *N) {
4058   return getExtractVEXTRACTImmediate(N, 256);
4059 }
4060
4061 /// getInsertVINSERT128Immediate - Return the appropriate immediate
4062 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF128
4063 /// and VINSERTI128 instructions.
4064 unsigned X86::getInsertVINSERT128Immediate(SDNode *N) {
4065   return getInsertVINSERTImmediate(N, 128);
4066 }
4067
4068 /// getInsertVINSERT256Immediate - Return the appropriate immediate
4069 /// to insert at the specified INSERT_SUBVECTOR index with VINSERTF46x4
4070 /// and VINSERTI64x4 instructions.
4071 unsigned X86::getInsertVINSERT256Immediate(SDNode *N) {
4072   return getInsertVINSERTImmediate(N, 256);
4073 }
4074
4075 /// isZero - Returns true if Elt is a constant integer zero
4076 static bool isZero(SDValue V) {
4077   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
4078   return C && C->isNullValue();
4079 }
4080
4081 /// isZeroNode - Returns true if Elt is a constant zero or a floating point
4082 /// constant +0.0.
4083 bool X86::isZeroNode(SDValue Elt) {
4084   if (isZero(Elt))
4085     return true;
4086   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Elt))
4087     return CFP->getValueAPF().isPosZero();
4088   return false;
4089 }
4090
4091 /// getZeroVector - Returns a vector of specified type with all zero elements.
4092 ///
4093 static SDValue getZeroVector(EVT VT, const X86Subtarget *Subtarget,
4094                              SelectionDAG &DAG, SDLoc dl) {
4095   assert(VT.isVector() && "Expected a vector type");
4096
4097   // Always build SSE zero vectors as <4 x i32> bitcasted
4098   // to their dest type. This ensures they get CSE'd.
4099   SDValue Vec;
4100   if (VT.is128BitVector()) {  // SSE
4101     if (Subtarget->hasSSE2()) {  // SSE2
4102       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4103       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4104     } else { // SSE1
4105       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4106       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4f32, Cst, Cst, Cst, Cst);
4107     }
4108   } else if (VT.is256BitVector()) { // AVX
4109     if (Subtarget->hasInt256()) { // AVX2
4110       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4111       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4112       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4113     } else {
4114       // 256-bit logic and arithmetic instructions in AVX are all
4115       // floating-point, no support for integer ops. Emit fp zeroed vectors.
4116       SDValue Cst = DAG.getConstantFP(+0.0, dl, MVT::f32);
4117       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4118       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8f32, Ops);
4119     }
4120   } else if (VT.is512BitVector()) { // AVX-512
4121       SDValue Cst = DAG.getConstant(0, dl, MVT::i32);
4122       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst,
4123                         Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4124       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v16i32, Ops);
4125   } else if (VT.getScalarType() == MVT::i1) {
4126
4127     assert((Subtarget->hasBWI() || VT.getVectorNumElements() <= 16)
4128             && "Unexpected vector type");
4129     assert((Subtarget->hasVLX() || VT.getVectorNumElements() >= 8)
4130             && "Unexpected vector type");
4131     SDValue Cst = DAG.getConstant(0, dl, MVT::i1);
4132     SmallVector<SDValue, 64> Ops(VT.getVectorNumElements(), Cst);
4133     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
4134   } else
4135     llvm_unreachable("Unexpected vector type");
4136
4137   return DAG.getBitcast(VT, Vec);
4138 }
4139
4140 static SDValue ExtractSubVector(SDValue Vec, unsigned IdxVal,
4141                                 SelectionDAG &DAG, SDLoc dl,
4142                                 unsigned vectorWidth) {
4143   assert((vectorWidth == 128 || vectorWidth == 256) &&
4144          "Unsupported vector width");
4145   EVT VT = Vec.getValueType();
4146   EVT ElVT = VT.getVectorElementType();
4147   unsigned Factor = VT.getSizeInBits()/vectorWidth;
4148   EVT ResultVT = EVT::getVectorVT(*DAG.getContext(), ElVT,
4149                                   VT.getVectorNumElements()/Factor);
4150
4151   // Extract from UNDEF is UNDEF.
4152   if (Vec.getOpcode() == ISD::UNDEF)
4153     return DAG.getUNDEF(ResultVT);
4154
4155   // Extract the relevant vectorWidth bits.  Generate an EXTRACT_SUBVECTOR
4156   unsigned ElemsPerChunk = vectorWidth / ElVT.getSizeInBits();
4157
4158   // This is the index of the first element of the vectorWidth-bit chunk
4159   // we want.
4160   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits()) / vectorWidth)
4161                                * ElemsPerChunk);
4162
4163   // If the input is a buildvector just emit a smaller one.
4164   if (Vec.getOpcode() == ISD::BUILD_VECTOR)
4165     return DAG.getNode(ISD::BUILD_VECTOR, dl, ResultVT,
4166                        makeArrayRef(Vec->op_begin() + NormalizedIdxVal,
4167                                     ElemsPerChunk));
4168
4169   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4170   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, ResultVT, Vec, VecIdx);
4171 }
4172
4173 /// Generate a DAG to grab 128-bits from a vector > 128 bits.  This
4174 /// sets things up to match to an AVX VEXTRACTF128 / VEXTRACTI128
4175 /// or AVX-512 VEXTRACTF32x4 / VEXTRACTI32x4
4176 /// instructions or a simple subregister reference. Idx is an index in the
4177 /// 128 bits we want.  It need not be aligned to a 128-bit boundary.  That makes
4178 /// lowering EXTRACT_VECTOR_ELT operations easier.
4179 static SDValue Extract128BitVector(SDValue Vec, unsigned IdxVal,
4180                                    SelectionDAG &DAG, SDLoc dl) {
4181   assert((Vec.getValueType().is256BitVector() ||
4182           Vec.getValueType().is512BitVector()) && "Unexpected vector size!");
4183   return ExtractSubVector(Vec, IdxVal, DAG, dl, 128);
4184 }
4185
4186 /// Generate a DAG to grab 256-bits from a 512-bit vector.
4187 static SDValue Extract256BitVector(SDValue Vec, unsigned IdxVal,
4188                                    SelectionDAG &DAG, SDLoc dl) {
4189   assert(Vec.getValueType().is512BitVector() && "Unexpected vector size!");
4190   return ExtractSubVector(Vec, IdxVal, DAG, dl, 256);
4191 }
4192
4193 static SDValue InsertSubVector(SDValue Result, SDValue Vec,
4194                                unsigned IdxVal, SelectionDAG &DAG,
4195                                SDLoc dl, unsigned vectorWidth) {
4196   assert((vectorWidth == 128 || vectorWidth == 256) &&
4197          "Unsupported vector width");
4198   // Inserting UNDEF is Result
4199   if (Vec.getOpcode() == ISD::UNDEF)
4200     return Result;
4201   EVT VT = Vec.getValueType();
4202   EVT ElVT = VT.getVectorElementType();
4203   EVT ResultVT = Result.getValueType();
4204
4205   // Insert the relevant vectorWidth bits.
4206   unsigned ElemsPerChunk = vectorWidth/ElVT.getSizeInBits();
4207
4208   // This is the index of the first element of the vectorWidth-bit chunk
4209   // we want.
4210   unsigned NormalizedIdxVal = (((IdxVal * ElVT.getSizeInBits())/vectorWidth)
4211                                * ElemsPerChunk);
4212
4213   SDValue VecIdx = DAG.getIntPtrConstant(NormalizedIdxVal, dl);
4214   return DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Result, Vec, VecIdx);
4215 }
4216
4217 /// Generate a DAG to put 128-bits into a vector > 128 bits.  This
4218 /// sets things up to match to an AVX VINSERTF128/VINSERTI128 or
4219 /// AVX-512 VINSERTF32x4/VINSERTI32x4 instructions or a
4220 /// simple superregister reference.  Idx is an index in the 128 bits
4221 /// we want.  It need not be aligned to a 128-bit boundary.  That makes
4222 /// lowering INSERT_VECTOR_ELT operations easier.
4223 static SDValue Insert128BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4224                                   SelectionDAG &DAG, SDLoc dl) {
4225   assert(Vec.getValueType().is128BitVector() && "Unexpected vector size!");
4226
4227   // For insertion into the zero index (low half) of a 256-bit vector, it is
4228   // more efficient to generate a blend with immediate instead of an insert*128.
4229   // We are still creating an INSERT_SUBVECTOR below with an undef node to
4230   // extend the subvector to the size of the result vector. Make sure that
4231   // we are not recursing on that node by checking for undef here.
4232   if (IdxVal == 0 && Result.getValueType().is256BitVector() &&
4233       Result.getOpcode() != ISD::UNDEF) {
4234     EVT ResultVT = Result.getValueType();
4235     SDValue ZeroIndex = DAG.getIntPtrConstant(0, dl);
4236     SDValue Undef = DAG.getUNDEF(ResultVT);
4237     SDValue Vec256 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResultVT, Undef,
4238                                  Vec, ZeroIndex);
4239
4240     // The blend instruction, and therefore its mask, depend on the data type.
4241     MVT ScalarType = ResultVT.getScalarType().getSimpleVT();
4242     if (ScalarType.isFloatingPoint()) {
4243       // Choose either vblendps (float) or vblendpd (double).
4244       unsigned ScalarSize = ScalarType.getSizeInBits();
4245       assert((ScalarSize == 64 || ScalarSize == 32) && "Unknown float type");
4246       unsigned MaskVal = (ScalarSize == 64) ? 0x03 : 0x0f;
4247       SDValue Mask = DAG.getConstant(MaskVal, dl, MVT::i8);
4248       return DAG.getNode(X86ISD::BLENDI, dl, ResultVT, Result, Vec256, Mask);
4249     }
4250
4251     const X86Subtarget &Subtarget =
4252     static_cast<const X86Subtarget &>(DAG.getSubtarget());
4253
4254     // AVX2 is needed for 256-bit integer blend support.
4255     // Integers must be cast to 32-bit because there is only vpblendd;
4256     // vpblendw can't be used for this because it has a handicapped mask.
4257
4258     // If we don't have AVX2, then cast to float. Using a wrong domain blend
4259     // is still more efficient than using the wrong domain vinsertf128 that
4260     // will be created by InsertSubVector().
4261     MVT CastVT = Subtarget.hasAVX2() ? MVT::v8i32 : MVT::v8f32;
4262
4263     SDValue Mask = DAG.getConstant(0x0f, dl, MVT::i8);
4264     Vec256 = DAG.getBitcast(CastVT, Vec256);
4265     Vec256 = DAG.getNode(X86ISD::BLENDI, dl, CastVT, Result, Vec256, Mask);
4266     return DAG.getBitcast(ResultVT, Vec256);
4267   }
4268
4269   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 128);
4270 }
4271
4272 static SDValue Insert256BitVector(SDValue Result, SDValue Vec, unsigned IdxVal,
4273                                   SelectionDAG &DAG, SDLoc dl) {
4274   assert(Vec.getValueType().is256BitVector() && "Unexpected vector size!");
4275   return InsertSubVector(Result, Vec, IdxVal, DAG, dl, 256);
4276 }
4277
4278 /// Concat two 128-bit vectors into a 256 bit vector using VINSERTF128
4279 /// instructions. This is used because creating CONCAT_VECTOR nodes of
4280 /// BUILD_VECTORS returns a larger BUILD_VECTOR while we're trying to lower
4281 /// large BUILD_VECTORS.
4282 static SDValue Concat128BitVectors(SDValue V1, SDValue V2, EVT VT,
4283                                    unsigned NumElems, SelectionDAG &DAG,
4284                                    SDLoc dl) {
4285   SDValue V = Insert128BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4286   return Insert128BitVector(V, V2, NumElems/2, DAG, dl);
4287 }
4288
4289 static SDValue Concat256BitVectors(SDValue V1, SDValue V2, EVT VT,
4290                                    unsigned NumElems, SelectionDAG &DAG,
4291                                    SDLoc dl) {
4292   SDValue V = Insert256BitVector(DAG.getUNDEF(VT), V1, 0, DAG, dl);
4293   return Insert256BitVector(V, V2, NumElems/2, DAG, dl);
4294 }
4295
4296 /// getOnesVector - Returns a vector of specified type with all bits set.
4297 /// Always build ones vectors as <4 x i32> or <8 x i32>. For 256-bit types with
4298 /// no AVX2 supprt, use two <4 x i32> inserted in a <8 x i32> appropriately.
4299 /// Then bitcast to their original type, ensuring they get CSE'd.
4300 static SDValue getOnesVector(MVT VT, bool HasInt256, SelectionDAG &DAG,
4301                              SDLoc dl) {
4302   assert(VT.isVector() && "Expected a vector type");
4303
4304   SDValue Cst = DAG.getConstant(~0U, dl, MVT::i32);
4305   SDValue Vec;
4306   if (VT.is256BitVector()) {
4307     if (HasInt256) { // AVX2
4308       SDValue Ops[] = { Cst, Cst, Cst, Cst, Cst, Cst, Cst, Cst };
4309       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v8i32, Ops);
4310     } else { // AVX
4311       Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4312       Vec = Concat128BitVectors(Vec, Vec, MVT::v8i32, 8, DAG, dl);
4313     }
4314   } else if (VT.is128BitVector()) {
4315     Vec = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32, Cst, Cst, Cst, Cst);
4316   } else
4317     llvm_unreachable("Unexpected vector type");
4318
4319   return DAG.getBitcast(VT, Vec);
4320 }
4321
4322 /// getMOVLMask - Returns a vector_shuffle mask for an movs{s|d}, movd
4323 /// operation of specified width.
4324 static SDValue getMOVL(SelectionDAG &DAG, SDLoc dl, EVT VT, SDValue V1,
4325                        SDValue V2) {
4326   unsigned NumElems = VT.getVectorNumElements();
4327   SmallVector<int, 8> Mask;
4328   Mask.push_back(NumElems);
4329   for (unsigned i = 1; i != NumElems; ++i)
4330     Mask.push_back(i);
4331   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4332 }
4333
4334 /// getUnpackl - Returns a vector_shuffle node for an unpackl operation.
4335 static SDValue getUnpackl(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4336                           SDValue V2) {
4337   unsigned NumElems = VT.getVectorNumElements();
4338   SmallVector<int, 8> Mask;
4339   for (unsigned i = 0, e = NumElems/2; i != e; ++i) {
4340     Mask.push_back(i);
4341     Mask.push_back(i + NumElems);
4342   }
4343   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4344 }
4345
4346 /// getUnpackh - Returns a vector_shuffle node for an unpackh operation.
4347 static SDValue getUnpackh(SelectionDAG &DAG, SDLoc dl, MVT VT, SDValue V1,
4348                           SDValue V2) {
4349   unsigned NumElems = VT.getVectorNumElements();
4350   SmallVector<int, 8> Mask;
4351   for (unsigned i = 0, Half = NumElems/2; i != Half; ++i) {
4352     Mask.push_back(i + Half);
4353     Mask.push_back(i + NumElems + Half);
4354   }
4355   return DAG.getVectorShuffle(VT, dl, V1, V2, &Mask[0]);
4356 }
4357
4358 /// getShuffleVectorZeroOrUndef - Return a vector_shuffle of the specified
4359 /// vector of zero or undef vector.  This produces a shuffle where the low
4360 /// element of V2 is swizzled into the zero/undef vector, landing at element
4361 /// Idx.  This produces a shuffle mask like 4,1,2,3 (idx=0) or  0,1,2,4 (idx=3).
4362 static SDValue getShuffleVectorZeroOrUndef(SDValue V2, unsigned Idx,
4363                                            bool IsZero,
4364                                            const X86Subtarget *Subtarget,
4365                                            SelectionDAG &DAG) {
4366   MVT VT = V2.getSimpleValueType();
4367   SDValue V1 = IsZero
4368     ? getZeroVector(VT, Subtarget, DAG, SDLoc(V2)) : DAG.getUNDEF(VT);
4369   unsigned NumElems = VT.getVectorNumElements();
4370   SmallVector<int, 16> MaskVec;
4371   for (unsigned i = 0; i != NumElems; ++i)
4372     // If this is the insertion idx, put the low elt of V2 here.
4373     MaskVec.push_back(i == Idx ? NumElems : i);
4374   return DAG.getVectorShuffle(VT, SDLoc(V2), V1, V2, &MaskVec[0]);
4375 }
4376
4377 /// getTargetShuffleMask - Calculates the shuffle mask corresponding to the
4378 /// target specific opcode. Returns true if the Mask could be calculated. Sets
4379 /// IsUnary to true if only uses one source. Note that this will set IsUnary for
4380 /// shuffles which use a single input multiple times, and in those cases it will
4381 /// adjust the mask to only have indices within that single input.
4382 static bool getTargetShuffleMask(SDNode *N, MVT VT,
4383                                  SmallVectorImpl<int> &Mask, bool &IsUnary) {
4384   unsigned NumElems = VT.getVectorNumElements();
4385   SDValue ImmN;
4386
4387   IsUnary = false;
4388   bool IsFakeUnary = false;
4389   switch(N->getOpcode()) {
4390   case X86ISD::BLENDI:
4391     ImmN = N->getOperand(N->getNumOperands()-1);
4392     DecodeBLENDMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4393     break;
4394   case X86ISD::SHUFP:
4395     ImmN = N->getOperand(N->getNumOperands()-1);
4396     DecodeSHUFPMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4397     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4398     break;
4399   case X86ISD::UNPCKH:
4400     DecodeUNPCKHMask(VT, Mask);
4401     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4402     break;
4403   case X86ISD::UNPCKL:
4404     DecodeUNPCKLMask(VT, Mask);
4405     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4406     break;
4407   case X86ISD::MOVHLPS:
4408     DecodeMOVHLPSMask(NumElems, Mask);
4409     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4410     break;
4411   case X86ISD::MOVLHPS:
4412     DecodeMOVLHPSMask(NumElems, Mask);
4413     IsUnary = IsFakeUnary = N->getOperand(0) == N->getOperand(1);
4414     break;
4415   case X86ISD::PALIGNR:
4416     ImmN = N->getOperand(N->getNumOperands()-1);
4417     DecodePALIGNRMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4418     break;
4419   case X86ISD::PSHUFD:
4420   case X86ISD::VPERMILPI:
4421     ImmN = N->getOperand(N->getNumOperands()-1);
4422     DecodePSHUFMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4423     IsUnary = true;
4424     break;
4425   case X86ISD::PSHUFHW:
4426     ImmN = N->getOperand(N->getNumOperands()-1);
4427     DecodePSHUFHWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4428     IsUnary = true;
4429     break;
4430   case X86ISD::PSHUFLW:
4431     ImmN = N->getOperand(N->getNumOperands()-1);
4432     DecodePSHUFLWMask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4433     IsUnary = true;
4434     break;
4435   case X86ISD::PSHUFB: {
4436     IsUnary = true;
4437     SDValue MaskNode = N->getOperand(1);
4438     while (MaskNode->getOpcode() == ISD::BITCAST)
4439       MaskNode = MaskNode->getOperand(0);
4440
4441     if (MaskNode->getOpcode() == ISD::BUILD_VECTOR) {
4442       // If we have a build-vector, then things are easy.
4443       EVT VT = MaskNode.getValueType();
4444       assert(VT.isVector() &&
4445              "Can't produce a non-vector with a build_vector!");
4446       if (!VT.isInteger())
4447         return false;
4448
4449       int NumBytesPerElement = VT.getVectorElementType().getSizeInBits() / 8;
4450
4451       SmallVector<uint64_t, 32> RawMask;
4452       for (int i = 0, e = MaskNode->getNumOperands(); i < e; ++i) {
4453         SDValue Op = MaskNode->getOperand(i);
4454         if (Op->getOpcode() == ISD::UNDEF) {
4455           RawMask.push_back((uint64_t)SM_SentinelUndef);
4456           continue;
4457         }
4458         auto *CN = dyn_cast<ConstantSDNode>(Op.getNode());
4459         if (!CN)
4460           return false;
4461         APInt MaskElement = CN->getAPIntValue();
4462
4463         // We now have to decode the element which could be any integer size and
4464         // extract each byte of it.
4465         for (int j = 0; j < NumBytesPerElement; ++j) {
4466           // Note that this is x86 and so always little endian: the low byte is
4467           // the first byte of the mask.
4468           RawMask.push_back(MaskElement.getLoBits(8).getZExtValue());
4469           MaskElement = MaskElement.lshr(8);
4470         }
4471       }
4472       DecodePSHUFBMask(RawMask, Mask);
4473       break;
4474     }
4475
4476     auto *MaskLoad = dyn_cast<LoadSDNode>(MaskNode);
4477     if (!MaskLoad)
4478       return false;
4479
4480     SDValue Ptr = MaskLoad->getBasePtr();
4481     if (Ptr->getOpcode() == X86ISD::Wrapper ||
4482         Ptr->getOpcode() == X86ISD::WrapperRIP)
4483       Ptr = Ptr->getOperand(0);
4484
4485     auto *MaskCP = dyn_cast<ConstantPoolSDNode>(Ptr);
4486     if (!MaskCP || MaskCP->isMachineConstantPoolEntry())
4487       return false;
4488
4489     if (auto *C = dyn_cast<Constant>(MaskCP->getConstVal())) {
4490       DecodePSHUFBMask(C, Mask);
4491       if (Mask.empty())
4492         return false;
4493       break;
4494     }
4495
4496     return false;
4497   }
4498   case X86ISD::VPERMI:
4499     ImmN = N->getOperand(N->getNumOperands()-1);
4500     DecodeVPERMMask(cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4501     IsUnary = true;
4502     break;
4503   case X86ISD::MOVSS:
4504   case X86ISD::MOVSD:
4505     DecodeScalarMoveMask(VT, /* IsLoad */ false, Mask);
4506     break;
4507   case X86ISD::VPERM2X128:
4508     ImmN = N->getOperand(N->getNumOperands()-1);
4509     DecodeVPERM2X128Mask(VT, cast<ConstantSDNode>(ImmN)->getZExtValue(), Mask);
4510     if (Mask.empty()) return false;
4511     break;
4512   case X86ISD::MOVSLDUP:
4513     DecodeMOVSLDUPMask(VT, Mask);
4514     IsUnary = true;
4515     break;
4516   case X86ISD::MOVSHDUP:
4517     DecodeMOVSHDUPMask(VT, Mask);
4518     IsUnary = true;
4519     break;
4520   case X86ISD::MOVDDUP:
4521     DecodeMOVDDUPMask(VT, Mask);
4522     IsUnary = true;
4523     break;
4524   case X86ISD::MOVLHPD:
4525   case X86ISD::MOVLPD:
4526   case X86ISD::MOVLPS:
4527     // Not yet implemented
4528     return false;
4529   default: llvm_unreachable("unknown target shuffle node");
4530   }
4531
4532   // If we have a fake unary shuffle, the shuffle mask is spread across two
4533   // inputs that are actually the same node. Re-map the mask to always point
4534   // into the first input.
4535   if (IsFakeUnary)
4536     for (int &M : Mask)
4537       if (M >= (int)Mask.size())
4538         M -= Mask.size();
4539
4540   return true;
4541 }
4542
4543 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
4544 /// element of the result of the vector shuffle.
4545 static SDValue getShuffleScalarElt(SDNode *N, unsigned Index, SelectionDAG &DAG,
4546                                    unsigned Depth) {
4547   if (Depth == 6)
4548     return SDValue();  // Limit search depth.
4549
4550   SDValue V = SDValue(N, 0);
4551   EVT VT = V.getValueType();
4552   unsigned Opcode = V.getOpcode();
4553
4554   // Recurse into ISD::VECTOR_SHUFFLE node to find scalars.
4555   if (const ShuffleVectorSDNode *SV = dyn_cast<ShuffleVectorSDNode>(N)) {
4556     int Elt = SV->getMaskElt(Index);
4557
4558     if (Elt < 0)
4559       return DAG.getUNDEF(VT.getVectorElementType());
4560
4561     unsigned NumElems = VT.getVectorNumElements();
4562     SDValue NewV = (Elt < (int)NumElems) ? SV->getOperand(0)
4563                                          : SV->getOperand(1);
4564     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG, Depth+1);
4565   }
4566
4567   // Recurse into target specific vector shuffles to find scalars.
4568   if (isTargetShuffle(Opcode)) {
4569     MVT ShufVT = V.getSimpleValueType();
4570     unsigned NumElems = ShufVT.getVectorNumElements();
4571     SmallVector<int, 16> ShuffleMask;
4572     bool IsUnary;
4573
4574     if (!getTargetShuffleMask(N, ShufVT, ShuffleMask, IsUnary))
4575       return SDValue();
4576
4577     int Elt = ShuffleMask[Index];
4578     if (Elt < 0)
4579       return DAG.getUNDEF(ShufVT.getVectorElementType());
4580
4581     SDValue NewV = (Elt < (int)NumElems) ? N->getOperand(0)
4582                                          : N->getOperand(1);
4583     return getShuffleScalarElt(NewV.getNode(), Elt % NumElems, DAG,
4584                                Depth+1);
4585   }
4586
4587   // Actual nodes that may contain scalar elements
4588   if (Opcode == ISD::BITCAST) {
4589     V = V.getOperand(0);
4590     EVT SrcVT = V.getValueType();
4591     unsigned NumElems = VT.getVectorNumElements();
4592
4593     if (!SrcVT.isVector() || SrcVT.getVectorNumElements() != NumElems)
4594       return SDValue();
4595   }
4596
4597   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
4598     return (Index == 0) ? V.getOperand(0)
4599                         : DAG.getUNDEF(VT.getVectorElementType());
4600
4601   if (V.getOpcode() == ISD::BUILD_VECTOR)
4602     return V.getOperand(Index);
4603
4604   return SDValue();
4605 }
4606
4607 /// LowerBuildVectorv16i8 - Custom lower build_vector of v16i8.
4608 ///
4609 static SDValue LowerBuildVectorv16i8(SDValue Op, unsigned NonZeros,
4610                                        unsigned NumNonZero, unsigned NumZero,
4611                                        SelectionDAG &DAG,
4612                                        const X86Subtarget* Subtarget,
4613                                        const TargetLowering &TLI) {
4614   if (NumNonZero > 8)
4615     return SDValue();
4616
4617   SDLoc dl(Op);
4618   SDValue V;
4619   bool First = true;
4620
4621   // SSE4.1 - use PINSRB to insert each byte directly.
4622   if (Subtarget->hasSSE41()) {
4623     for (unsigned i = 0; i < 16; ++i) {
4624       bool isNonZero = (NonZeros & (1 << i)) != 0;
4625       if (isNonZero) {
4626         if (First) {
4627           if (NumZero)
4628             V = getZeroVector(MVT::v16i8, Subtarget, DAG, dl);
4629           else
4630             V = DAG.getUNDEF(MVT::v16i8);
4631           First = false;
4632         }
4633         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4634                         MVT::v16i8, V, Op.getOperand(i),
4635                         DAG.getIntPtrConstant(i, dl));
4636       }
4637     }
4638
4639     return V;
4640   }
4641
4642   // Pre-SSE4.1 - merge byte pairs and insert with PINSRW.
4643   for (unsigned i = 0; i < 16; ++i) {
4644     bool ThisIsNonZero = (NonZeros & (1 << i)) != 0;
4645     if (ThisIsNonZero && First) {
4646       if (NumZero)
4647         V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4648       else
4649         V = DAG.getUNDEF(MVT::v8i16);
4650       First = false;
4651     }
4652
4653     if ((i & 1) != 0) {
4654       SDValue ThisElt, LastElt;
4655       bool LastIsNonZero = (NonZeros & (1 << (i-1))) != 0;
4656       if (LastIsNonZero) {
4657         LastElt = DAG.getNode(ISD::ZERO_EXTEND, dl,
4658                               MVT::i16, Op.getOperand(i-1));
4659       }
4660       if (ThisIsNonZero) {
4661         ThisElt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i16, Op.getOperand(i));
4662         ThisElt = DAG.getNode(ISD::SHL, dl, MVT::i16,
4663                               ThisElt, DAG.getConstant(8, dl, MVT::i8));
4664         if (LastIsNonZero)
4665           ThisElt = DAG.getNode(ISD::OR, dl, MVT::i16, ThisElt, LastElt);
4666       } else
4667         ThisElt = LastElt;
4668
4669       if (ThisElt.getNode())
4670         V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, MVT::v8i16, V, ThisElt,
4671                         DAG.getIntPtrConstant(i/2, dl));
4672     }
4673   }
4674
4675   return DAG.getBitcast(MVT::v16i8, V);
4676 }
4677
4678 /// LowerBuildVectorv8i16 - Custom lower build_vector of v8i16.
4679 ///
4680 static SDValue LowerBuildVectorv8i16(SDValue Op, unsigned NonZeros,
4681                                      unsigned NumNonZero, unsigned NumZero,
4682                                      SelectionDAG &DAG,
4683                                      const X86Subtarget* Subtarget,
4684                                      const TargetLowering &TLI) {
4685   if (NumNonZero > 4)
4686     return SDValue();
4687
4688   SDLoc dl(Op);
4689   SDValue V;
4690   bool First = true;
4691   for (unsigned i = 0; i < 8; ++i) {
4692     bool isNonZero = (NonZeros & (1 << i)) != 0;
4693     if (isNonZero) {
4694       if (First) {
4695         if (NumZero)
4696           V = getZeroVector(MVT::v8i16, Subtarget, DAG, dl);
4697         else
4698           V = DAG.getUNDEF(MVT::v8i16);
4699         First = false;
4700       }
4701       V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl,
4702                       MVT::v8i16, V, Op.getOperand(i),
4703                       DAG.getIntPtrConstant(i, dl));
4704     }
4705   }
4706
4707   return V;
4708 }
4709
4710 /// LowerBuildVectorv4x32 - Custom lower build_vector of v4i32 or v4f32.
4711 static SDValue LowerBuildVectorv4x32(SDValue Op, SelectionDAG &DAG,
4712                                      const X86Subtarget *Subtarget,
4713                                      const TargetLowering &TLI) {
4714   // Find all zeroable elements.
4715   std::bitset<4> Zeroable;
4716   for (int i=0; i < 4; ++i) {
4717     SDValue Elt = Op->getOperand(i);
4718     Zeroable[i] = (Elt.getOpcode() == ISD::UNDEF || X86::isZeroNode(Elt));
4719   }
4720   assert(Zeroable.size() - Zeroable.count() > 1 &&
4721          "We expect at least two non-zero elements!");
4722
4723   // We only know how to deal with build_vector nodes where elements are either
4724   // zeroable or extract_vector_elt with constant index.
4725   SDValue FirstNonZero;
4726   unsigned FirstNonZeroIdx;
4727   for (unsigned i=0; i < 4; ++i) {
4728     if (Zeroable[i])
4729       continue;
4730     SDValue Elt = Op->getOperand(i);
4731     if (Elt.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
4732         !isa<ConstantSDNode>(Elt.getOperand(1)))
4733       return SDValue();
4734     // Make sure that this node is extracting from a 128-bit vector.
4735     MVT VT = Elt.getOperand(0).getSimpleValueType();
4736     if (!VT.is128BitVector())
4737       return SDValue();
4738     if (!FirstNonZero.getNode()) {
4739       FirstNonZero = Elt;
4740       FirstNonZeroIdx = i;
4741     }
4742   }
4743
4744   assert(FirstNonZero.getNode() && "Unexpected build vector of all zeros!");
4745   SDValue V1 = FirstNonZero.getOperand(0);
4746   MVT VT = V1.getSimpleValueType();
4747
4748   // See if this build_vector can be lowered as a blend with zero.
4749   SDValue Elt;
4750   unsigned EltMaskIdx, EltIdx;
4751   int Mask[4];
4752   for (EltIdx = 0; EltIdx < 4; ++EltIdx) {
4753     if (Zeroable[EltIdx]) {
4754       // The zero vector will be on the right hand side.
4755       Mask[EltIdx] = EltIdx+4;
4756       continue;
4757     }
4758
4759     Elt = Op->getOperand(EltIdx);
4760     // By construction, Elt is a EXTRACT_VECTOR_ELT with constant index.
4761     EltMaskIdx = cast<ConstantSDNode>(Elt.getOperand(1))->getZExtValue();
4762     if (Elt.getOperand(0) != V1 || EltMaskIdx != EltIdx)
4763       break;
4764     Mask[EltIdx] = EltIdx;
4765   }
4766
4767   if (EltIdx == 4) {
4768     // Let the shuffle legalizer deal with blend operations.
4769     SDValue VZero = getZeroVector(VT, Subtarget, DAG, SDLoc(Op));
4770     if (V1.getSimpleValueType() != VT)
4771       V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), VT, V1);
4772     return DAG.getVectorShuffle(VT, SDLoc(V1), V1, VZero, &Mask[0]);
4773   }
4774
4775   // See if we can lower this build_vector to a INSERTPS.
4776   if (!Subtarget->hasSSE41())
4777     return SDValue();
4778
4779   SDValue V2 = Elt.getOperand(0);
4780   if (Elt == FirstNonZero && EltIdx == FirstNonZeroIdx)
4781     V1 = SDValue();
4782
4783   bool CanFold = true;
4784   for (unsigned i = EltIdx + 1; i < 4 && CanFold; ++i) {
4785     if (Zeroable[i])
4786       continue;
4787
4788     SDValue Current = Op->getOperand(i);
4789     SDValue SrcVector = Current->getOperand(0);
4790     if (!V1.getNode())
4791       V1 = SrcVector;
4792     CanFold = SrcVector == V1 &&
4793       cast<ConstantSDNode>(Current.getOperand(1))->getZExtValue() == i;
4794   }
4795
4796   if (!CanFold)
4797     return SDValue();
4798
4799   assert(V1.getNode() && "Expected at least two non-zero elements!");
4800   if (V1.getSimpleValueType() != MVT::v4f32)
4801     V1 = DAG.getNode(ISD::BITCAST, SDLoc(V1), MVT::v4f32, V1);
4802   if (V2.getSimpleValueType() != MVT::v4f32)
4803     V2 = DAG.getNode(ISD::BITCAST, SDLoc(V2), MVT::v4f32, V2);
4804
4805   // Ok, we can emit an INSERTPS instruction.
4806   unsigned ZMask = Zeroable.to_ulong();
4807
4808   unsigned InsertPSMask = EltMaskIdx << 6 | EltIdx << 4 | ZMask;
4809   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
4810   SDLoc DL(Op);
4811   SDValue Result = DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
4812                                DAG.getIntPtrConstant(InsertPSMask, DL));
4813   return DAG.getBitcast(VT, Result);
4814 }
4815
4816 /// Return a vector logical shift node.
4817 static SDValue getVShift(bool isLeft, EVT VT, SDValue SrcOp,
4818                          unsigned NumBits, SelectionDAG &DAG,
4819                          const TargetLowering &TLI, SDLoc dl) {
4820   assert(VT.is128BitVector() && "Unknown type for VShift");
4821   MVT ShVT = MVT::v2i64;
4822   unsigned Opc = isLeft ? X86ISD::VSHLDQ : X86ISD::VSRLDQ;
4823   SrcOp = DAG.getBitcast(ShVT, SrcOp);
4824   MVT ScalarShiftTy = TLI.getScalarShiftAmountTy(SrcOp.getValueType());
4825   assert(NumBits % 8 == 0 && "Only support byte sized shifts");
4826   SDValue ShiftVal = DAG.getConstant(NumBits/8, dl, ScalarShiftTy);
4827   return DAG.getBitcast(VT, DAG.getNode(Opc, dl, ShVT, SrcOp, ShiftVal));
4828 }
4829
4830 static SDValue
4831 LowerAsSplatVectorLoad(SDValue SrcOp, MVT VT, SDLoc dl, SelectionDAG &DAG) {
4832
4833   // Check if the scalar load can be widened into a vector load. And if
4834   // the address is "base + cst" see if the cst can be "absorbed" into
4835   // the shuffle mask.
4836   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(SrcOp)) {
4837     SDValue Ptr = LD->getBasePtr();
4838     if (!ISD::isNormalLoad(LD) || LD->isVolatile())
4839       return SDValue();
4840     EVT PVT = LD->getValueType(0);
4841     if (PVT != MVT::i32 && PVT != MVT::f32)
4842       return SDValue();
4843
4844     int FI = -1;
4845     int64_t Offset = 0;
4846     if (FrameIndexSDNode *FINode = dyn_cast<FrameIndexSDNode>(Ptr)) {
4847       FI = FINode->getIndex();
4848       Offset = 0;
4849     } else if (DAG.isBaseWithConstantOffset(Ptr) &&
4850                isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
4851       FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
4852       Offset = Ptr.getConstantOperandVal(1);
4853       Ptr = Ptr.getOperand(0);
4854     } else {
4855       return SDValue();
4856     }
4857
4858     // FIXME: 256-bit vector instructions don't require a strict alignment,
4859     // improve this code to support it better.
4860     unsigned RequiredAlign = VT.getSizeInBits()/8;
4861     SDValue Chain = LD->getChain();
4862     // Make sure the stack object alignment is at least 16 or 32.
4863     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
4864     if (DAG.InferPtrAlignment(Ptr) < RequiredAlign) {
4865       if (MFI->isFixedObjectIndex(FI)) {
4866         // Can't change the alignment. FIXME: It's possible to compute
4867         // the exact stack offset and reference FI + adjust offset instead.
4868         // If someone *really* cares about this. That's the way to implement it.
4869         return SDValue();
4870       } else {
4871         MFI->setObjectAlignment(FI, RequiredAlign);
4872       }
4873     }
4874
4875     // (Offset % 16 or 32) must be multiple of 4. Then address is then
4876     // Ptr + (Offset & ~15).
4877     if (Offset < 0)
4878       return SDValue();
4879     if ((Offset % RequiredAlign) & 3)
4880       return SDValue();
4881     int64_t StartOffset = Offset & ~(RequiredAlign-1);
4882     if (StartOffset) {
4883       SDLoc DL(Ptr);
4884       Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4885                         DAG.getConstant(StartOffset, DL, Ptr.getValueType()));
4886     }
4887
4888     int EltNo = (Offset - StartOffset) >> 2;
4889     unsigned NumElems = VT.getVectorNumElements();
4890
4891     EVT NVT = EVT::getVectorVT(*DAG.getContext(), PVT, NumElems);
4892     SDValue V1 = DAG.getLoad(NVT, dl, Chain, Ptr,
4893                              LD->getPointerInfo().getWithOffset(StartOffset),
4894                              false, false, false, 0);
4895
4896     SmallVector<int, 8> Mask(NumElems, EltNo);
4897
4898     return DAG.getVectorShuffle(NVT, dl, V1, DAG.getUNDEF(NVT), &Mask[0]);
4899   }
4900
4901   return SDValue();
4902 }
4903
4904 /// Given the initializing elements 'Elts' of a vector of type 'VT', see if the
4905 /// elements can be replaced by a single large load which has the same value as
4906 /// a build_vector or insert_subvector whose loaded operands are 'Elts'.
4907 ///
4908 /// Example: <load i32 *a, load i32 *a+4, undef, undef> -> zextload a
4909 ///
4910 /// FIXME: we'd also like to handle the case where the last elements are zero
4911 /// rather than undef via VZEXT_LOAD, but we do not detect that case today.
4912 /// There's even a handy isZeroNode for that purpose.
4913 static SDValue EltsFromConsecutiveLoads(EVT VT, ArrayRef<SDValue> Elts,
4914                                         SDLoc &DL, SelectionDAG &DAG,
4915                                         bool isAfterLegalize) {
4916   unsigned NumElems = Elts.size();
4917
4918   LoadSDNode *LDBase = nullptr;
4919   unsigned LastLoadedElt = -1U;
4920
4921   // For each element in the initializer, see if we've found a load or an undef.
4922   // If we don't find an initial load element, or later load elements are
4923   // non-consecutive, bail out.
4924   for (unsigned i = 0; i < NumElems; ++i) {
4925     SDValue Elt = Elts[i];
4926     // Look through a bitcast.
4927     if (Elt.getNode() && Elt.getOpcode() == ISD::BITCAST)
4928       Elt = Elt.getOperand(0);
4929     if (!Elt.getNode() ||
4930         (Elt.getOpcode() != ISD::UNDEF && !ISD::isNON_EXTLoad(Elt.getNode())))
4931       return SDValue();
4932     if (!LDBase) {
4933       if (Elt.getNode()->getOpcode() == ISD::UNDEF)
4934         return SDValue();
4935       LDBase = cast<LoadSDNode>(Elt.getNode());
4936       LastLoadedElt = i;
4937       continue;
4938     }
4939     if (Elt.getOpcode() == ISD::UNDEF)
4940       continue;
4941
4942     LoadSDNode *LD = cast<LoadSDNode>(Elt);
4943     EVT LdVT = Elt.getValueType();
4944     // Each loaded element must be the correct fractional portion of the
4945     // requested vector load.
4946     if (LdVT.getSizeInBits() != VT.getSizeInBits() / NumElems)
4947       return SDValue();
4948     if (!DAG.isConsecutiveLoad(LD, LDBase, LdVT.getSizeInBits() / 8, i))
4949       return SDValue();
4950     LastLoadedElt = i;
4951   }
4952
4953   // If we have found an entire vector of loads and undefs, then return a large
4954   // load of the entire vector width starting at the base pointer.  If we found
4955   // consecutive loads for the low half, generate a vzext_load node.
4956   if (LastLoadedElt == NumElems - 1) {
4957     assert(LDBase && "Did not find base load for merging consecutive loads");
4958     EVT EltVT = LDBase->getValueType(0);
4959     // Ensure that the input vector size for the merged loads matches the
4960     // cumulative size of the input elements.
4961     if (VT.getSizeInBits() != EltVT.getSizeInBits() * NumElems)
4962       return SDValue();
4963
4964     if (isAfterLegalize &&
4965         !DAG.getTargetLoweringInfo().isOperationLegal(ISD::LOAD, VT))
4966       return SDValue();
4967
4968     SDValue NewLd = SDValue();
4969
4970     NewLd = DAG.getLoad(VT, DL, LDBase->getChain(), LDBase->getBasePtr(),
4971                         LDBase->getPointerInfo(), LDBase->isVolatile(),
4972                         LDBase->isNonTemporal(), LDBase->isInvariant(),
4973                         LDBase->getAlignment());
4974
4975     if (LDBase->hasAnyUseOfValue(1)) {
4976       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
4977                                      SDValue(LDBase, 1),
4978                                      SDValue(NewLd.getNode(), 1));
4979       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
4980       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
4981                              SDValue(NewLd.getNode(), 1));
4982     }
4983
4984     return NewLd;
4985   }
4986
4987   //TODO: The code below fires only for for loading the low v2i32 / v2f32
4988   //of a v4i32 / v4f32. It's probably worth generalizing.
4989   EVT EltVT = VT.getVectorElementType();
4990   if (NumElems == 4 && LastLoadedElt == 1 && (EltVT.getSizeInBits() == 32) &&
4991       DAG.getTargetLoweringInfo().isTypeLegal(MVT::v2i64)) {
4992     SDVTList Tys = DAG.getVTList(MVT::v2i64, MVT::Other);
4993     SDValue Ops[] = { LDBase->getChain(), LDBase->getBasePtr() };
4994     SDValue ResNode =
4995         DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, DL, Tys, Ops, MVT::i64,
4996                                 LDBase->getPointerInfo(),
4997                                 LDBase->getAlignment(),
4998                                 false/*isVolatile*/, true/*ReadMem*/,
4999                                 false/*WriteMem*/);
5000
5001     // Make sure the newly-created LOAD is in the same position as LDBase in
5002     // terms of dependency. We create a TokenFactor for LDBase and ResNode, and
5003     // update uses of LDBase's output chain to use the TokenFactor.
5004     if (LDBase->hasAnyUseOfValue(1)) {
5005       SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
5006                              SDValue(LDBase, 1), SDValue(ResNode.getNode(), 1));
5007       DAG.ReplaceAllUsesOfValueWith(SDValue(LDBase, 1), NewChain);
5008       DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(LDBase, 1),
5009                              SDValue(ResNode.getNode(), 1));
5010     }
5011
5012     return DAG.getBitcast(VT, ResNode);
5013   }
5014   return SDValue();
5015 }
5016
5017 /// LowerVectorBroadcast - Attempt to use the vbroadcast instruction
5018 /// to generate a splat value for the following cases:
5019 /// 1. A splat BUILD_VECTOR which uses a single scalar load, or a constant.
5020 /// 2. A splat shuffle which uses a scalar_to_vector node which comes from
5021 /// a scalar load, or a constant.
5022 /// The VBROADCAST node is returned when a pattern is found,
5023 /// or SDValue() otherwise.
5024 static SDValue LowerVectorBroadcast(SDValue Op, const X86Subtarget* Subtarget,
5025                                     SelectionDAG &DAG) {
5026   // VBROADCAST requires AVX.
5027   // TODO: Splats could be generated for non-AVX CPUs using SSE
5028   // instructions, but there's less potential gain for only 128-bit vectors.
5029   if (!Subtarget->hasAVX())
5030     return SDValue();
5031
5032   MVT VT = Op.getSimpleValueType();
5033   SDLoc dl(Op);
5034
5035   assert((VT.is128BitVector() || VT.is256BitVector() || VT.is512BitVector()) &&
5036          "Unsupported vector type for broadcast.");
5037
5038   SDValue Ld;
5039   bool ConstSplatVal;
5040
5041   switch (Op.getOpcode()) {
5042     default:
5043       // Unknown pattern found.
5044       return SDValue();
5045
5046     case ISD::BUILD_VECTOR: {
5047       auto *BVOp = cast<BuildVectorSDNode>(Op.getNode());
5048       BitVector UndefElements;
5049       SDValue Splat = BVOp->getSplatValue(&UndefElements);
5050
5051       // We need a splat of a single value to use broadcast, and it doesn't
5052       // make any sense if the value is only in one element of the vector.
5053       if (!Splat || (VT.getVectorNumElements() - UndefElements.count()) <= 1)
5054         return SDValue();
5055
5056       Ld = Splat;
5057       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5058                        Ld.getOpcode() == ISD::ConstantFP);
5059
5060       // Make sure that all of the users of a non-constant load are from the
5061       // BUILD_VECTOR node.
5062       if (!ConstSplatVal && !BVOp->isOnlyUserOf(Ld.getNode()))
5063         return SDValue();
5064       break;
5065     }
5066
5067     case ISD::VECTOR_SHUFFLE: {
5068       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
5069
5070       // Shuffles must have a splat mask where the first element is
5071       // broadcasted.
5072       if ((!SVOp->isSplat()) || SVOp->getMaskElt(0) != 0)
5073         return SDValue();
5074
5075       SDValue Sc = Op.getOperand(0);
5076       if (Sc.getOpcode() != ISD::SCALAR_TO_VECTOR &&
5077           Sc.getOpcode() != ISD::BUILD_VECTOR) {
5078
5079         if (!Subtarget->hasInt256())
5080           return SDValue();
5081
5082         // Use the register form of the broadcast instruction available on AVX2.
5083         if (VT.getSizeInBits() >= 256)
5084           Sc = Extract128BitVector(Sc, 0, DAG, dl);
5085         return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Sc);
5086       }
5087
5088       Ld = Sc.getOperand(0);
5089       ConstSplatVal = (Ld.getOpcode() == ISD::Constant ||
5090                        Ld.getOpcode() == ISD::ConstantFP);
5091
5092       // The scalar_to_vector node and the suspected
5093       // load node must have exactly one user.
5094       // Constants may have multiple users.
5095
5096       // AVX-512 has register version of the broadcast
5097       bool hasRegVer = Subtarget->hasAVX512() && VT.is512BitVector() &&
5098         Ld.getValueType().getSizeInBits() >= 32;
5099       if (!ConstSplatVal && ((!Sc.hasOneUse() || !Ld.hasOneUse()) &&
5100           !hasRegVer))
5101         return SDValue();
5102       break;
5103     }
5104   }
5105
5106   unsigned ScalarSize = Ld.getValueType().getSizeInBits();
5107   bool IsGE256 = (VT.getSizeInBits() >= 256);
5108
5109   // When optimizing for size, generate up to 5 extra bytes for a broadcast
5110   // instruction to save 8 or more bytes of constant pool data.
5111   // TODO: If multiple splats are generated to load the same constant,
5112   // it may be detrimental to overall size. There needs to be a way to detect
5113   // that condition to know if this is truly a size win.
5114   const Function *F = DAG.getMachineFunction().getFunction();
5115   bool OptForSize = F->hasFnAttribute(Attribute::OptimizeForSize);
5116
5117   // Handle broadcasting a single constant scalar from the constant pool
5118   // into a vector.
5119   // On Sandybridge (no AVX2), it is still better to load a constant vector
5120   // from the constant pool and not to broadcast it from a scalar.
5121   // But override that restriction when optimizing for size.
5122   // TODO: Check if splatting is recommended for other AVX-capable CPUs.
5123   if (ConstSplatVal && (Subtarget->hasAVX2() || OptForSize)) {
5124     EVT CVT = Ld.getValueType();
5125     assert(!CVT.isVector() && "Must not broadcast a vector type");
5126
5127     // Splat f32, i32, v4f64, v4i64 in all cases with AVX2.
5128     // For size optimization, also splat v2f64 and v2i64, and for size opt
5129     // with AVX2, also splat i8 and i16.
5130     // With pattern matching, the VBROADCAST node may become a VMOVDDUP.
5131     if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5132         (OptForSize && (ScalarSize == 64 || Subtarget->hasAVX2()))) {
5133       const Constant *C = nullptr;
5134       if (ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Ld))
5135         C = CI->getConstantIntValue();
5136       else if (ConstantFPSDNode *CF = dyn_cast<ConstantFPSDNode>(Ld))
5137         C = CF->getConstantFPValue();
5138
5139       assert(C && "Invalid constant type");
5140
5141       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5142       SDValue CP = DAG.getConstantPool(C, TLI.getPointerTy());
5143       unsigned Alignment = cast<ConstantPoolSDNode>(CP)->getAlignment();
5144       Ld = DAG.getLoad(CVT, dl, DAG.getEntryNode(), CP,
5145                        MachinePointerInfo::getConstantPool(),
5146                        false, false, false, Alignment);
5147
5148       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5149     }
5150   }
5151
5152   bool IsLoad = ISD::isNormalLoad(Ld.getNode());
5153
5154   // Handle AVX2 in-register broadcasts.
5155   if (!IsLoad && Subtarget->hasInt256() &&
5156       (ScalarSize == 32 || (IsGE256 && ScalarSize == 64)))
5157     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5158
5159   // The scalar source must be a normal load.
5160   if (!IsLoad)
5161     return SDValue();
5162
5163   if (ScalarSize == 32 || (IsGE256 && ScalarSize == 64) ||
5164       (Subtarget->hasVLX() && ScalarSize == 64))
5165     return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5166
5167   // The integer check is needed for the 64-bit into 128-bit so it doesn't match
5168   // double since there is no vbroadcastsd xmm
5169   if (Subtarget->hasInt256() && Ld.getValueType().isInteger()) {
5170     if (ScalarSize == 8 || ScalarSize == 16 || ScalarSize == 64)
5171       return DAG.getNode(X86ISD::VBROADCAST, dl, VT, Ld);
5172   }
5173
5174   // Unsupported broadcast.
5175   return SDValue();
5176 }
5177
5178 /// \brief For an EXTRACT_VECTOR_ELT with a constant index return the real
5179 /// underlying vector and index.
5180 ///
5181 /// Modifies \p ExtractedFromVec to the real vector and returns the real
5182 /// index.
5183 static int getUnderlyingExtractedFromVec(SDValue &ExtractedFromVec,
5184                                          SDValue ExtIdx) {
5185   int Idx = cast<ConstantSDNode>(ExtIdx)->getZExtValue();
5186   if (!isa<ShuffleVectorSDNode>(ExtractedFromVec))
5187     return Idx;
5188
5189   // For 256-bit vectors, LowerEXTRACT_VECTOR_ELT_SSE4 may have already
5190   // lowered this:
5191   //   (extract_vector_elt (v8f32 %vreg1), Constant<6>)
5192   // to:
5193   //   (extract_vector_elt (vector_shuffle<2,u,u,u>
5194   //                           (extract_subvector (v8f32 %vreg0), Constant<4>),
5195   //                           undef)
5196   //                       Constant<0>)
5197   // In this case the vector is the extract_subvector expression and the index
5198   // is 2, as specified by the shuffle.
5199   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(ExtractedFromVec);
5200   SDValue ShuffleVec = SVOp->getOperand(0);
5201   MVT ShuffleVecVT = ShuffleVec.getSimpleValueType();
5202   assert(ShuffleVecVT.getVectorElementType() ==
5203          ExtractedFromVec.getSimpleValueType().getVectorElementType());
5204
5205   int ShuffleIdx = SVOp->getMaskElt(Idx);
5206   if (isUndefOrInRange(ShuffleIdx, 0, ShuffleVecVT.getVectorNumElements())) {
5207     ExtractedFromVec = ShuffleVec;
5208     return ShuffleIdx;
5209   }
5210   return Idx;
5211 }
5212
5213 static SDValue buildFromShuffleMostly(SDValue Op, SelectionDAG &DAG) {
5214   MVT VT = Op.getSimpleValueType();
5215
5216   // Skip if insert_vec_elt is not supported.
5217   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
5218   if (!TLI.isOperationLegalOrCustom(ISD::INSERT_VECTOR_ELT, VT))
5219     return SDValue();
5220
5221   SDLoc DL(Op);
5222   unsigned NumElems = Op.getNumOperands();
5223
5224   SDValue VecIn1;
5225   SDValue VecIn2;
5226   SmallVector<unsigned, 4> InsertIndices;
5227   SmallVector<int, 8> Mask(NumElems, -1);
5228
5229   for (unsigned i = 0; i != NumElems; ++i) {
5230     unsigned Opc = Op.getOperand(i).getOpcode();
5231
5232     if (Opc == ISD::UNDEF)
5233       continue;
5234
5235     if (Opc != ISD::EXTRACT_VECTOR_ELT) {
5236       // Quit if more than 1 elements need inserting.
5237       if (InsertIndices.size() > 1)
5238         return SDValue();
5239
5240       InsertIndices.push_back(i);
5241       continue;
5242     }
5243
5244     SDValue ExtractedFromVec = Op.getOperand(i).getOperand(0);
5245     SDValue ExtIdx = Op.getOperand(i).getOperand(1);
5246     // Quit if non-constant index.
5247     if (!isa<ConstantSDNode>(ExtIdx))
5248       return SDValue();
5249     int Idx = getUnderlyingExtractedFromVec(ExtractedFromVec, ExtIdx);
5250
5251     // Quit if extracted from vector of different type.
5252     if (ExtractedFromVec.getValueType() != VT)
5253       return SDValue();
5254
5255     if (!VecIn1.getNode())
5256       VecIn1 = ExtractedFromVec;
5257     else if (VecIn1 != ExtractedFromVec) {
5258       if (!VecIn2.getNode())
5259         VecIn2 = ExtractedFromVec;
5260       else if (VecIn2 != ExtractedFromVec)
5261         // Quit if more than 2 vectors to shuffle
5262         return SDValue();
5263     }
5264
5265     if (ExtractedFromVec == VecIn1)
5266       Mask[i] = Idx;
5267     else if (ExtractedFromVec == VecIn2)
5268       Mask[i] = Idx + NumElems;
5269   }
5270
5271   if (!VecIn1.getNode())
5272     return SDValue();
5273
5274   VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
5275   SDValue NV = DAG.getVectorShuffle(VT, DL, VecIn1, VecIn2, &Mask[0]);
5276   for (unsigned i = 0, e = InsertIndices.size(); i != e; ++i) {
5277     unsigned Idx = InsertIndices[i];
5278     NV = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, NV, Op.getOperand(Idx),
5279                      DAG.getIntPtrConstant(Idx, DL));
5280   }
5281
5282   return NV;
5283 }
5284
5285 static SDValue ConvertI1VectorToInterger(SDValue Op, SelectionDAG &DAG) {
5286   assert(ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
5287          Op.getScalarValueSizeInBits() == 1 &&
5288          "Can not convert non-constant vector");
5289   uint64_t Immediate = 0;
5290   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5291     SDValue In = Op.getOperand(idx);
5292     if (In.getOpcode() != ISD::UNDEF)
5293       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5294   }
5295   SDLoc dl(Op);
5296   MVT VT =
5297    MVT::getIntegerVT(std::max((int)Op.getValueType().getSizeInBits(), 8));
5298   return DAG.getConstant(Immediate, dl, VT);
5299 }
5300 // Lower BUILD_VECTOR operation for v8i1 and v16i1 types.
5301 SDValue
5302 X86TargetLowering::LowerBUILD_VECTORvXi1(SDValue Op, SelectionDAG &DAG) const {
5303
5304   MVT VT = Op.getSimpleValueType();
5305   assert((VT.getVectorElementType() == MVT::i1) &&
5306          "Unexpected type in LowerBUILD_VECTORvXi1!");
5307
5308   SDLoc dl(Op);
5309   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5310     SDValue Cst = DAG.getTargetConstant(0, dl, MVT::i1);
5311     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5312     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5313   }
5314
5315   if (ISD::isBuildVectorAllOnes(Op.getNode())) {
5316     SDValue Cst = DAG.getTargetConstant(1, dl, MVT::i1);
5317     SmallVector<SDValue, 16> Ops(VT.getVectorNumElements(), Cst);
5318     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
5319   }
5320
5321   if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
5322     SDValue Imm = ConvertI1VectorToInterger(Op, DAG);
5323     if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5324       return DAG.getBitcast(VT, Imm);
5325     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5326     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5327                         DAG.getIntPtrConstant(0, dl));
5328   }
5329
5330   // Vector has one or more non-const elements
5331   uint64_t Immediate = 0;
5332   SmallVector<unsigned, 16> NonConstIdx;
5333   bool IsSplat = true;
5334   bool HasConstElts = false;
5335   int SplatIdx = -1;
5336   for (unsigned idx = 0, e = Op.getNumOperands(); idx < e; ++idx) {
5337     SDValue In = Op.getOperand(idx);
5338     if (In.getOpcode() == ISD::UNDEF)
5339       continue;
5340     if (!isa<ConstantSDNode>(In))
5341       NonConstIdx.push_back(idx);
5342     else {
5343       Immediate |= cast<ConstantSDNode>(In)->getZExtValue() << idx;
5344       HasConstElts = true;
5345     }
5346     if (SplatIdx == -1)
5347       SplatIdx = idx;
5348     else if (In != Op.getOperand(SplatIdx))
5349       IsSplat = false;
5350   }
5351
5352   // for splat use " (select i1 splat_elt, all-ones, all-zeroes)"
5353   if (IsSplat)
5354     return DAG.getNode(ISD::SELECT, dl, VT, Op.getOperand(SplatIdx),
5355                        DAG.getConstant(1, dl, VT),
5356                        DAG.getConstant(0, dl, VT));
5357
5358   // insert elements one by one
5359   SDValue DstVec;
5360   SDValue Imm;
5361   if (Immediate) {
5362     MVT ImmVT = MVT::getIntegerVT(std::max((int)VT.getSizeInBits(), 8));
5363     Imm = DAG.getConstant(Immediate, dl, ImmVT);
5364   }
5365   else if (HasConstElts)
5366     Imm = DAG.getConstant(0, dl, VT);
5367   else
5368     Imm = DAG.getUNDEF(VT);
5369   if (Imm.getValueSizeInBits() == VT.getSizeInBits())
5370     DstVec = DAG.getBitcast(VT, Imm);
5371   else {
5372     SDValue ExtVec = DAG.getBitcast(MVT::v8i1, Imm);
5373     DstVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, ExtVec,
5374                          DAG.getIntPtrConstant(0, dl));
5375   }
5376
5377   for (unsigned i = 0; i < NonConstIdx.size(); ++i) {
5378     unsigned InsertIdx = NonConstIdx[i];
5379     DstVec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
5380                          Op.getOperand(InsertIdx),
5381                          DAG.getIntPtrConstant(InsertIdx, dl));
5382   }
5383   return DstVec;
5384 }
5385
5386 /// \brief Return true if \p N implements a horizontal binop and return the
5387 /// operands for the horizontal binop into V0 and V1.
5388 ///
5389 /// This is a helper function of LowerToHorizontalOp().
5390 /// This function checks that the build_vector \p N in input implements a
5391 /// horizontal operation. Parameter \p Opcode defines the kind of horizontal
5392 /// operation to match.
5393 /// For example, if \p Opcode is equal to ISD::ADD, then this function
5394 /// checks if \p N implements a horizontal arithmetic add; if instead \p Opcode
5395 /// is equal to ISD::SUB, then this function checks if this is a horizontal
5396 /// arithmetic sub.
5397 ///
5398 /// This function only analyzes elements of \p N whose indices are
5399 /// in range [BaseIdx, LastIdx).
5400 static bool isHorizontalBinOp(const BuildVectorSDNode *N, unsigned Opcode,
5401                               SelectionDAG &DAG,
5402                               unsigned BaseIdx, unsigned LastIdx,
5403                               SDValue &V0, SDValue &V1) {
5404   EVT VT = N->getValueType(0);
5405
5406   assert(BaseIdx * 2 <= LastIdx && "Invalid Indices in input!");
5407   assert(VT.isVector() && VT.getVectorNumElements() >= LastIdx &&
5408          "Invalid Vector in input!");
5409
5410   bool IsCommutable = (Opcode == ISD::ADD || Opcode == ISD::FADD);
5411   bool CanFold = true;
5412   unsigned ExpectedVExtractIdx = BaseIdx;
5413   unsigned NumElts = LastIdx - BaseIdx;
5414   V0 = DAG.getUNDEF(VT);
5415   V1 = DAG.getUNDEF(VT);
5416
5417   // Check if N implements a horizontal binop.
5418   for (unsigned i = 0, e = NumElts; i != e && CanFold; ++i) {
5419     SDValue Op = N->getOperand(i + BaseIdx);
5420
5421     // Skip UNDEFs.
5422     if (Op->getOpcode() == ISD::UNDEF) {
5423       // Update the expected vector extract index.
5424       if (i * 2 == NumElts)
5425         ExpectedVExtractIdx = BaseIdx;
5426       ExpectedVExtractIdx += 2;
5427       continue;
5428     }
5429
5430     CanFold = Op->getOpcode() == Opcode && Op->hasOneUse();
5431
5432     if (!CanFold)
5433       break;
5434
5435     SDValue Op0 = Op.getOperand(0);
5436     SDValue Op1 = Op.getOperand(1);
5437
5438     // Try to match the following pattern:
5439     // (BINOP (extract_vector_elt A, I), (extract_vector_elt A, I+1))
5440     CanFold = (Op0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5441         Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
5442         Op0.getOperand(0) == Op1.getOperand(0) &&
5443         isa<ConstantSDNode>(Op0.getOperand(1)) &&
5444         isa<ConstantSDNode>(Op1.getOperand(1)));
5445     if (!CanFold)
5446       break;
5447
5448     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5449     unsigned I1 = cast<ConstantSDNode>(Op1.getOperand(1))->getZExtValue();
5450
5451     if (i * 2 < NumElts) {
5452       if (V0.getOpcode() == ISD::UNDEF) {
5453         V0 = Op0.getOperand(0);
5454         if (V0.getValueType() != VT)
5455           return false;
5456       }
5457     } else {
5458       if (V1.getOpcode() == ISD::UNDEF) {
5459         V1 = Op0.getOperand(0);
5460         if (V1.getValueType() != VT)
5461           return false;
5462       }
5463       if (i * 2 == NumElts)
5464         ExpectedVExtractIdx = BaseIdx;
5465     }
5466
5467     SDValue Expected = (i * 2 < NumElts) ? V0 : V1;
5468     if (I0 == ExpectedVExtractIdx)
5469       CanFold = I1 == I0 + 1 && Op0.getOperand(0) == Expected;
5470     else if (IsCommutable && I1 == ExpectedVExtractIdx) {
5471       // Try to match the following dag sequence:
5472       // (BINOP (extract_vector_elt A, I+1), (extract_vector_elt A, I))
5473       CanFold = I0 == I1 + 1 && Op1.getOperand(0) == Expected;
5474     } else
5475       CanFold = false;
5476
5477     ExpectedVExtractIdx += 2;
5478   }
5479
5480   return CanFold;
5481 }
5482
5483 /// \brief Emit a sequence of two 128-bit horizontal add/sub followed by
5484 /// a concat_vector.
5485 ///
5486 /// This is a helper function of LowerToHorizontalOp().
5487 /// This function expects two 256-bit vectors called V0 and V1.
5488 /// At first, each vector is split into two separate 128-bit vectors.
5489 /// Then, the resulting 128-bit vectors are used to implement two
5490 /// horizontal binary operations.
5491 ///
5492 /// The kind of horizontal binary operation is defined by \p X86Opcode.
5493 ///
5494 /// \p Mode specifies how the 128-bit parts of V0 and V1 are passed in input to
5495 /// the two new horizontal binop.
5496 /// When Mode is set, the first horizontal binop dag node would take as input
5497 /// the lower 128-bit of V0 and the upper 128-bit of V0. The second
5498 /// horizontal binop dag node would take as input the lower 128-bit of V1
5499 /// and the upper 128-bit of V1.
5500 ///   Example:
5501 ///     HADD V0_LO, V0_HI
5502 ///     HADD V1_LO, V1_HI
5503 ///
5504 /// Otherwise, the first horizontal binop dag node takes as input the lower
5505 /// 128-bit of V0 and the lower 128-bit of V1, and the second horizontal binop
5506 /// dag node takes the upper 128-bit of V0 and the upper 128-bit of V1.
5507 ///   Example:
5508 ///     HADD V0_LO, V1_LO
5509 ///     HADD V0_HI, V1_HI
5510 ///
5511 /// If \p isUndefLO is set, then the algorithm propagates UNDEF to the lower
5512 /// 128-bits of the result. If \p isUndefHI is set, then UNDEF is propagated to
5513 /// the upper 128-bits of the result.
5514 static SDValue ExpandHorizontalBinOp(const SDValue &V0, const SDValue &V1,
5515                                      SDLoc DL, SelectionDAG &DAG,
5516                                      unsigned X86Opcode, bool Mode,
5517                                      bool isUndefLO, bool isUndefHI) {
5518   EVT VT = V0.getValueType();
5519   assert(VT.is256BitVector() && VT == V1.getValueType() &&
5520          "Invalid nodes in input!");
5521
5522   unsigned NumElts = VT.getVectorNumElements();
5523   SDValue V0_LO = Extract128BitVector(V0, 0, DAG, DL);
5524   SDValue V0_HI = Extract128BitVector(V0, NumElts/2, DAG, DL);
5525   SDValue V1_LO = Extract128BitVector(V1, 0, DAG, DL);
5526   SDValue V1_HI = Extract128BitVector(V1, NumElts/2, DAG, DL);
5527   EVT NewVT = V0_LO.getValueType();
5528
5529   SDValue LO = DAG.getUNDEF(NewVT);
5530   SDValue HI = DAG.getUNDEF(NewVT);
5531
5532   if (Mode) {
5533     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5534     if (!isUndefLO && V0->getOpcode() != ISD::UNDEF)
5535       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V0_HI);
5536     if (!isUndefHI && V1->getOpcode() != ISD::UNDEF)
5537       HI = DAG.getNode(X86Opcode, DL, NewVT, V1_LO, V1_HI);
5538   } else {
5539     // Don't emit a horizontal binop if the result is expected to be UNDEF.
5540     if (!isUndefLO && (V0_LO->getOpcode() != ISD::UNDEF ||
5541                        V1_LO->getOpcode() != ISD::UNDEF))
5542       LO = DAG.getNode(X86Opcode, DL, NewVT, V0_LO, V1_LO);
5543
5544     if (!isUndefHI && (V0_HI->getOpcode() != ISD::UNDEF ||
5545                        V1_HI->getOpcode() != ISD::UNDEF))
5546       HI = DAG.getNode(X86Opcode, DL, NewVT, V0_HI, V1_HI);
5547   }
5548
5549   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LO, HI);
5550 }
5551
5552 /// Try to fold a build_vector that performs an 'addsub' to an X86ISD::ADDSUB
5553 /// node.
5554 static SDValue LowerToAddSub(const BuildVectorSDNode *BV,
5555                              const X86Subtarget *Subtarget, SelectionDAG &DAG) {
5556   EVT VT = BV->getValueType(0);
5557   if ((!Subtarget->hasSSE3() || (VT != MVT::v4f32 && VT != MVT::v2f64)) &&
5558       (!Subtarget->hasAVX() || (VT != MVT::v8f32 && VT != MVT::v4f64)))
5559     return SDValue();
5560
5561   SDLoc DL(BV);
5562   unsigned NumElts = VT.getVectorNumElements();
5563   SDValue InVec0 = DAG.getUNDEF(VT);
5564   SDValue InVec1 = DAG.getUNDEF(VT);
5565
5566   assert((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v4f32 ||
5567           VT == MVT::v2f64) && "build_vector with an invalid type found!");
5568
5569   // Odd-numbered elements in the input build vector are obtained from
5570   // adding two integer/float elements.
5571   // Even-numbered elements in the input build vector are obtained from
5572   // subtracting two integer/float elements.
5573   unsigned ExpectedOpcode = ISD::FSUB;
5574   unsigned NextExpectedOpcode = ISD::FADD;
5575   bool AddFound = false;
5576   bool SubFound = false;
5577
5578   for (unsigned i = 0, e = NumElts; i != e; ++i) {
5579     SDValue Op = BV->getOperand(i);
5580
5581     // Skip 'undef' values.
5582     unsigned Opcode = Op.getOpcode();
5583     if (Opcode == ISD::UNDEF) {
5584       std::swap(ExpectedOpcode, NextExpectedOpcode);
5585       continue;
5586     }
5587
5588     // Early exit if we found an unexpected opcode.
5589     if (Opcode != ExpectedOpcode)
5590       return SDValue();
5591
5592     SDValue Op0 = Op.getOperand(0);
5593     SDValue Op1 = Op.getOperand(1);
5594
5595     // Try to match the following pattern:
5596     // (BINOP (extract_vector_elt A, i), (extract_vector_elt B, i))
5597     // Early exit if we cannot match that sequence.
5598     if (Op0.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5599         Op1.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
5600         !isa<ConstantSDNode>(Op0.getOperand(1)) ||
5601         !isa<ConstantSDNode>(Op1.getOperand(1)) ||
5602         Op0.getOperand(1) != Op1.getOperand(1))
5603       return SDValue();
5604
5605     unsigned I0 = cast<ConstantSDNode>(Op0.getOperand(1))->getZExtValue();
5606     if (I0 != i)
5607       return SDValue();
5608
5609     // We found a valid add/sub node. Update the information accordingly.
5610     if (i & 1)
5611       AddFound = true;
5612     else
5613       SubFound = true;
5614
5615     // Update InVec0 and InVec1.
5616     if (InVec0.getOpcode() == ISD::UNDEF) {
5617       InVec0 = Op0.getOperand(0);
5618       if (InVec0.getValueType() != VT)
5619         return SDValue();
5620     }
5621     if (InVec1.getOpcode() == ISD::UNDEF) {
5622       InVec1 = Op1.getOperand(0);
5623       if (InVec1.getValueType() != VT)
5624         return SDValue();
5625     }
5626
5627     // Make sure that operands in input to each add/sub node always
5628     // come from a same pair of vectors.
5629     if (InVec0 != Op0.getOperand(0)) {
5630       if (ExpectedOpcode == ISD::FSUB)
5631         return SDValue();
5632
5633       // FADD is commutable. Try to commute the operands
5634       // and then test again.
5635       std::swap(Op0, Op1);
5636       if (InVec0 != Op0.getOperand(0))
5637         return SDValue();
5638     }
5639
5640     if (InVec1 != Op1.getOperand(0))
5641       return SDValue();
5642
5643     // Update the pair of expected opcodes.
5644     std::swap(ExpectedOpcode, NextExpectedOpcode);
5645   }
5646
5647   // Don't try to fold this build_vector into an ADDSUB if the inputs are undef.
5648   if (AddFound && SubFound && InVec0.getOpcode() != ISD::UNDEF &&
5649       InVec1.getOpcode() != ISD::UNDEF)
5650     return DAG.getNode(X86ISD::ADDSUB, DL, VT, InVec0, InVec1);
5651
5652   return SDValue();
5653 }
5654
5655 /// Lower BUILD_VECTOR to a horizontal add/sub operation if possible.
5656 static SDValue LowerToHorizontalOp(const BuildVectorSDNode *BV,
5657                                    const X86Subtarget *Subtarget,
5658                                    SelectionDAG &DAG) {
5659   EVT VT = BV->getValueType(0);
5660   unsigned NumElts = VT.getVectorNumElements();
5661   unsigned NumUndefsLO = 0;
5662   unsigned NumUndefsHI = 0;
5663   unsigned Half = NumElts/2;
5664
5665   // Count the number of UNDEF operands in the build_vector in input.
5666   for (unsigned i = 0, e = Half; i != e; ++i)
5667     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5668       NumUndefsLO++;
5669
5670   for (unsigned i = Half, e = NumElts; i != e; ++i)
5671     if (BV->getOperand(i)->getOpcode() == ISD::UNDEF)
5672       NumUndefsHI++;
5673
5674   // Early exit if this is either a build_vector of all UNDEFs or all the
5675   // operands but one are UNDEF.
5676   if (NumUndefsLO + NumUndefsHI + 1 >= NumElts)
5677     return SDValue();
5678
5679   SDLoc DL(BV);
5680   SDValue InVec0, InVec1;
5681   if ((VT == MVT::v4f32 || VT == MVT::v2f64) && Subtarget->hasSSE3()) {
5682     // Try to match an SSE3 float HADD/HSUB.
5683     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5684       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5685
5686     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5687       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5688   } else if ((VT == MVT::v4i32 || VT == MVT::v8i16) && Subtarget->hasSSSE3()) {
5689     // Try to match an SSSE3 integer HADD/HSUB.
5690     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5691       return DAG.getNode(X86ISD::HADD, DL, VT, InVec0, InVec1);
5692
5693     if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5694       return DAG.getNode(X86ISD::HSUB, DL, VT, InVec0, InVec1);
5695   }
5696
5697   if (!Subtarget->hasAVX())
5698     return SDValue();
5699
5700   if ((VT == MVT::v8f32 || VT == MVT::v4f64)) {
5701     // Try to match an AVX horizontal add/sub of packed single/double
5702     // precision floating point values from 256-bit vectors.
5703     SDValue InVec2, InVec3;
5704     if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, Half, InVec0, InVec1) &&
5705         isHorizontalBinOp(BV, ISD::FADD, DAG, Half, NumElts, InVec2, InVec3) &&
5706         ((InVec0.getOpcode() == ISD::UNDEF ||
5707           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5708         ((InVec1.getOpcode() == ISD::UNDEF ||
5709           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5710       return DAG.getNode(X86ISD::FHADD, DL, VT, InVec0, InVec1);
5711
5712     if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, Half, InVec0, InVec1) &&
5713         isHorizontalBinOp(BV, ISD::FSUB, DAG, Half, NumElts, InVec2, InVec3) &&
5714         ((InVec0.getOpcode() == ISD::UNDEF ||
5715           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5716         ((InVec1.getOpcode() == ISD::UNDEF ||
5717           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5718       return DAG.getNode(X86ISD::FHSUB, DL, VT, InVec0, InVec1);
5719   } else if (VT == MVT::v8i32 || VT == MVT::v16i16) {
5720     // Try to match an AVX2 horizontal add/sub of signed integers.
5721     SDValue InVec2, InVec3;
5722     unsigned X86Opcode;
5723     bool CanFold = true;
5724
5725     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, Half, InVec0, InVec1) &&
5726         isHorizontalBinOp(BV, ISD::ADD, DAG, Half, NumElts, InVec2, InVec3) &&
5727         ((InVec0.getOpcode() == ISD::UNDEF ||
5728           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5729         ((InVec1.getOpcode() == ISD::UNDEF ||
5730           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5731       X86Opcode = X86ISD::HADD;
5732     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, Half, InVec0, InVec1) &&
5733         isHorizontalBinOp(BV, ISD::SUB, DAG, Half, NumElts, InVec2, InVec3) &&
5734         ((InVec0.getOpcode() == ISD::UNDEF ||
5735           InVec2.getOpcode() == ISD::UNDEF) || InVec0 == InVec2) &&
5736         ((InVec1.getOpcode() == ISD::UNDEF ||
5737           InVec3.getOpcode() == ISD::UNDEF) || InVec1 == InVec3))
5738       X86Opcode = X86ISD::HSUB;
5739     else
5740       CanFold = false;
5741
5742     if (CanFold) {
5743       // Fold this build_vector into a single horizontal add/sub.
5744       // Do this only if the target has AVX2.
5745       if (Subtarget->hasAVX2())
5746         return DAG.getNode(X86Opcode, DL, VT, InVec0, InVec1);
5747
5748       // Do not try to expand this build_vector into a pair of horizontal
5749       // add/sub if we can emit a pair of scalar add/sub.
5750       if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5751         return SDValue();
5752
5753       // Convert this build_vector into a pair of horizontal binop followed by
5754       // a concat vector.
5755       bool isUndefLO = NumUndefsLO == Half;
5756       bool isUndefHI = NumUndefsHI == Half;
5757       return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, false,
5758                                    isUndefLO, isUndefHI);
5759     }
5760   }
5761
5762   if ((VT == MVT::v8f32 || VT == MVT::v4f64 || VT == MVT::v8i32 ||
5763        VT == MVT::v16i16) && Subtarget->hasAVX()) {
5764     unsigned X86Opcode;
5765     if (isHorizontalBinOp(BV, ISD::ADD, DAG, 0, NumElts, InVec0, InVec1))
5766       X86Opcode = X86ISD::HADD;
5767     else if (isHorizontalBinOp(BV, ISD::SUB, DAG, 0, NumElts, InVec0, InVec1))
5768       X86Opcode = X86ISD::HSUB;
5769     else if (isHorizontalBinOp(BV, ISD::FADD, DAG, 0, NumElts, InVec0, InVec1))
5770       X86Opcode = X86ISD::FHADD;
5771     else if (isHorizontalBinOp(BV, ISD::FSUB, DAG, 0, NumElts, InVec0, InVec1))
5772       X86Opcode = X86ISD::FHSUB;
5773     else
5774       return SDValue();
5775
5776     // Don't try to expand this build_vector into a pair of horizontal add/sub
5777     // if we can simply emit a pair of scalar add/sub.
5778     if (NumUndefsLO + 1 == Half || NumUndefsHI + 1 == Half)
5779       return SDValue();
5780
5781     // Convert this build_vector into two horizontal add/sub followed by
5782     // a concat vector.
5783     bool isUndefLO = NumUndefsLO == Half;
5784     bool isUndefHI = NumUndefsHI == Half;
5785     return ExpandHorizontalBinOp(InVec0, InVec1, DL, DAG, X86Opcode, true,
5786                                  isUndefLO, isUndefHI);
5787   }
5788
5789   return SDValue();
5790 }
5791
5792 SDValue
5793 X86TargetLowering::LowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG) const {
5794   SDLoc dl(Op);
5795
5796   MVT VT = Op.getSimpleValueType();
5797   MVT ExtVT = VT.getVectorElementType();
5798   unsigned NumElems = Op.getNumOperands();
5799
5800   // Generate vectors for predicate vectors.
5801   if (VT.getScalarType() == MVT::i1 && Subtarget->hasAVX512())
5802     return LowerBUILD_VECTORvXi1(Op, DAG);
5803
5804   // Vectors containing all zeros can be matched by pxor and xorps later
5805   if (ISD::isBuildVectorAllZeros(Op.getNode())) {
5806     // Canonicalize this to <4 x i32> to 1) ensure the zero vectors are CSE'd
5807     // and 2) ensure that i64 scalars are eliminated on x86-32 hosts.
5808     if (VT == MVT::v4i32 || VT == MVT::v8i32 || VT == MVT::v16i32)
5809       return Op;
5810
5811     return getZeroVector(VT, Subtarget, DAG, dl);
5812   }
5813
5814   // Vectors containing all ones can be matched by pcmpeqd on 128-bit width
5815   // vectors or broken into v4i32 operations on 256-bit vectors. AVX2 can use
5816   // vpcmpeqd on 256-bit vectors.
5817   if (Subtarget->hasSSE2() && ISD::isBuildVectorAllOnes(Op.getNode())) {
5818     if (VT == MVT::v4i32 || (VT == MVT::v8i32 && Subtarget->hasInt256()))
5819       return Op;
5820
5821     if (!VT.is512BitVector())
5822       return getOnesVector(VT, Subtarget->hasInt256(), DAG, dl);
5823   }
5824
5825   BuildVectorSDNode *BV = cast<BuildVectorSDNode>(Op.getNode());
5826   if (SDValue AddSub = LowerToAddSub(BV, Subtarget, DAG))
5827     return AddSub;
5828   if (SDValue HorizontalOp = LowerToHorizontalOp(BV, Subtarget, DAG))
5829     return HorizontalOp;
5830   if (SDValue Broadcast = LowerVectorBroadcast(Op, Subtarget, DAG))
5831     return Broadcast;
5832
5833   unsigned EVTBits = ExtVT.getSizeInBits();
5834
5835   unsigned NumZero  = 0;
5836   unsigned NumNonZero = 0;
5837   unsigned NonZeros = 0;
5838   bool IsAllConstants = true;
5839   SmallSet<SDValue, 8> Values;
5840   for (unsigned i = 0; i < NumElems; ++i) {
5841     SDValue Elt = Op.getOperand(i);
5842     if (Elt.getOpcode() == ISD::UNDEF)
5843       continue;
5844     Values.insert(Elt);
5845     if (Elt.getOpcode() != ISD::Constant &&
5846         Elt.getOpcode() != ISD::ConstantFP)
5847       IsAllConstants = false;
5848     if (X86::isZeroNode(Elt))
5849       NumZero++;
5850     else {
5851       NonZeros |= (1 << i);
5852       NumNonZero++;
5853     }
5854   }
5855
5856   // All undef vector. Return an UNDEF.  All zero vectors were handled above.
5857   if (NumNonZero == 0)
5858     return DAG.getUNDEF(VT);
5859
5860   // Special case for single non-zero, non-undef, element.
5861   if (NumNonZero == 1) {
5862     unsigned Idx = countTrailingZeros(NonZeros);
5863     SDValue Item = Op.getOperand(Idx);
5864
5865     // If this is an insertion of an i64 value on x86-32, and if the top bits of
5866     // the value are obviously zero, truncate the value to i32 and do the
5867     // insertion that way.  Only do this if the value is non-constant or if the
5868     // value is a constant being inserted into element 0.  It is cheaper to do
5869     // a constant pool load than it is to do a movd + shuffle.
5870     if (ExtVT == MVT::i64 && !Subtarget->is64Bit() &&
5871         (!IsAllConstants || Idx == 0)) {
5872       if (DAG.MaskedValueIsZero(Item, APInt::getBitsSet(64, 32, 64))) {
5873         // Handle SSE only.
5874         assert(VT == MVT::v2i64 && "Expected an SSE value type!");
5875         EVT VecVT = MVT::v4i32;
5876
5877         // Truncate the value (which may itself be a constant) to i32, and
5878         // convert it to a vector with movd (S2V+shuffle to zero extend).
5879         Item = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Item);
5880         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Item);
5881         return DAG.getBitcast(VT, getShuffleVectorZeroOrUndef(
5882                                       Item, Idx * 2, true, Subtarget, DAG));
5883       }
5884     }
5885
5886     // If we have a constant or non-constant insertion into the low element of
5887     // a vector, we can do this with SCALAR_TO_VECTOR + shuffle of zero into
5888     // the rest of the elements.  This will be matched as movd/movq/movss/movsd
5889     // depending on what the source datatype is.
5890     if (Idx == 0) {
5891       if (NumZero == 0)
5892         return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5893
5894       if (ExtVT == MVT::i32 || ExtVT == MVT::f32 || ExtVT == MVT::f64 ||
5895           (ExtVT == MVT::i64 && Subtarget->is64Bit())) {
5896         if (VT.is512BitVector()) {
5897           SDValue ZeroVec = getZeroVector(VT, Subtarget, DAG, dl);
5898           return DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, ZeroVec,
5899                              Item, DAG.getIntPtrConstant(0, dl));
5900         }
5901         assert((VT.is128BitVector() || VT.is256BitVector()) &&
5902                "Expected an SSE value type!");
5903         Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5904         // Turn it into a MOVL (i.e. movss, movsd, or movd) to a zero vector.
5905         return getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5906       }
5907
5908       // We can't directly insert an i8 or i16 into a vector, so zero extend
5909       // it to i32 first.
5910       if (ExtVT == MVT::i16 || ExtVT == MVT::i8) {
5911         Item = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Item);
5912         if (VT.is256BitVector()) {
5913           if (Subtarget->hasAVX()) {
5914             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v8i32, Item);
5915             Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5916           } else {
5917             // Without AVX, we need to extend to a 128-bit vector and then
5918             // insert into the 256-bit vector.
5919             Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5920             SDValue ZeroVec = getZeroVector(MVT::v8i32, Subtarget, DAG, dl);
5921             Item = Insert128BitVector(ZeroVec, Item, 0, DAG, dl);
5922           }
5923         } else {
5924           assert(VT.is128BitVector() && "Expected an SSE value type!");
5925           Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, Item);
5926           Item = getShuffleVectorZeroOrUndef(Item, 0, true, Subtarget, DAG);
5927         }
5928         return DAG.getBitcast(VT, Item);
5929       }
5930     }
5931
5932     // Is it a vector logical left shift?
5933     if (NumElems == 2 && Idx == 1 &&
5934         X86::isZeroNode(Op.getOperand(0)) &&
5935         !X86::isZeroNode(Op.getOperand(1))) {
5936       unsigned NumBits = VT.getSizeInBits();
5937       return getVShift(true, VT,
5938                        DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
5939                                    VT, Op.getOperand(1)),
5940                        NumBits/2, DAG, *this, dl);
5941     }
5942
5943     if (IsAllConstants) // Otherwise, it's better to do a constpool load.
5944       return SDValue();
5945
5946     // Otherwise, if this is a vector with i32 or f32 elements, and the element
5947     // is a non-constant being inserted into an element other than the low one,
5948     // we can't use a constant pool load.  Instead, use SCALAR_TO_VECTOR (aka
5949     // movd/movss) to move this into the low element, then shuffle it into
5950     // place.
5951     if (EVTBits == 32) {
5952       Item = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Item);
5953       return getShuffleVectorZeroOrUndef(Item, Idx, NumZero > 0, Subtarget, DAG);
5954     }
5955   }
5956
5957   // Splat is obviously ok. Let legalizer expand it to a shuffle.
5958   if (Values.size() == 1) {
5959     if (EVTBits == 32) {
5960       // Instead of a shuffle like this:
5961       // shuffle (scalar_to_vector (load (ptr + 4))), undef, <0, 0, 0, 0>
5962       // Check if it's possible to issue this instead.
5963       // shuffle (vload ptr)), undef, <1, 1, 1, 1>
5964       unsigned Idx = countTrailingZeros(NonZeros);
5965       SDValue Item = Op.getOperand(Idx);
5966       if (Op.getNode()->isOnlyUserOf(Item.getNode()))
5967         return LowerAsSplatVectorLoad(Item, VT, dl, DAG);
5968     }
5969     return SDValue();
5970   }
5971
5972   // A vector full of immediates; various special cases are already
5973   // handled, so this is best done with a single constant-pool load.
5974   if (IsAllConstants)
5975     return SDValue();
5976
5977   // For AVX-length vectors, see if we can use a vector load to get all of the
5978   // elements, otherwise build the individual 128-bit pieces and use
5979   // shuffles to put them in place.
5980   if (VT.is256BitVector() || VT.is512BitVector()) {
5981     SmallVector<SDValue, 64> V(Op->op_begin(), Op->op_begin() + NumElems);
5982
5983     // Check for a build vector of consecutive loads.
5984     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
5985       return LD;
5986
5987     EVT HVT = EVT::getVectorVT(*DAG.getContext(), ExtVT, NumElems/2);
5988
5989     // Build both the lower and upper subvector.
5990     SDValue Lower = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5991                                 makeArrayRef(&V[0], NumElems/2));
5992     SDValue Upper = DAG.getNode(ISD::BUILD_VECTOR, dl, HVT,
5993                                 makeArrayRef(&V[NumElems / 2], NumElems/2));
5994
5995     // Recreate the wider vector with the lower and upper part.
5996     if (VT.is256BitVector())
5997       return Concat128BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5998     return Concat256BitVectors(Lower, Upper, VT, NumElems, DAG, dl);
5999   }
6000
6001   // Let legalizer expand 2-wide build_vectors.
6002   if (EVTBits == 64) {
6003     if (NumNonZero == 1) {
6004       // One half is zero or undef.
6005       unsigned Idx = countTrailingZeros(NonZeros);
6006       SDValue V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT,
6007                                  Op.getOperand(Idx));
6008       return getShuffleVectorZeroOrUndef(V2, Idx, true, Subtarget, DAG);
6009     }
6010     return SDValue();
6011   }
6012
6013   // If element VT is < 32 bits, convert it to inserts into a zero vector.
6014   if (EVTBits == 8 && NumElems == 16)
6015     if (SDValue V = LowerBuildVectorv16i8(Op, NonZeros,NumNonZero,NumZero, DAG,
6016                                         Subtarget, *this))
6017       return V;
6018
6019   if (EVTBits == 16 && NumElems == 8)
6020     if (SDValue V = LowerBuildVectorv8i16(Op, NonZeros,NumNonZero,NumZero, DAG,
6021                                       Subtarget, *this))
6022       return V;
6023
6024   // If element VT is == 32 bits and has 4 elems, try to generate an INSERTPS
6025   if (EVTBits == 32 && NumElems == 4)
6026     if (SDValue V = LowerBuildVectorv4x32(Op, DAG, Subtarget, *this))
6027       return V;
6028
6029   // If element VT is == 32 bits, turn it into a number of shuffles.
6030   SmallVector<SDValue, 8> V(NumElems);
6031   if (NumElems == 4 && NumZero > 0) {
6032     for (unsigned i = 0; i < 4; ++i) {
6033       bool isZero = !(NonZeros & (1 << i));
6034       if (isZero)
6035         V[i] = getZeroVector(VT, Subtarget, DAG, dl);
6036       else
6037         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6038     }
6039
6040     for (unsigned i = 0; i < 2; ++i) {
6041       switch ((NonZeros & (0x3 << i*2)) >> (i*2)) {
6042         default: break;
6043         case 0:
6044           V[i] = V[i*2];  // Must be a zero vector.
6045           break;
6046         case 1:
6047           V[i] = getMOVL(DAG, dl, VT, V[i*2+1], V[i*2]);
6048           break;
6049         case 2:
6050           V[i] = getMOVL(DAG, dl, VT, V[i*2], V[i*2+1]);
6051           break;
6052         case 3:
6053           V[i] = getUnpackl(DAG, dl, VT, V[i*2], V[i*2+1]);
6054           break;
6055       }
6056     }
6057
6058     bool Reverse1 = (NonZeros & 0x3) == 2;
6059     bool Reverse2 = ((NonZeros & (0x3 << 2)) >> 2) == 2;
6060     int MaskVec[] = {
6061       Reverse1 ? 1 : 0,
6062       Reverse1 ? 0 : 1,
6063       static_cast<int>(Reverse2 ? NumElems+1 : NumElems),
6064       static_cast<int>(Reverse2 ? NumElems   : NumElems+1)
6065     };
6066     return DAG.getVectorShuffle(VT, dl, V[0], V[1], &MaskVec[0]);
6067   }
6068
6069   if (Values.size() > 1 && VT.is128BitVector()) {
6070     // Check for a build vector of consecutive loads.
6071     for (unsigned i = 0; i < NumElems; ++i)
6072       V[i] = Op.getOperand(i);
6073
6074     // Check for elements which are consecutive loads.
6075     if (SDValue LD = EltsFromConsecutiveLoads(VT, V, dl, DAG, false))
6076       return LD;
6077
6078     // Check for a build vector from mostly shuffle plus few inserting.
6079     if (SDValue Sh = buildFromShuffleMostly(Op, DAG))
6080       return Sh;
6081
6082     // For SSE 4.1, use insertps to put the high elements into the low element.
6083     if (Subtarget->hasSSE41()) {
6084       SDValue Result;
6085       if (Op.getOperand(0).getOpcode() != ISD::UNDEF)
6086         Result = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(0));
6087       else
6088         Result = DAG.getUNDEF(VT);
6089
6090       for (unsigned i = 1; i < NumElems; ++i) {
6091         if (Op.getOperand(i).getOpcode() == ISD::UNDEF) continue;
6092         Result = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Result,
6093                              Op.getOperand(i), DAG.getIntPtrConstant(i, dl));
6094       }
6095       return Result;
6096     }
6097
6098     // Otherwise, expand into a number of unpckl*, start by extending each of
6099     // our (non-undef) elements to the full vector width with the element in the
6100     // bottom slot of the vector (which generates no code for SSE).
6101     for (unsigned i = 0; i < NumElems; ++i) {
6102       if (Op.getOperand(i).getOpcode() != ISD::UNDEF)
6103         V[i] = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op.getOperand(i));
6104       else
6105         V[i] = DAG.getUNDEF(VT);
6106     }
6107
6108     // Next, we iteratively mix elements, e.g. for v4f32:
6109     //   Step 1: unpcklps 0, 2 ==> X: <?, ?, 2, 0>
6110     //         : unpcklps 1, 3 ==> Y: <?, ?, 3, 1>
6111     //   Step 2: unpcklps X, Y ==>    <3, 2, 1, 0>
6112     unsigned EltStride = NumElems >> 1;
6113     while (EltStride != 0) {
6114       for (unsigned i = 0; i < EltStride; ++i) {
6115         // If V[i+EltStride] is undef and this is the first round of mixing,
6116         // then it is safe to just drop this shuffle: V[i] is already in the
6117         // right place, the one element (since it's the first round) being
6118         // inserted as undef can be dropped.  This isn't safe for successive
6119         // rounds because they will permute elements within both vectors.
6120         if (V[i+EltStride].getOpcode() == ISD::UNDEF &&
6121             EltStride == NumElems/2)
6122           continue;
6123
6124         V[i] = getUnpackl(DAG, dl, VT, V[i], V[i + EltStride]);
6125       }
6126       EltStride >>= 1;
6127     }
6128     return V[0];
6129   }
6130   return SDValue();
6131 }
6132
6133 // LowerAVXCONCAT_VECTORS - 256-bit AVX can use the vinsertf128 instruction
6134 // to create 256-bit vectors from two other 128-bit ones.
6135 static SDValue LowerAVXCONCAT_VECTORS(SDValue Op, SelectionDAG &DAG) {
6136   SDLoc dl(Op);
6137   MVT ResVT = Op.getSimpleValueType();
6138
6139   assert((ResVT.is256BitVector() ||
6140           ResVT.is512BitVector()) && "Value type must be 256-/512-bit wide");
6141
6142   SDValue V1 = Op.getOperand(0);
6143   SDValue V2 = Op.getOperand(1);
6144   unsigned NumElems = ResVT.getVectorNumElements();
6145   if (ResVT.is256BitVector())
6146     return Concat128BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6147
6148   if (Op.getNumOperands() == 4) {
6149     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6150                                 ResVT.getVectorNumElements()/2);
6151     SDValue V3 = Op.getOperand(2);
6152     SDValue V4 = Op.getOperand(3);
6153     return Concat256BitVectors(Concat128BitVectors(V1, V2, HalfVT, NumElems/2, DAG, dl),
6154       Concat128BitVectors(V3, V4, HalfVT, NumElems/2, DAG, dl), ResVT, NumElems, DAG, dl);
6155   }
6156   return Concat256BitVectors(V1, V2, ResVT, NumElems, DAG, dl);
6157 }
6158
6159 static SDValue LowerCONCAT_VECTORSvXi1(SDValue Op,
6160                                        const X86Subtarget *Subtarget,
6161                                        SelectionDAG & DAG) {
6162   SDLoc dl(Op);
6163   MVT ResVT = Op.getSimpleValueType();
6164   unsigned NumOfOperands = Op.getNumOperands();
6165
6166   assert(isPowerOf2_32(NumOfOperands) &&
6167          "Unexpected number of operands in CONCAT_VECTORS");
6168
6169   if (NumOfOperands > 2) {
6170     MVT HalfVT = MVT::getVectorVT(ResVT.getScalarType(),
6171                                   ResVT.getVectorNumElements()/2);
6172     SmallVector<SDValue, 2> Ops;
6173     for (unsigned i = 0; i < NumOfOperands/2; i++)
6174       Ops.push_back(Op.getOperand(i));
6175     SDValue Lo = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6176     Ops.clear();
6177     for (unsigned i = NumOfOperands/2; i < NumOfOperands; i++)
6178       Ops.push_back(Op.getOperand(i));
6179     SDValue Hi = DAG.getNode(ISD::CONCAT_VECTORS, dl, HalfVT, Ops);
6180     return DAG.getNode(ISD::CONCAT_VECTORS, dl, ResVT, Lo, Hi);
6181   }
6182
6183   SDValue V1 = Op.getOperand(0);
6184   SDValue V2 = Op.getOperand(1);
6185   bool IsZeroV1 = ISD::isBuildVectorAllZeros(V1.getNode());
6186   bool IsZeroV2 = ISD::isBuildVectorAllZeros(V2.getNode());
6187
6188   if (IsZeroV1 && IsZeroV2)
6189     return getZeroVector(ResVT, Subtarget, DAG, dl);
6190
6191   SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
6192   SDValue Undef = DAG.getUNDEF(ResVT);
6193   unsigned NumElems = ResVT.getVectorNumElements();
6194   SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
6195
6196   V2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V2, ZeroIdx);
6197   V2 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V2, ShiftBits);
6198   if (IsZeroV1)
6199     return V2;
6200
6201   V1 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, ResVT, Undef, V1, ZeroIdx);
6202   // Zero the upper bits of V1
6203   V1 = DAG.getNode(X86ISD::VSHLI, dl, ResVT, V1, ShiftBits);
6204   V1 = DAG.getNode(X86ISD::VSRLI, dl, ResVT, V1, ShiftBits);
6205   if (IsZeroV2)
6206     return V1;
6207   return DAG.getNode(ISD::OR, dl, ResVT, V1, V2);
6208 }
6209
6210 static SDValue LowerCONCAT_VECTORS(SDValue Op,
6211                                    const X86Subtarget *Subtarget,
6212                                    SelectionDAG &DAG) {
6213   MVT VT = Op.getSimpleValueType();
6214   if (VT.getVectorElementType() == MVT::i1)
6215     return LowerCONCAT_VECTORSvXi1(Op, Subtarget, DAG);
6216
6217   assert((VT.is256BitVector() && Op.getNumOperands() == 2) ||
6218          (VT.is512BitVector() && (Op.getNumOperands() == 2 ||
6219           Op.getNumOperands() == 4)));
6220
6221   // AVX can use the vinsertf128 instruction to create 256-bit vectors
6222   // from two other 128-bit ones.
6223
6224   // 512-bit vector may contain 2 256-bit vectors or 4 128-bit vectors
6225   return LowerAVXCONCAT_VECTORS(Op, DAG);
6226 }
6227
6228
6229 //===----------------------------------------------------------------------===//
6230 // Vector shuffle lowering
6231 //
6232 // This is an experimental code path for lowering vector shuffles on x86. It is
6233 // designed to handle arbitrary vector shuffles and blends, gracefully
6234 // degrading performance as necessary. It works hard to recognize idiomatic
6235 // shuffles and lower them to optimal instruction patterns without leaving
6236 // a framework that allows reasonably efficient handling of all vector shuffle
6237 // patterns.
6238 //===----------------------------------------------------------------------===//
6239
6240 /// \brief Tiny helper function to identify a no-op mask.
6241 ///
6242 /// This is a somewhat boring predicate function. It checks whether the mask
6243 /// array input, which is assumed to be a single-input shuffle mask of the kind
6244 /// used by the X86 shuffle instructions (not a fully general
6245 /// ShuffleVectorSDNode mask) requires any shuffles to occur. Both undef and an
6246 /// in-place shuffle are 'no-op's.
6247 static bool isNoopShuffleMask(ArrayRef<int> Mask) {
6248   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6249     if (Mask[i] != -1 && Mask[i] != i)
6250       return false;
6251   return true;
6252 }
6253
6254 /// \brief Helper function to classify a mask as a single-input mask.
6255 ///
6256 /// This isn't a generic single-input test because in the vector shuffle
6257 /// lowering we canonicalize single inputs to be the first input operand. This
6258 /// means we can more quickly test for a single input by only checking whether
6259 /// an input from the second operand exists. We also assume that the size of
6260 /// mask corresponds to the size of the input vectors which isn't true in the
6261 /// fully general case.
6262 static bool isSingleInputShuffleMask(ArrayRef<int> Mask) {
6263   for (int M : Mask)
6264     if (M >= (int)Mask.size())
6265       return false;
6266   return true;
6267 }
6268
6269 /// \brief Test whether there are elements crossing 128-bit lanes in this
6270 /// shuffle mask.
6271 ///
6272 /// X86 divides up its shuffles into in-lane and cross-lane shuffle operations
6273 /// and we routinely test for these.
6274 static bool is128BitLaneCrossingShuffleMask(MVT VT, ArrayRef<int> Mask) {
6275   int LaneSize = 128 / VT.getScalarSizeInBits();
6276   int Size = Mask.size();
6277   for (int i = 0; i < Size; ++i)
6278     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
6279       return true;
6280   return false;
6281 }
6282
6283 /// \brief Test whether a shuffle mask is equivalent within each 128-bit lane.
6284 ///
6285 /// This checks a shuffle mask to see if it is performing the same
6286 /// 128-bit lane-relative shuffle in each 128-bit lane. This trivially implies
6287 /// that it is also not lane-crossing. It may however involve a blend from the
6288 /// same lane of a second vector.
6289 ///
6290 /// The specific repeated shuffle mask is populated in \p RepeatedMask, as it is
6291 /// non-trivial to compute in the face of undef lanes. The representation is
6292 /// *not* suitable for use with existing 128-bit shuffles as it will contain
6293 /// entries from both V1 and V2 inputs to the wider mask.
6294 static bool
6295 is128BitLaneRepeatedShuffleMask(MVT VT, ArrayRef<int> Mask,
6296                                 SmallVectorImpl<int> &RepeatedMask) {
6297   int LaneSize = 128 / VT.getScalarSizeInBits();
6298   RepeatedMask.resize(LaneSize, -1);
6299   int Size = Mask.size();
6300   for (int i = 0; i < Size; ++i) {
6301     if (Mask[i] < 0)
6302       continue;
6303     if ((Mask[i] % Size) / LaneSize != i / LaneSize)
6304       // This entry crosses lanes, so there is no way to model this shuffle.
6305       return false;
6306
6307     // Ok, handle the in-lane shuffles by detecting if and when they repeat.
6308     if (RepeatedMask[i % LaneSize] == -1)
6309       // This is the first non-undef entry in this slot of a 128-bit lane.
6310       RepeatedMask[i % LaneSize] =
6311           Mask[i] < Size ? Mask[i] % LaneSize : Mask[i] % LaneSize + Size;
6312     else if (RepeatedMask[i % LaneSize] + (i / LaneSize) * LaneSize != Mask[i])
6313       // Found a mismatch with the repeated mask.
6314       return false;
6315   }
6316   return true;
6317 }
6318
6319 /// \brief Checks whether a shuffle mask is equivalent to an explicit list of
6320 /// arguments.
6321 ///
6322 /// This is a fast way to test a shuffle mask against a fixed pattern:
6323 ///
6324 ///   if (isShuffleEquivalent(Mask, 3, 2, {1, 0})) { ... }
6325 ///
6326 /// It returns true if the mask is exactly as wide as the argument list, and
6327 /// each element of the mask is either -1 (signifying undef) or the value given
6328 /// in the argument.
6329 static bool isShuffleEquivalent(SDValue V1, SDValue V2, ArrayRef<int> Mask,
6330                                 ArrayRef<int> ExpectedMask) {
6331   if (Mask.size() != ExpectedMask.size())
6332     return false;
6333
6334   int Size = Mask.size();
6335
6336   // If the values are build vectors, we can look through them to find
6337   // equivalent inputs that make the shuffles equivalent.
6338   auto *BV1 = dyn_cast<BuildVectorSDNode>(V1);
6339   auto *BV2 = dyn_cast<BuildVectorSDNode>(V2);
6340
6341   for (int i = 0; i < Size; ++i)
6342     if (Mask[i] != -1 && Mask[i] != ExpectedMask[i]) {
6343       auto *MaskBV = Mask[i] < Size ? BV1 : BV2;
6344       auto *ExpectedBV = ExpectedMask[i] < Size ? BV1 : BV2;
6345       if (!MaskBV || !ExpectedBV ||
6346           MaskBV->getOperand(Mask[i] % Size) !=
6347               ExpectedBV->getOperand(ExpectedMask[i] % Size))
6348         return false;
6349     }
6350
6351   return true;
6352 }
6353
6354 /// \brief Get a 4-lane 8-bit shuffle immediate for a mask.
6355 ///
6356 /// This helper function produces an 8-bit shuffle immediate corresponding to
6357 /// the ubiquitous shuffle encoding scheme used in x86 instructions for
6358 /// shuffling 4 lanes. It can be used with most of the PSHUF instructions for
6359 /// example.
6360 ///
6361 /// NB: We rely heavily on "undef" masks preserving the input lane.
6362 static SDValue getV4X86ShuffleImm8ForMask(ArrayRef<int> Mask, SDLoc DL,
6363                                           SelectionDAG &DAG) {
6364   assert(Mask.size() == 4 && "Only 4-lane shuffle masks");
6365   assert(Mask[0] >= -1 && Mask[0] < 4 && "Out of bound mask element!");
6366   assert(Mask[1] >= -1 && Mask[1] < 4 && "Out of bound mask element!");
6367   assert(Mask[2] >= -1 && Mask[2] < 4 && "Out of bound mask element!");
6368   assert(Mask[3] >= -1 && Mask[3] < 4 && "Out of bound mask element!");
6369
6370   unsigned Imm = 0;
6371   Imm |= (Mask[0] == -1 ? 0 : Mask[0]) << 0;
6372   Imm |= (Mask[1] == -1 ? 1 : Mask[1]) << 2;
6373   Imm |= (Mask[2] == -1 ? 2 : Mask[2]) << 4;
6374   Imm |= (Mask[3] == -1 ? 3 : Mask[3]) << 6;
6375   return DAG.getConstant(Imm, DL, MVT::i8);
6376 }
6377
6378 /// \brief Try to emit a blend instruction for a shuffle using bit math.
6379 ///
6380 /// This is used as a fallback approach when first class blend instructions are
6381 /// unavailable. Currently it is only suitable for integer vectors, but could
6382 /// be generalized for floating point vectors if desirable.
6383 static SDValue lowerVectorShuffleAsBitBlend(SDLoc DL, MVT VT, SDValue V1,
6384                                             SDValue V2, ArrayRef<int> Mask,
6385                                             SelectionDAG &DAG) {
6386   assert(VT.isInteger() && "Only supports integer vector types!");
6387   MVT EltVT = VT.getScalarType();
6388   int NumEltBits = EltVT.getSizeInBits();
6389   SDValue Zero = DAG.getConstant(0, DL, EltVT);
6390   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6391                                     EltVT);
6392   SmallVector<SDValue, 16> MaskOps;
6393   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6394     if (Mask[i] != -1 && Mask[i] != i && Mask[i] != i + Size)
6395       return SDValue(); // Shuffled input!
6396     MaskOps.push_back(Mask[i] < Size ? AllOnes : Zero);
6397   }
6398
6399   SDValue V1Mask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, MaskOps);
6400   V1 = DAG.getNode(ISD::AND, DL, VT, V1, V1Mask);
6401   // We have to cast V2 around.
6402   MVT MaskVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
6403   V2 = DAG.getBitcast(VT, DAG.getNode(X86ISD::ANDNP, DL, MaskVT,
6404                                       DAG.getBitcast(MaskVT, V1Mask),
6405                                       DAG.getBitcast(MaskVT, V2)));
6406   return DAG.getNode(ISD::OR, DL, VT, V1, V2);
6407 }
6408
6409 /// \brief Try to emit a blend instruction for a shuffle.
6410 ///
6411 /// This doesn't do any checks for the availability of instructions for blending
6412 /// these values. It relies on the availability of the X86ISD::BLENDI pattern to
6413 /// be matched in the backend with the type given. What it does check for is
6414 /// that the shuffle mask is in fact a blend.
6415 static SDValue lowerVectorShuffleAsBlend(SDLoc DL, MVT VT, SDValue V1,
6416                                          SDValue V2, ArrayRef<int> Mask,
6417                                          const X86Subtarget *Subtarget,
6418                                          SelectionDAG &DAG) {
6419   unsigned BlendMask = 0;
6420   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6421     if (Mask[i] >= Size) {
6422       if (Mask[i] != i + Size)
6423         return SDValue(); // Shuffled V2 input!
6424       BlendMask |= 1u << i;
6425       continue;
6426     }
6427     if (Mask[i] >= 0 && Mask[i] != i)
6428       return SDValue(); // Shuffled V1 input!
6429   }
6430   switch (VT.SimpleTy) {
6431   case MVT::v2f64:
6432   case MVT::v4f32:
6433   case MVT::v4f64:
6434   case MVT::v8f32:
6435     return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V2,
6436                        DAG.getConstant(BlendMask, DL, MVT::i8));
6437
6438   case MVT::v4i64:
6439   case MVT::v8i32:
6440     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6441     // FALLTHROUGH
6442   case MVT::v2i64:
6443   case MVT::v4i32:
6444     // If we have AVX2 it is faster to use VPBLENDD when the shuffle fits into
6445     // that instruction.
6446     if (Subtarget->hasAVX2()) {
6447       // Scale the blend by the number of 32-bit dwords per element.
6448       int Scale =  VT.getScalarSizeInBits() / 32;
6449       BlendMask = 0;
6450       for (int i = 0, Size = Mask.size(); i < Size; ++i)
6451         if (Mask[i] >= Size)
6452           for (int j = 0; j < Scale; ++j)
6453             BlendMask |= 1u << (i * Scale + j);
6454
6455       MVT BlendVT = VT.getSizeInBits() > 128 ? MVT::v8i32 : MVT::v4i32;
6456       V1 = DAG.getBitcast(BlendVT, V1);
6457       V2 = DAG.getBitcast(BlendVT, V2);
6458       return DAG.getBitcast(
6459           VT, DAG.getNode(X86ISD::BLENDI, DL, BlendVT, V1, V2,
6460                           DAG.getConstant(BlendMask, DL, MVT::i8)));
6461     }
6462     // FALLTHROUGH
6463   case MVT::v8i16: {
6464     // For integer shuffles we need to expand the mask and cast the inputs to
6465     // v8i16s prior to blending.
6466     int Scale = 8 / VT.getVectorNumElements();
6467     BlendMask = 0;
6468     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6469       if (Mask[i] >= Size)
6470         for (int j = 0; j < Scale; ++j)
6471           BlendMask |= 1u << (i * Scale + j);
6472
6473     V1 = DAG.getBitcast(MVT::v8i16, V1);
6474     V2 = DAG.getBitcast(MVT::v8i16, V2);
6475     return DAG.getBitcast(VT,
6476                           DAG.getNode(X86ISD::BLENDI, DL, MVT::v8i16, V1, V2,
6477                                       DAG.getConstant(BlendMask, DL, MVT::i8)));
6478   }
6479
6480   case MVT::v16i16: {
6481     assert(Subtarget->hasAVX2() && "256-bit integer blends require AVX2!");
6482     SmallVector<int, 8> RepeatedMask;
6483     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
6484       // We can lower these with PBLENDW which is mirrored across 128-bit lanes.
6485       assert(RepeatedMask.size() == 8 && "Repeated mask size doesn't match!");
6486       BlendMask = 0;
6487       for (int i = 0; i < 8; ++i)
6488         if (RepeatedMask[i] >= 16)
6489           BlendMask |= 1u << i;
6490       return DAG.getNode(X86ISD::BLENDI, DL, MVT::v16i16, V1, V2,
6491                          DAG.getConstant(BlendMask, DL, MVT::i8));
6492     }
6493   }
6494     // FALLTHROUGH
6495   case MVT::v16i8:
6496   case MVT::v32i8: {
6497     assert((VT.getSizeInBits() == 128 || Subtarget->hasAVX2()) &&
6498            "256-bit byte-blends require AVX2 support!");
6499
6500     // Scale the blend by the number of bytes per element.
6501     int Scale = VT.getScalarSizeInBits() / 8;
6502
6503     // This form of blend is always done on bytes. Compute the byte vector
6504     // type.
6505     MVT BlendVT = MVT::getVectorVT(MVT::i8, VT.getSizeInBits() / 8);
6506
6507     // Compute the VSELECT mask. Note that VSELECT is really confusing in the
6508     // mix of LLVM's code generator and the x86 backend. We tell the code
6509     // generator that boolean values in the elements of an x86 vector register
6510     // are -1 for true and 0 for false. We then use the LLVM semantics of 'true'
6511     // mapping a select to operand #1, and 'false' mapping to operand #2. The
6512     // reality in x86 is that vector masks (pre-AVX-512) use only the high bit
6513     // of the element (the remaining are ignored) and 0 in that high bit would
6514     // mean operand #1 while 1 in the high bit would mean operand #2. So while
6515     // the LLVM model for boolean values in vector elements gets the relevant
6516     // bit set, it is set backwards and over constrained relative to x86's
6517     // actual model.
6518     SmallVector<SDValue, 32> VSELECTMask;
6519     for (int i = 0, Size = Mask.size(); i < Size; ++i)
6520       for (int j = 0; j < Scale; ++j)
6521         VSELECTMask.push_back(
6522             Mask[i] < 0 ? DAG.getUNDEF(MVT::i8)
6523                         : DAG.getConstant(Mask[i] < Size ? -1 : 0, DL,
6524                                           MVT::i8));
6525
6526     V1 = DAG.getBitcast(BlendVT, V1);
6527     V2 = DAG.getBitcast(BlendVT, V2);
6528     return DAG.getBitcast(VT, DAG.getNode(ISD::VSELECT, DL, BlendVT,
6529                                           DAG.getNode(ISD::BUILD_VECTOR, DL,
6530                                                       BlendVT, VSELECTMask),
6531                                           V1, V2));
6532   }
6533
6534   default:
6535     llvm_unreachable("Not a supported integer vector type!");
6536   }
6537 }
6538
6539 /// \brief Try to lower as a blend of elements from two inputs followed by
6540 /// a single-input permutation.
6541 ///
6542 /// This matches the pattern where we can blend elements from two inputs and
6543 /// then reduce the shuffle to a single-input permutation.
6544 static SDValue lowerVectorShuffleAsBlendAndPermute(SDLoc DL, MVT VT, SDValue V1,
6545                                                    SDValue V2,
6546                                                    ArrayRef<int> Mask,
6547                                                    SelectionDAG &DAG) {
6548   // We build up the blend mask while checking whether a blend is a viable way
6549   // to reduce the shuffle.
6550   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6551   SmallVector<int, 32> PermuteMask(Mask.size(), -1);
6552
6553   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6554     if (Mask[i] < 0)
6555       continue;
6556
6557     assert(Mask[i] < Size * 2 && "Shuffle input is out of bounds.");
6558
6559     if (BlendMask[Mask[i] % Size] == -1)
6560       BlendMask[Mask[i] % Size] = Mask[i];
6561     else if (BlendMask[Mask[i] % Size] != Mask[i])
6562       return SDValue(); // Can't blend in the needed input!
6563
6564     PermuteMask[i] = Mask[i] % Size;
6565   }
6566
6567   SDValue V = DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6568   return DAG.getVectorShuffle(VT, DL, V, DAG.getUNDEF(VT), PermuteMask);
6569 }
6570
6571 /// \brief Generic routine to decompose a shuffle and blend into indepndent
6572 /// blends and permutes.
6573 ///
6574 /// This matches the extremely common pattern for handling combined
6575 /// shuffle+blend operations on newer X86 ISAs where we have very fast blend
6576 /// operations. It will try to pick the best arrangement of shuffles and
6577 /// blends.
6578 static SDValue lowerVectorShuffleAsDecomposedShuffleBlend(SDLoc DL, MVT VT,
6579                                                           SDValue V1,
6580                                                           SDValue V2,
6581                                                           ArrayRef<int> Mask,
6582                                                           SelectionDAG &DAG) {
6583   // Shuffle the input elements into the desired positions in V1 and V2 and
6584   // blend them together.
6585   SmallVector<int, 32> V1Mask(Mask.size(), -1);
6586   SmallVector<int, 32> V2Mask(Mask.size(), -1);
6587   SmallVector<int, 32> BlendMask(Mask.size(), -1);
6588   for (int i = 0, Size = Mask.size(); i < Size; ++i)
6589     if (Mask[i] >= 0 && Mask[i] < Size) {
6590       V1Mask[i] = Mask[i];
6591       BlendMask[i] = i;
6592     } else if (Mask[i] >= Size) {
6593       V2Mask[i] = Mask[i] - Size;
6594       BlendMask[i] = i + Size;
6595     }
6596
6597   // Try to lower with the simpler initial blend strategy unless one of the
6598   // input shuffles would be a no-op. We prefer to shuffle inputs as the
6599   // shuffle may be able to fold with a load or other benefit. However, when
6600   // we'll have to do 2x as many shuffles in order to achieve this, blending
6601   // first is a better strategy.
6602   if (!isNoopShuffleMask(V1Mask) && !isNoopShuffleMask(V2Mask))
6603     if (SDValue BlendPerm =
6604             lowerVectorShuffleAsBlendAndPermute(DL, VT, V1, V2, Mask, DAG))
6605       return BlendPerm;
6606
6607   V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
6608   V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
6609   return DAG.getVectorShuffle(VT, DL, V1, V2, BlendMask);
6610 }
6611
6612 /// \brief Try to lower a vector shuffle as a byte rotation.
6613 ///
6614 /// SSSE3 has a generic PALIGNR instruction in x86 that will do an arbitrary
6615 /// byte-rotation of the concatenation of two vectors; pre-SSSE3 can use
6616 /// a PSRLDQ/PSLLDQ/POR pattern to get a similar effect. This routine will
6617 /// try to generically lower a vector shuffle through such an pattern. It
6618 /// does not check for the profitability of lowering either as PALIGNR or
6619 /// PSRLDQ/PSLLDQ/POR, only whether the mask is valid to lower in that form.
6620 /// This matches shuffle vectors that look like:
6621 ///
6622 ///   v8i16 [11, 12, 13, 14, 15, 0, 1, 2]
6623 ///
6624 /// Essentially it concatenates V1 and V2, shifts right by some number of
6625 /// elements, and takes the low elements as the result. Note that while this is
6626 /// specified as a *right shift* because x86 is little-endian, it is a *left
6627 /// rotate* of the vector lanes.
6628 static SDValue lowerVectorShuffleAsByteRotate(SDLoc DL, MVT VT, SDValue V1,
6629                                               SDValue V2,
6630                                               ArrayRef<int> Mask,
6631                                               const X86Subtarget *Subtarget,
6632                                               SelectionDAG &DAG) {
6633   assert(!isNoopShuffleMask(Mask) && "We shouldn't lower no-op shuffles!");
6634
6635   int NumElts = Mask.size();
6636   int NumLanes = VT.getSizeInBits() / 128;
6637   int NumLaneElts = NumElts / NumLanes;
6638
6639   // We need to detect various ways of spelling a rotation:
6640   //   [11, 12, 13, 14, 15,  0,  1,  2]
6641   //   [-1, 12, 13, 14, -1, -1,  1, -1]
6642   //   [-1, -1, -1, -1, -1, -1,  1,  2]
6643   //   [ 3,  4,  5,  6,  7,  8,  9, 10]
6644   //   [-1,  4,  5,  6, -1, -1,  9, -1]
6645   //   [-1,  4,  5,  6, -1, -1, -1, -1]
6646   int Rotation = 0;
6647   SDValue Lo, Hi;
6648   for (int l = 0; l < NumElts; l += NumLaneElts) {
6649     for (int i = 0; i < NumLaneElts; ++i) {
6650       if (Mask[l + i] == -1)
6651         continue;
6652       assert(Mask[l + i] >= 0 && "Only -1 is a valid negative mask element!");
6653
6654       // Get the mod-Size index and lane correct it.
6655       int LaneIdx = (Mask[l + i] % NumElts) - l;
6656       // Make sure it was in this lane.
6657       if (LaneIdx < 0 || LaneIdx >= NumLaneElts)
6658         return SDValue();
6659
6660       // Determine where a rotated vector would have started.
6661       int StartIdx = i - LaneIdx;
6662       if (StartIdx == 0)
6663         // The identity rotation isn't interesting, stop.
6664         return SDValue();
6665
6666       // If we found the tail of a vector the rotation must be the missing
6667       // front. If we found the head of a vector, it must be how much of the
6668       // head.
6669       int CandidateRotation = StartIdx < 0 ? -StartIdx : NumLaneElts - StartIdx;
6670
6671       if (Rotation == 0)
6672         Rotation = CandidateRotation;
6673       else if (Rotation != CandidateRotation)
6674         // The rotations don't match, so we can't match this mask.
6675         return SDValue();
6676
6677       // Compute which value this mask is pointing at.
6678       SDValue MaskV = Mask[l + i] < NumElts ? V1 : V2;
6679
6680       // Compute which of the two target values this index should be assigned
6681       // to. This reflects whether the high elements are remaining or the low
6682       // elements are remaining.
6683       SDValue &TargetV = StartIdx < 0 ? Hi : Lo;
6684
6685       // Either set up this value if we've not encountered it before, or check
6686       // that it remains consistent.
6687       if (!TargetV)
6688         TargetV = MaskV;
6689       else if (TargetV != MaskV)
6690         // This may be a rotation, but it pulls from the inputs in some
6691         // unsupported interleaving.
6692         return SDValue();
6693     }
6694   }
6695
6696   // Check that we successfully analyzed the mask, and normalize the results.
6697   assert(Rotation != 0 && "Failed to locate a viable rotation!");
6698   assert((Lo || Hi) && "Failed to find a rotated input vector!");
6699   if (!Lo)
6700     Lo = Hi;
6701   else if (!Hi)
6702     Hi = Lo;
6703
6704   // The actual rotate instruction rotates bytes, so we need to scale the
6705   // rotation based on how many bytes are in the vector lane.
6706   int Scale = 16 / NumLaneElts;
6707
6708   // SSSE3 targets can use the palignr instruction.
6709   if (Subtarget->hasSSSE3()) {
6710     // Cast the inputs to i8 vector of correct length to match PALIGNR.
6711     MVT AlignVT = MVT::getVectorVT(MVT::i8, 16 * NumLanes);
6712     Lo = DAG.getBitcast(AlignVT, Lo);
6713     Hi = DAG.getBitcast(AlignVT, Hi);
6714
6715     return DAG.getBitcast(
6716         VT, DAG.getNode(X86ISD::PALIGNR, DL, AlignVT, Hi, Lo,
6717                         DAG.getConstant(Rotation * Scale, DL, MVT::i8)));
6718   }
6719
6720   assert(VT.getSizeInBits() == 128 &&
6721          "Rotate-based lowering only supports 128-bit lowering!");
6722   assert(Mask.size() <= 16 &&
6723          "Can shuffle at most 16 bytes in a 128-bit vector!");
6724
6725   // Default SSE2 implementation
6726   int LoByteShift = 16 - Rotation * Scale;
6727   int HiByteShift = Rotation * Scale;
6728
6729   // Cast the inputs to v2i64 to match PSLLDQ/PSRLDQ.
6730   Lo = DAG.getBitcast(MVT::v2i64, Lo);
6731   Hi = DAG.getBitcast(MVT::v2i64, Hi);
6732
6733   SDValue LoShift = DAG.getNode(X86ISD::VSHLDQ, DL, MVT::v2i64, Lo,
6734                                 DAG.getConstant(LoByteShift, DL, MVT::i8));
6735   SDValue HiShift = DAG.getNode(X86ISD::VSRLDQ, DL, MVT::v2i64, Hi,
6736                                 DAG.getConstant(HiByteShift, DL, MVT::i8));
6737   return DAG.getBitcast(VT,
6738                         DAG.getNode(ISD::OR, DL, MVT::v2i64, LoShift, HiShift));
6739 }
6740
6741 /// \brief Compute whether each element of a shuffle is zeroable.
6742 ///
6743 /// A "zeroable" vector shuffle element is one which can be lowered to zero.
6744 /// Either it is an undef element in the shuffle mask, the element of the input
6745 /// referenced is undef, or the element of the input referenced is known to be
6746 /// zero. Many x86 shuffles can zero lanes cheaply and we often want to handle
6747 /// as many lanes with this technique as possible to simplify the remaining
6748 /// shuffle.
6749 static SmallBitVector computeZeroableShuffleElements(ArrayRef<int> Mask,
6750                                                      SDValue V1, SDValue V2) {
6751   SmallBitVector Zeroable(Mask.size(), false);
6752
6753   while (V1.getOpcode() == ISD::BITCAST)
6754     V1 = V1->getOperand(0);
6755   while (V2.getOpcode() == ISD::BITCAST)
6756     V2 = V2->getOperand(0);
6757
6758   bool V1IsZero = ISD::isBuildVectorAllZeros(V1.getNode());
6759   bool V2IsZero = ISD::isBuildVectorAllZeros(V2.getNode());
6760
6761   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6762     int M = Mask[i];
6763     // Handle the easy cases.
6764     if (M < 0 || (M >= 0 && M < Size && V1IsZero) || (M >= Size && V2IsZero)) {
6765       Zeroable[i] = true;
6766       continue;
6767     }
6768
6769     // If this is an index into a build_vector node (which has the same number
6770     // of elements), dig out the input value and use it.
6771     SDValue V = M < Size ? V1 : V2;
6772     if (V.getOpcode() != ISD::BUILD_VECTOR || Size != (int)V.getNumOperands())
6773       continue;
6774
6775     SDValue Input = V.getOperand(M % Size);
6776     // The UNDEF opcode check really should be dead code here, but not quite
6777     // worth asserting on (it isn't invalid, just unexpected).
6778     if (Input.getOpcode() == ISD::UNDEF || X86::isZeroNode(Input))
6779       Zeroable[i] = true;
6780   }
6781
6782   return Zeroable;
6783 }
6784
6785 /// \brief Try to emit a bitmask instruction for a shuffle.
6786 ///
6787 /// This handles cases where we can model a blend exactly as a bitmask due to
6788 /// one of the inputs being zeroable.
6789 static SDValue lowerVectorShuffleAsBitMask(SDLoc DL, MVT VT, SDValue V1,
6790                                            SDValue V2, ArrayRef<int> Mask,
6791                                            SelectionDAG &DAG) {
6792   MVT EltVT = VT.getScalarType();
6793   int NumEltBits = EltVT.getSizeInBits();
6794   MVT IntEltVT = MVT::getIntegerVT(NumEltBits);
6795   SDValue Zero = DAG.getConstant(0, DL, IntEltVT);
6796   SDValue AllOnes = DAG.getConstant(APInt::getAllOnesValue(NumEltBits), DL,
6797                                     IntEltVT);
6798   if (EltVT.isFloatingPoint()) {
6799     Zero = DAG.getBitcast(EltVT, Zero);
6800     AllOnes = DAG.getBitcast(EltVT, AllOnes);
6801   }
6802   SmallVector<SDValue, 16> VMaskOps(Mask.size(), Zero);
6803   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6804   SDValue V;
6805   for (int i = 0, Size = Mask.size(); i < Size; ++i) {
6806     if (Zeroable[i])
6807       continue;
6808     if (Mask[i] % Size != i)
6809       return SDValue(); // Not a blend.
6810     if (!V)
6811       V = Mask[i] < Size ? V1 : V2;
6812     else if (V != (Mask[i] < Size ? V1 : V2))
6813       return SDValue(); // Can only let one input through the mask.
6814
6815     VMaskOps[i] = AllOnes;
6816   }
6817   if (!V)
6818     return SDValue(); // No non-zeroable elements!
6819
6820   SDValue VMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, VMaskOps);
6821   V = DAG.getNode(VT.isFloatingPoint()
6822                   ? (unsigned) X86ISD::FAND : (unsigned) ISD::AND,
6823                   DL, VT, V, VMask);
6824   return V;
6825 }
6826
6827 /// \brief Try to lower a vector shuffle as a bit shift (shifts in zeros).
6828 ///
6829 /// Attempts to match a shuffle mask against the PSLL(W/D/Q/DQ) and
6830 /// PSRL(W/D/Q/DQ) SSE2 and AVX2 logical bit-shift instructions. The function
6831 /// matches elements from one of the input vectors shuffled to the left or
6832 /// right with zeroable elements 'shifted in'. It handles both the strictly
6833 /// bit-wise element shifts and the byte shift across an entire 128-bit double
6834 /// quad word lane.
6835 ///
6836 /// PSHL : (little-endian) left bit shift.
6837 /// [ zz, 0, zz,  2 ]
6838 /// [ -1, 4, zz, -1 ]
6839 /// PSRL : (little-endian) right bit shift.
6840 /// [  1, zz,  3, zz]
6841 /// [ -1, -1,  7, zz]
6842 /// PSLLDQ : (little-endian) left byte shift
6843 /// [ zz,  0,  1,  2,  3,  4,  5,  6]
6844 /// [ zz, zz, -1, -1,  2,  3,  4, -1]
6845 /// [ zz, zz, zz, zz, zz, zz, -1,  1]
6846 /// PSRLDQ : (little-endian) right byte shift
6847 /// [  5, 6,  7, zz, zz, zz, zz, zz]
6848 /// [ -1, 5,  6,  7, zz, zz, zz, zz]
6849 /// [  1, 2, -1, -1, -1, -1, zz, zz]
6850 static SDValue lowerVectorShuffleAsShift(SDLoc DL, MVT VT, SDValue V1,
6851                                          SDValue V2, ArrayRef<int> Mask,
6852                                          SelectionDAG &DAG) {
6853   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
6854
6855   int Size = Mask.size();
6856   assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
6857
6858   auto CheckZeros = [&](int Shift, int Scale, bool Left) {
6859     for (int i = 0; i < Size; i += Scale)
6860       for (int j = 0; j < Shift; ++j)
6861         if (!Zeroable[i + j + (Left ? 0 : (Scale - Shift))])
6862           return false;
6863
6864     return true;
6865   };
6866
6867   auto MatchShift = [&](int Shift, int Scale, bool Left, SDValue V) {
6868     for (int i = 0; i != Size; i += Scale) {
6869       unsigned Pos = Left ? i + Shift : i;
6870       unsigned Low = Left ? i : i + Shift;
6871       unsigned Len = Scale - Shift;
6872       if (!isSequentialOrUndefInRange(Mask, Pos, Len,
6873                                       Low + (V == V1 ? 0 : Size)))
6874         return SDValue();
6875     }
6876
6877     int ShiftEltBits = VT.getScalarSizeInBits() * Scale;
6878     bool ByteShift = ShiftEltBits > 64;
6879     unsigned OpCode = Left ? (ByteShift ? X86ISD::VSHLDQ : X86ISD::VSHLI)
6880                            : (ByteShift ? X86ISD::VSRLDQ : X86ISD::VSRLI);
6881     int ShiftAmt = Shift * VT.getScalarSizeInBits() / (ByteShift ? 8 : 1);
6882
6883     // Normalize the scale for byte shifts to still produce an i64 element
6884     // type.
6885     Scale = ByteShift ? Scale / 2 : Scale;
6886
6887     // We need to round trip through the appropriate type for the shift.
6888     MVT ShiftSVT = MVT::getIntegerVT(VT.getScalarSizeInBits() * Scale);
6889     MVT ShiftVT = MVT::getVectorVT(ShiftSVT, Size / Scale);
6890     assert(DAG.getTargetLoweringInfo().isTypeLegal(ShiftVT) &&
6891            "Illegal integer vector type");
6892     V = DAG.getBitcast(ShiftVT, V);
6893
6894     V = DAG.getNode(OpCode, DL, ShiftVT, V,
6895                     DAG.getConstant(ShiftAmt, DL, MVT::i8));
6896     return DAG.getBitcast(VT, V);
6897   };
6898
6899   // SSE/AVX supports logical shifts up to 64-bit integers - so we can just
6900   // keep doubling the size of the integer elements up to that. We can
6901   // then shift the elements of the integer vector by whole multiples of
6902   // their width within the elements of the larger integer vector. Test each
6903   // multiple to see if we can find a match with the moved element indices
6904   // and that the shifted in elements are all zeroable.
6905   for (int Scale = 2; Scale * VT.getScalarSizeInBits() <= 128; Scale *= 2)
6906     for (int Shift = 1; Shift != Scale; ++Shift)
6907       for (bool Left : {true, false})
6908         if (CheckZeros(Shift, Scale, Left))
6909           for (SDValue V : {V1, V2})
6910             if (SDValue Match = MatchShift(Shift, Scale, Left, V))
6911               return Match;
6912
6913   // no match
6914   return SDValue();
6915 }
6916
6917 /// \brief Lower a vector shuffle as a zero or any extension.
6918 ///
6919 /// Given a specific number of elements, element bit width, and extension
6920 /// stride, produce either a zero or any extension based on the available
6921 /// features of the subtarget.
6922 static SDValue lowerVectorShuffleAsSpecificZeroOrAnyExtend(
6923     SDLoc DL, MVT VT, int Scale, bool AnyExt, SDValue InputV,
6924     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
6925   assert(Scale > 1 && "Need a scale to extend.");
6926   int NumElements = VT.getVectorNumElements();
6927   int EltBits = VT.getScalarSizeInBits();
6928   assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
6929          "Only 8, 16, and 32 bit elements can be extended.");
6930   assert(Scale * EltBits <= 64 && "Cannot zero extend past 64 bits.");
6931
6932   // Found a valid zext mask! Try various lowering strategies based on the
6933   // input type and available ISA extensions.
6934   if (Subtarget->hasSSE41()) {
6935     MVT ExtVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits * Scale),
6936                                  NumElements / Scale);
6937     return DAG.getBitcast(VT, DAG.getNode(X86ISD::VZEXT, DL, ExtVT, InputV));
6938   }
6939
6940   // For any extends we can cheat for larger element sizes and use shuffle
6941   // instructions that can fold with a load and/or copy.
6942   if (AnyExt && EltBits == 32) {
6943     int PSHUFDMask[4] = {0, -1, 1, -1};
6944     return DAG.getBitcast(
6945         VT, DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6946                         DAG.getBitcast(MVT::v4i32, InputV),
6947                         getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
6948   }
6949   if (AnyExt && EltBits == 16 && Scale > 2) {
6950     int PSHUFDMask[4] = {0, -1, 0, -1};
6951     InputV = DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32,
6952                          DAG.getBitcast(MVT::v4i32, InputV),
6953                          getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG));
6954     int PSHUFHWMask[4] = {1, -1, -1, -1};
6955     return DAG.getBitcast(
6956         VT, DAG.getNode(X86ISD::PSHUFHW, DL, MVT::v8i16,
6957                         DAG.getBitcast(MVT::v8i16, InputV),
6958                         getV4X86ShuffleImm8ForMask(PSHUFHWMask, DL, DAG)));
6959   }
6960
6961   // If this would require more than 2 unpack instructions to expand, use
6962   // pshufb when available. We can only use more than 2 unpack instructions
6963   // when zero extending i8 elements which also makes it easier to use pshufb.
6964   if (Scale > 4 && EltBits == 8 && Subtarget->hasSSSE3()) {
6965     assert(NumElements == 16 && "Unexpected byte vector width!");
6966     SDValue PSHUFBMask[16];
6967     for (int i = 0; i < 16; ++i)
6968       PSHUFBMask[i] =
6969           DAG.getConstant((i % Scale == 0) ? i / Scale : 0x80, DL, MVT::i8);
6970     InputV = DAG.getBitcast(MVT::v16i8, InputV);
6971     return DAG.getBitcast(VT,
6972                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8, InputV,
6973                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
6974                                                   MVT::v16i8, PSHUFBMask)));
6975   }
6976
6977   // Otherwise emit a sequence of unpacks.
6978   do {
6979     MVT InputVT = MVT::getVectorVT(MVT::getIntegerVT(EltBits), NumElements);
6980     SDValue Ext = AnyExt ? DAG.getUNDEF(InputVT)
6981                          : getZeroVector(InputVT, Subtarget, DAG, DL);
6982     InputV = DAG.getBitcast(InputVT, InputV);
6983     InputV = DAG.getNode(X86ISD::UNPCKL, DL, InputVT, InputV, Ext);
6984     Scale /= 2;
6985     EltBits *= 2;
6986     NumElements /= 2;
6987   } while (Scale > 1);
6988   return DAG.getBitcast(VT, InputV);
6989 }
6990
6991 /// \brief Try to lower a vector shuffle as a zero extension on any microarch.
6992 ///
6993 /// This routine will try to do everything in its power to cleverly lower
6994 /// a shuffle which happens to match the pattern of a zero extend. It doesn't
6995 /// check for the profitability of this lowering,  it tries to aggressively
6996 /// match this pattern. It will use all of the micro-architectural details it
6997 /// can to emit an efficient lowering. It handles both blends with all-zero
6998 /// inputs to explicitly zero-extend and undef-lanes (sometimes undef due to
6999 /// masking out later).
7000 ///
7001 /// The reason we have dedicated lowering for zext-style shuffles is that they
7002 /// are both incredibly common and often quite performance sensitive.
7003 static SDValue lowerVectorShuffleAsZeroOrAnyExtend(
7004     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7005     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7006   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7007
7008   int Bits = VT.getSizeInBits();
7009   int NumElements = VT.getVectorNumElements();
7010   assert(VT.getScalarSizeInBits() <= 32 &&
7011          "Exceeds 32-bit integer zero extension limit");
7012   assert((int)Mask.size() == NumElements && "Unexpected shuffle mask size");
7013
7014   // Define a helper function to check a particular ext-scale and lower to it if
7015   // valid.
7016   auto Lower = [&](int Scale) -> SDValue {
7017     SDValue InputV;
7018     bool AnyExt = true;
7019     for (int i = 0; i < NumElements; ++i) {
7020       if (Mask[i] == -1)
7021         continue; // Valid anywhere but doesn't tell us anything.
7022       if (i % Scale != 0) {
7023         // Each of the extended elements need to be zeroable.
7024         if (!Zeroable[i])
7025           return SDValue();
7026
7027         // We no longer are in the anyext case.
7028         AnyExt = false;
7029         continue;
7030       }
7031
7032       // Each of the base elements needs to be consecutive indices into the
7033       // same input vector.
7034       SDValue V = Mask[i] < NumElements ? V1 : V2;
7035       if (!InputV)
7036         InputV = V;
7037       else if (InputV != V)
7038         return SDValue(); // Flip-flopping inputs.
7039
7040       if (Mask[i] % NumElements != i / Scale)
7041         return SDValue(); // Non-consecutive strided elements.
7042     }
7043
7044     // If we fail to find an input, we have a zero-shuffle which should always
7045     // have already been handled.
7046     // FIXME: Maybe handle this here in case during blending we end up with one?
7047     if (!InputV)
7048       return SDValue();
7049
7050     return lowerVectorShuffleAsSpecificZeroOrAnyExtend(
7051         DL, VT, Scale, AnyExt, InputV, Subtarget, DAG);
7052   };
7053
7054   // The widest scale possible for extending is to a 64-bit integer.
7055   assert(Bits % 64 == 0 &&
7056          "The number of bits in a vector must be divisible by 64 on x86!");
7057   int NumExtElements = Bits / 64;
7058
7059   // Each iteration, try extending the elements half as much, but into twice as
7060   // many elements.
7061   for (; NumExtElements < NumElements; NumExtElements *= 2) {
7062     assert(NumElements % NumExtElements == 0 &&
7063            "The input vector size must be divisible by the extended size.");
7064     if (SDValue V = Lower(NumElements / NumExtElements))
7065       return V;
7066   }
7067
7068   // General extends failed, but 128-bit vectors may be able to use MOVQ.
7069   if (Bits != 128)
7070     return SDValue();
7071
7072   // Returns one of the source operands if the shuffle can be reduced to a
7073   // MOVQ, copying the lower 64-bits and zero-extending to the upper 64-bits.
7074   auto CanZExtLowHalf = [&]() {
7075     for (int i = NumElements / 2; i != NumElements; ++i)
7076       if (!Zeroable[i])
7077         return SDValue();
7078     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, 0))
7079       return V1;
7080     if (isSequentialOrUndefInRange(Mask, 0, NumElements / 2, NumElements))
7081       return V2;
7082     return SDValue();
7083   };
7084
7085   if (SDValue V = CanZExtLowHalf()) {
7086     V = DAG.getBitcast(MVT::v2i64, V);
7087     V = DAG.getNode(X86ISD::VZEXT_MOVL, DL, MVT::v2i64, V);
7088     return DAG.getBitcast(VT, V);
7089   }
7090
7091   // No viable ext lowering found.
7092   return SDValue();
7093 }
7094
7095 /// \brief Try to get a scalar value for a specific element of a vector.
7096 ///
7097 /// Looks through BUILD_VECTOR and SCALAR_TO_VECTOR nodes to find a scalar.
7098 static SDValue getScalarValueForVectorElement(SDValue V, int Idx,
7099                                               SelectionDAG &DAG) {
7100   MVT VT = V.getSimpleValueType();
7101   MVT EltVT = VT.getVectorElementType();
7102   while (V.getOpcode() == ISD::BITCAST)
7103     V = V.getOperand(0);
7104   // If the bitcasts shift the element size, we can't extract an equivalent
7105   // element from it.
7106   MVT NewVT = V.getSimpleValueType();
7107   if (!NewVT.isVector() || NewVT.getScalarSizeInBits() != VT.getScalarSizeInBits())
7108     return SDValue();
7109
7110   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7111       (Idx == 0 && V.getOpcode() == ISD::SCALAR_TO_VECTOR)) {
7112     // Ensure the scalar operand is the same size as the destination.
7113     // FIXME: Add support for scalar truncation where possible.
7114     SDValue S = V.getOperand(Idx);
7115     if (EltVT.getSizeInBits() == S.getSimpleValueType().getSizeInBits())
7116       return DAG.getNode(ISD::BITCAST, SDLoc(V), EltVT, S);
7117   }
7118
7119   return SDValue();
7120 }
7121
7122 /// \brief Helper to test for a load that can be folded with x86 shuffles.
7123 ///
7124 /// This is particularly important because the set of instructions varies
7125 /// significantly based on whether the operand is a load or not.
7126 static bool isShuffleFoldableLoad(SDValue V) {
7127   while (V.getOpcode() == ISD::BITCAST)
7128     V = V.getOperand(0);
7129
7130   return ISD::isNON_EXTLoad(V.getNode());
7131 }
7132
7133 /// \brief Try to lower insertion of a single element into a zero vector.
7134 ///
7135 /// This is a common pattern that we have especially efficient patterns to lower
7136 /// across all subtarget feature sets.
7137 static SDValue lowerVectorShuffleAsElementInsertion(
7138     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
7139     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
7140   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7141   MVT ExtVT = VT;
7142   MVT EltVT = VT.getVectorElementType();
7143
7144   int V2Index = std::find_if(Mask.begin(), Mask.end(),
7145                              [&Mask](int M) { return M >= (int)Mask.size(); }) -
7146                 Mask.begin();
7147   bool IsV1Zeroable = true;
7148   for (int i = 0, Size = Mask.size(); i < Size; ++i)
7149     if (i != V2Index && !Zeroable[i]) {
7150       IsV1Zeroable = false;
7151       break;
7152     }
7153
7154   // Check for a single input from a SCALAR_TO_VECTOR node.
7155   // FIXME: All of this should be canonicalized into INSERT_VECTOR_ELT and
7156   // all the smarts here sunk into that routine. However, the current
7157   // lowering of BUILD_VECTOR makes that nearly impossible until the old
7158   // vector shuffle lowering is dead.
7159   if (SDValue V2S = getScalarValueForVectorElement(
7160           V2, Mask[V2Index] - Mask.size(), DAG)) {
7161     // We need to zext the scalar if it is smaller than an i32.
7162     V2S = DAG.getBitcast(EltVT, V2S);
7163     if (EltVT == MVT::i8 || EltVT == MVT::i16) {
7164       // Using zext to expand a narrow element won't work for non-zero
7165       // insertions.
7166       if (!IsV1Zeroable)
7167         return SDValue();
7168
7169       // Zero-extend directly to i32.
7170       ExtVT = MVT::v4i32;
7171       V2S = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, V2S);
7172     }
7173     V2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, ExtVT, V2S);
7174   } else if (Mask[V2Index] != (int)Mask.size() || EltVT == MVT::i8 ||
7175              EltVT == MVT::i16) {
7176     // Either not inserting from the low element of the input or the input
7177     // element size is too small to use VZEXT_MOVL to clear the high bits.
7178     return SDValue();
7179   }
7180
7181   if (!IsV1Zeroable) {
7182     // If V1 can't be treated as a zero vector we have fewer options to lower
7183     // this. We can't support integer vectors or non-zero targets cheaply, and
7184     // the V1 elements can't be permuted in any way.
7185     assert(VT == ExtVT && "Cannot change extended type when non-zeroable!");
7186     if (!VT.isFloatingPoint() || V2Index != 0)
7187       return SDValue();
7188     SmallVector<int, 8> V1Mask(Mask.begin(), Mask.end());
7189     V1Mask[V2Index] = -1;
7190     if (!isNoopShuffleMask(V1Mask))
7191       return SDValue();
7192     // This is essentially a special case blend operation, but if we have
7193     // general purpose blend operations, they are always faster. Bail and let
7194     // the rest of the lowering handle these as blends.
7195     if (Subtarget->hasSSE41())
7196       return SDValue();
7197
7198     // Otherwise, use MOVSD or MOVSS.
7199     assert((EltVT == MVT::f32 || EltVT == MVT::f64) &&
7200            "Only two types of floating point element types to handle!");
7201     return DAG.getNode(EltVT == MVT::f32 ? X86ISD::MOVSS : X86ISD::MOVSD, DL,
7202                        ExtVT, V1, V2);
7203   }
7204
7205   // This lowering only works for the low element with floating point vectors.
7206   if (VT.isFloatingPoint() && V2Index != 0)
7207     return SDValue();
7208
7209   V2 = DAG.getNode(X86ISD::VZEXT_MOVL, DL, ExtVT, V2);
7210   if (ExtVT != VT)
7211     V2 = DAG.getBitcast(VT, V2);
7212
7213   if (V2Index != 0) {
7214     // If we have 4 or fewer lanes we can cheaply shuffle the element into
7215     // the desired position. Otherwise it is more efficient to do a vector
7216     // shift left. We know that we can do a vector shift left because all
7217     // the inputs are zero.
7218     if (VT.isFloatingPoint() || VT.getVectorNumElements() <= 4) {
7219       SmallVector<int, 4> V2Shuffle(Mask.size(), 1);
7220       V2Shuffle[V2Index] = 0;
7221       V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Shuffle);
7222     } else {
7223       V2 = DAG.getBitcast(MVT::v2i64, V2);
7224       V2 = DAG.getNode(
7225           X86ISD::VSHLDQ, DL, MVT::v2i64, V2,
7226           DAG.getConstant(
7227               V2Index * EltVT.getSizeInBits()/8, DL,
7228               DAG.getTargetLoweringInfo().getScalarShiftAmountTy(MVT::v2i64)));
7229       V2 = DAG.getBitcast(VT, V2);
7230     }
7231   }
7232   return V2;
7233 }
7234
7235 /// \brief Try to lower broadcast of a single element.
7236 ///
7237 /// For convenience, this code also bundles all of the subtarget feature set
7238 /// filtering. While a little annoying to re-dispatch on type here, there isn't
7239 /// a convenient way to factor it out.
7240 static SDValue lowerVectorShuffleAsBroadcast(SDLoc DL, MVT VT, SDValue V,
7241                                              ArrayRef<int> Mask,
7242                                              const X86Subtarget *Subtarget,
7243                                              SelectionDAG &DAG) {
7244   if (!Subtarget->hasAVX())
7245     return SDValue();
7246   if (VT.isInteger() && !Subtarget->hasAVX2())
7247     return SDValue();
7248
7249   // Check that the mask is a broadcast.
7250   int BroadcastIdx = -1;
7251   for (int M : Mask)
7252     if (M >= 0 && BroadcastIdx == -1)
7253       BroadcastIdx = M;
7254     else if (M >= 0 && M != BroadcastIdx)
7255       return SDValue();
7256
7257   assert(BroadcastIdx < (int)Mask.size() && "We only expect to be called with "
7258                                             "a sorted mask where the broadcast "
7259                                             "comes from V1.");
7260
7261   // Go up the chain of (vector) values to find a scalar load that we can
7262   // combine with the broadcast.
7263   for (;;) {
7264     switch (V.getOpcode()) {
7265     case ISD::CONCAT_VECTORS: {
7266       int OperandSize = Mask.size() / V.getNumOperands();
7267       V = V.getOperand(BroadcastIdx / OperandSize);
7268       BroadcastIdx %= OperandSize;
7269       continue;
7270     }
7271
7272     case ISD::INSERT_SUBVECTOR: {
7273       SDValue VOuter = V.getOperand(0), VInner = V.getOperand(1);
7274       auto ConstantIdx = dyn_cast<ConstantSDNode>(V.getOperand(2));
7275       if (!ConstantIdx)
7276         break;
7277
7278       int BeginIdx = (int)ConstantIdx->getZExtValue();
7279       int EndIdx =
7280           BeginIdx + (int)VInner.getValueType().getVectorNumElements();
7281       if (BroadcastIdx >= BeginIdx && BroadcastIdx < EndIdx) {
7282         BroadcastIdx -= BeginIdx;
7283         V = VInner;
7284       } else {
7285         V = VOuter;
7286       }
7287       continue;
7288     }
7289     }
7290     break;
7291   }
7292
7293   // Check if this is a broadcast of a scalar. We special case lowering
7294   // for scalars so that we can more effectively fold with loads.
7295   if (V.getOpcode() == ISD::BUILD_VECTOR ||
7296       (V.getOpcode() == ISD::SCALAR_TO_VECTOR && BroadcastIdx == 0)) {
7297     V = V.getOperand(BroadcastIdx);
7298
7299     // If the scalar isn't a load, we can't broadcast from it in AVX1.
7300     // Only AVX2 has register broadcasts.
7301     if (!Subtarget->hasAVX2() && !isShuffleFoldableLoad(V))
7302       return SDValue();
7303   } else if (BroadcastIdx != 0 || !Subtarget->hasAVX2()) {
7304     // We can't broadcast from a vector register without AVX2, and we can only
7305     // broadcast from the zero-element of a vector register.
7306     return SDValue();
7307   }
7308
7309   return DAG.getNode(X86ISD::VBROADCAST, DL, VT, V);
7310 }
7311
7312 // Check for whether we can use INSERTPS to perform the shuffle. We only use
7313 // INSERTPS when the V1 elements are already in the correct locations
7314 // because otherwise we can just always use two SHUFPS instructions which
7315 // are much smaller to encode than a SHUFPS and an INSERTPS. We can also
7316 // perform INSERTPS if a single V1 element is out of place and all V2
7317 // elements are zeroable.
7318 static SDValue lowerVectorShuffleAsInsertPS(SDValue Op, SDValue V1, SDValue V2,
7319                                             ArrayRef<int> Mask,
7320                                             SelectionDAG &DAG) {
7321   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7322   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7323   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7324   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7325
7326   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
7327
7328   unsigned ZMask = 0;
7329   int V1DstIndex = -1;
7330   int V2DstIndex = -1;
7331   bool V1UsedInPlace = false;
7332
7333   for (int i = 0; i < 4; ++i) {
7334     // Synthesize a zero mask from the zeroable elements (includes undefs).
7335     if (Zeroable[i]) {
7336       ZMask |= 1 << i;
7337       continue;
7338     }
7339
7340     // Flag if we use any V1 inputs in place.
7341     if (i == Mask[i]) {
7342       V1UsedInPlace = true;
7343       continue;
7344     }
7345
7346     // We can only insert a single non-zeroable element.
7347     if (V1DstIndex != -1 || V2DstIndex != -1)
7348       return SDValue();
7349
7350     if (Mask[i] < 4) {
7351       // V1 input out of place for insertion.
7352       V1DstIndex = i;
7353     } else {
7354       // V2 input for insertion.
7355       V2DstIndex = i;
7356     }
7357   }
7358
7359   // Don't bother if we have no (non-zeroable) element for insertion.
7360   if (V1DstIndex == -1 && V2DstIndex == -1)
7361     return SDValue();
7362
7363   // Determine element insertion src/dst indices. The src index is from the
7364   // start of the inserted vector, not the start of the concatenated vector.
7365   unsigned V2SrcIndex = 0;
7366   if (V1DstIndex != -1) {
7367     // If we have a V1 input out of place, we use V1 as the V2 element insertion
7368     // and don't use the original V2 at all.
7369     V2SrcIndex = Mask[V1DstIndex];
7370     V2DstIndex = V1DstIndex;
7371     V2 = V1;
7372   } else {
7373     V2SrcIndex = Mask[V2DstIndex] - 4;
7374   }
7375
7376   // If no V1 inputs are used in place, then the result is created only from
7377   // the zero mask and the V2 insertion - so remove V1 dependency.
7378   if (!V1UsedInPlace)
7379     V1 = DAG.getUNDEF(MVT::v4f32);
7380
7381   unsigned InsertPSMask = V2SrcIndex << 6 | V2DstIndex << 4 | ZMask;
7382   assert((InsertPSMask & ~0xFFu) == 0 && "Invalid mask!");
7383
7384   // Insert the V2 element into the desired position.
7385   SDLoc DL(Op);
7386   return DAG.getNode(X86ISD::INSERTPS, DL, MVT::v4f32, V1, V2,
7387                      DAG.getConstant(InsertPSMask, DL, MVT::i8));
7388 }
7389
7390 /// \brief Try to lower a shuffle as a permute of the inputs followed by an
7391 /// UNPCK instruction.
7392 ///
7393 /// This specifically targets cases where we end up with alternating between
7394 /// the two inputs, and so can permute them into something that feeds a single
7395 /// UNPCK instruction. Note that this routine only targets integer vectors
7396 /// because for floating point vectors we have a generalized SHUFPS lowering
7397 /// strategy that handles everything that doesn't *exactly* match an unpack,
7398 /// making this clever lowering unnecessary.
7399 static SDValue lowerVectorShuffleAsUnpack(SDLoc DL, MVT VT, SDValue V1,
7400                                           SDValue V2, ArrayRef<int> Mask,
7401                                           SelectionDAG &DAG) {
7402   assert(!VT.isFloatingPoint() &&
7403          "This routine only supports integer vectors.");
7404   assert(!isSingleInputShuffleMask(Mask) &&
7405          "This routine should only be used when blending two inputs.");
7406   assert(Mask.size() >= 2 && "Single element masks are invalid.");
7407
7408   int Size = Mask.size();
7409
7410   int NumLoInputs = std::count_if(Mask.begin(), Mask.end(), [Size](int M) {
7411     return M >= 0 && M % Size < Size / 2;
7412   });
7413   int NumHiInputs = std::count_if(
7414       Mask.begin(), Mask.end(), [Size](int M) { return M % Size >= Size / 2; });
7415
7416   bool UnpackLo = NumLoInputs >= NumHiInputs;
7417
7418   auto TryUnpack = [&](MVT UnpackVT, int Scale) {
7419     SmallVector<int, 32> V1Mask(Mask.size(), -1);
7420     SmallVector<int, 32> V2Mask(Mask.size(), -1);
7421
7422     for (int i = 0; i < Size; ++i) {
7423       if (Mask[i] < 0)
7424         continue;
7425
7426       // Each element of the unpack contains Scale elements from this mask.
7427       int UnpackIdx = i / Scale;
7428
7429       // We only handle the case where V1 feeds the first slots of the unpack.
7430       // We rely on canonicalization to ensure this is the case.
7431       if ((UnpackIdx % 2 == 0) != (Mask[i] < Size))
7432         return SDValue();
7433
7434       // Setup the mask for this input. The indexing is tricky as we have to
7435       // handle the unpack stride.
7436       SmallVectorImpl<int> &VMask = (UnpackIdx % 2 == 0) ? V1Mask : V2Mask;
7437       VMask[(UnpackIdx / 2) * Scale + i % Scale + (UnpackLo ? 0 : Size / 2)] =
7438           Mask[i] % Size;
7439     }
7440
7441     // If we will have to shuffle both inputs to use the unpack, check whether
7442     // we can just unpack first and shuffle the result. If so, skip this unpack.
7443     if ((NumLoInputs == 0 || NumHiInputs == 0) && !isNoopShuffleMask(V1Mask) &&
7444         !isNoopShuffleMask(V2Mask))
7445       return SDValue();
7446
7447     // Shuffle the inputs into place.
7448     V1 = DAG.getVectorShuffle(VT, DL, V1, DAG.getUNDEF(VT), V1Mask);
7449     V2 = DAG.getVectorShuffle(VT, DL, V2, DAG.getUNDEF(VT), V2Mask);
7450
7451     // Cast the inputs to the type we will use to unpack them.
7452     V1 = DAG.getBitcast(UnpackVT, V1);
7453     V2 = DAG.getBitcast(UnpackVT, V2);
7454
7455     // Unpack the inputs and cast the result back to the desired type.
7456     return DAG.getBitcast(
7457         VT, DAG.getNode(UnpackLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
7458                         UnpackVT, V1, V2));
7459   };
7460
7461   // We try each unpack from the largest to the smallest to try and find one
7462   // that fits this mask.
7463   int OrigNumElements = VT.getVectorNumElements();
7464   int OrigScalarSize = VT.getScalarSizeInBits();
7465   for (int ScalarSize = 64; ScalarSize >= OrigScalarSize; ScalarSize /= 2) {
7466     int Scale = ScalarSize / OrigScalarSize;
7467     int NumElements = OrigNumElements / Scale;
7468     MVT UnpackVT = MVT::getVectorVT(MVT::getIntegerVT(ScalarSize), NumElements);
7469     if (SDValue Unpack = TryUnpack(UnpackVT, Scale))
7470       return Unpack;
7471   }
7472
7473   // If none of the unpack-rooted lowerings worked (or were profitable) try an
7474   // initial unpack.
7475   if (NumLoInputs == 0 || NumHiInputs == 0) {
7476     assert((NumLoInputs > 0 || NumHiInputs > 0) &&
7477            "We have to have *some* inputs!");
7478     int HalfOffset = NumLoInputs == 0 ? Size / 2 : 0;
7479
7480     // FIXME: We could consider the total complexity of the permute of each
7481     // possible unpacking. Or at the least we should consider how many
7482     // half-crossings are created.
7483     // FIXME: We could consider commuting the unpacks.
7484
7485     SmallVector<int, 32> PermMask;
7486     PermMask.assign(Size, -1);
7487     for (int i = 0; i < Size; ++i) {
7488       if (Mask[i] < 0)
7489         continue;
7490
7491       assert(Mask[i] % Size >= HalfOffset && "Found input from wrong half!");
7492
7493       PermMask[i] =
7494           2 * ((Mask[i] % Size) - HalfOffset) + (Mask[i] < Size ? 0 : 1);
7495     }
7496     return DAG.getVectorShuffle(
7497         VT, DL, DAG.getNode(NumLoInputs == 0 ? X86ISD::UNPCKH : X86ISD::UNPCKL,
7498                             DL, VT, V1, V2),
7499         DAG.getUNDEF(VT), PermMask);
7500   }
7501
7502   return SDValue();
7503 }
7504
7505 /// \brief Handle lowering of 2-lane 64-bit floating point shuffles.
7506 ///
7507 /// This is the basis function for the 2-lane 64-bit shuffles as we have full
7508 /// support for floating point shuffles but not integer shuffles. These
7509 /// instructions will incur a domain crossing penalty on some chips though so
7510 /// it is better to avoid lowering through this for integer vectors where
7511 /// possible.
7512 static SDValue lowerV2F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7513                                        const X86Subtarget *Subtarget,
7514                                        SelectionDAG &DAG) {
7515   SDLoc DL(Op);
7516   assert(Op.getSimpleValueType() == MVT::v2f64 && "Bad shuffle type!");
7517   assert(V1.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7518   assert(V2.getSimpleValueType() == MVT::v2f64 && "Bad operand type!");
7519   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7520   ArrayRef<int> Mask = SVOp->getMask();
7521   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7522
7523   if (isSingleInputShuffleMask(Mask)) {
7524     // Use low duplicate instructions for masks that match their pattern.
7525     if (Subtarget->hasSSE3())
7526       if (isShuffleEquivalent(V1, V2, Mask, {0, 0}))
7527         return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v2f64, V1);
7528
7529     // Straight shuffle of a single input vector. Simulate this by using the
7530     // single input as both of the "inputs" to this instruction..
7531     unsigned SHUFPDMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1);
7532
7533     if (Subtarget->hasAVX()) {
7534       // If we have AVX, we can use VPERMILPS which will allow folding a load
7535       // into the shuffle.
7536       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v2f64, V1,
7537                          DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7538     }
7539
7540     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V1,
7541                        DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7542   }
7543   assert(Mask[0] >= 0 && Mask[0] < 2 && "Non-canonicalized blend!");
7544   assert(Mask[1] >= 2 && "Non-canonicalized blend!");
7545
7546   // If we have a single input, insert that into V1 if we can do so cheaply.
7547   if ((Mask[0] >= 2) + (Mask[1] >= 2) == 1) {
7548     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7549             DL, MVT::v2f64, V1, V2, Mask, Subtarget, DAG))
7550       return Insertion;
7551     // Try inverting the insertion since for v2 masks it is easy to do and we
7552     // can't reliably sort the mask one way or the other.
7553     int InverseMask[2] = {Mask[0] < 0 ? -1 : (Mask[0] ^ 2),
7554                           Mask[1] < 0 ? -1 : (Mask[1] ^ 2)};
7555     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7556             DL, MVT::v2f64, V2, V1, InverseMask, Subtarget, DAG))
7557       return Insertion;
7558   }
7559
7560   // Try to use one of the special instruction patterns to handle two common
7561   // blend patterns if a zero-blend above didn't work.
7562   if (isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
7563       isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7564     if (SDValue V1S = getScalarValueForVectorElement(V1, Mask[0], DAG))
7565       // We can either use a special instruction to load over the low double or
7566       // to move just the low double.
7567       return DAG.getNode(
7568           isShuffleFoldableLoad(V1S) ? X86ISD::MOVLPD : X86ISD::MOVSD,
7569           DL, MVT::v2f64, V2,
7570           DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64, V1S));
7571
7572   if (Subtarget->hasSSE41())
7573     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2f64, V1, V2, Mask,
7574                                                   Subtarget, DAG))
7575       return Blend;
7576
7577   // Use dedicated unpack instructions for masks that match their pattern.
7578   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7579     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2f64, V1, V2);
7580   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7581     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2f64, V1, V2);
7582
7583   unsigned SHUFPDMask = (Mask[0] == 1) | (((Mask[1] - 2) == 1) << 1);
7584   return DAG.getNode(X86ISD::SHUFP, DL, MVT::v2f64, V1, V2,
7585                      DAG.getConstant(SHUFPDMask, DL, MVT::i8));
7586 }
7587
7588 /// \brief Handle lowering of 2-lane 64-bit integer shuffles.
7589 ///
7590 /// Tries to lower a 2-lane 64-bit shuffle using shuffle operations provided by
7591 /// the integer unit to minimize domain crossing penalties. However, for blends
7592 /// it falls back to the floating point shuffle operation with appropriate bit
7593 /// casting.
7594 static SDValue lowerV2I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7595                                        const X86Subtarget *Subtarget,
7596                                        SelectionDAG &DAG) {
7597   SDLoc DL(Op);
7598   assert(Op.getSimpleValueType() == MVT::v2i64 && "Bad shuffle type!");
7599   assert(V1.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7600   assert(V2.getSimpleValueType() == MVT::v2i64 && "Bad operand type!");
7601   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7602   ArrayRef<int> Mask = SVOp->getMask();
7603   assert(Mask.size() == 2 && "Unexpected mask size for v2 shuffle!");
7604
7605   if (isSingleInputShuffleMask(Mask)) {
7606     // Check for being able to broadcast a single element.
7607     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v2i64, V1,
7608                                                           Mask, Subtarget, DAG))
7609       return Broadcast;
7610
7611     // Straight shuffle of a single input vector. For everything from SSE2
7612     // onward this has a single fast instruction with no scary immediates.
7613     // We have to map the mask as it is actually a v4i32 shuffle instruction.
7614     V1 = DAG.getBitcast(MVT::v4i32, V1);
7615     int WidenedMask[4] = {
7616         std::max(Mask[0], 0) * 2, std::max(Mask[0], 0) * 2 + 1,
7617         std::max(Mask[1], 0) * 2, std::max(Mask[1], 0) * 2 + 1};
7618     return DAG.getBitcast(
7619         MVT::v2i64,
7620         DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7621                     getV4X86ShuffleImm8ForMask(WidenedMask, DL, DAG)));
7622   }
7623   assert(Mask[0] != -1 && "No undef lanes in multi-input v2 shuffles!");
7624   assert(Mask[1] != -1 && "No undef lanes in multi-input v2 shuffles!");
7625   assert(Mask[0] < 2 && "We sort V1 to be the first input.");
7626   assert(Mask[1] >= 2 && "We sort V2 to be the second input.");
7627
7628   // If we have a blend of two PACKUS operations an the blend aligns with the
7629   // low and half halves, we can just merge the PACKUS operations. This is
7630   // particularly important as it lets us merge shuffles that this routine itself
7631   // creates.
7632   auto GetPackNode = [](SDValue V) {
7633     while (V.getOpcode() == ISD::BITCAST)
7634       V = V.getOperand(0);
7635
7636     return V.getOpcode() == X86ISD::PACKUS ? V : SDValue();
7637   };
7638   if (SDValue V1Pack = GetPackNode(V1))
7639     if (SDValue V2Pack = GetPackNode(V2))
7640       return DAG.getBitcast(MVT::v2i64,
7641                             DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8,
7642                                         Mask[0] == 0 ? V1Pack.getOperand(0)
7643                                                      : V1Pack.getOperand(1),
7644                                         Mask[1] == 2 ? V2Pack.getOperand(0)
7645                                                      : V2Pack.getOperand(1)));
7646
7647   // Try to use shift instructions.
7648   if (SDValue Shift =
7649           lowerVectorShuffleAsShift(DL, MVT::v2i64, V1, V2, Mask, DAG))
7650     return Shift;
7651
7652   // When loading a scalar and then shuffling it into a vector we can often do
7653   // the insertion cheaply.
7654   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7655           DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7656     return Insertion;
7657   // Try inverting the insertion since for v2 masks it is easy to do and we
7658   // can't reliably sort the mask one way or the other.
7659   int InverseMask[2] = {Mask[0] ^ 2, Mask[1] ^ 2};
7660   if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
7661           DL, MVT::v2i64, V2, V1, InverseMask, Subtarget, DAG))
7662     return Insertion;
7663
7664   // We have different paths for blend lowering, but they all must use the
7665   // *exact* same predicate.
7666   bool IsBlendSupported = Subtarget->hasSSE41();
7667   if (IsBlendSupported)
7668     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v2i64, V1, V2, Mask,
7669                                                   Subtarget, DAG))
7670       return Blend;
7671
7672   // Use dedicated unpack instructions for masks that match their pattern.
7673   if (isShuffleEquivalent(V1, V2, Mask, {0, 2}))
7674     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v2i64, V1, V2);
7675   if (isShuffleEquivalent(V1, V2, Mask, {1, 3}))
7676     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v2i64, V1, V2);
7677
7678   // Try to use byte rotation instructions.
7679   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7680   if (Subtarget->hasSSSE3())
7681     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7682             DL, MVT::v2i64, V1, V2, Mask, Subtarget, DAG))
7683       return Rotate;
7684
7685   // If we have direct support for blends, we should lower by decomposing into
7686   // a permute. That will be faster than the domain cross.
7687   if (IsBlendSupported)
7688     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v2i64, V1, V2,
7689                                                       Mask, DAG);
7690
7691   // We implement this with SHUFPD which is pretty lame because it will likely
7692   // incur 2 cycles of stall for integer vectors on Nehalem and older chips.
7693   // However, all the alternatives are still more cycles and newer chips don't
7694   // have this problem. It would be really nice if x86 had better shuffles here.
7695   V1 = DAG.getBitcast(MVT::v2f64, V1);
7696   V2 = DAG.getBitcast(MVT::v2f64, V2);
7697   return DAG.getBitcast(MVT::v2i64,
7698                         DAG.getVectorShuffle(MVT::v2f64, DL, V1, V2, Mask));
7699 }
7700
7701 /// \brief Test whether this can be lowered with a single SHUFPS instruction.
7702 ///
7703 /// This is used to disable more specialized lowerings when the shufps lowering
7704 /// will happen to be efficient.
7705 static bool isSingleSHUFPSMask(ArrayRef<int> Mask) {
7706   // This routine only handles 128-bit shufps.
7707   assert(Mask.size() == 4 && "Unsupported mask size!");
7708
7709   // To lower with a single SHUFPS we need to have the low half and high half
7710   // each requiring a single input.
7711   if (Mask[0] != -1 && Mask[1] != -1 && (Mask[0] < 4) != (Mask[1] < 4))
7712     return false;
7713   if (Mask[2] != -1 && Mask[3] != -1 && (Mask[2] < 4) != (Mask[3] < 4))
7714     return false;
7715
7716   return true;
7717 }
7718
7719 /// \brief Lower a vector shuffle using the SHUFPS instruction.
7720 ///
7721 /// This is a helper routine dedicated to lowering vector shuffles using SHUFPS.
7722 /// It makes no assumptions about whether this is the *best* lowering, it simply
7723 /// uses it.
7724 static SDValue lowerVectorShuffleWithSHUFPS(SDLoc DL, MVT VT,
7725                                             ArrayRef<int> Mask, SDValue V1,
7726                                             SDValue V2, SelectionDAG &DAG) {
7727   SDValue LowV = V1, HighV = V2;
7728   int NewMask[4] = {Mask[0], Mask[1], Mask[2], Mask[3]};
7729
7730   int NumV2Elements =
7731       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7732
7733   if (NumV2Elements == 1) {
7734     int V2Index =
7735         std::find_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; }) -
7736         Mask.begin();
7737
7738     // Compute the index adjacent to V2Index and in the same half by toggling
7739     // the low bit.
7740     int V2AdjIndex = V2Index ^ 1;
7741
7742     if (Mask[V2AdjIndex] == -1) {
7743       // Handles all the cases where we have a single V2 element and an undef.
7744       // This will only ever happen in the high lanes because we commute the
7745       // vector otherwise.
7746       if (V2Index < 2)
7747         std::swap(LowV, HighV);
7748       NewMask[V2Index] -= 4;
7749     } else {
7750       // Handle the case where the V2 element ends up adjacent to a V1 element.
7751       // To make this work, blend them together as the first step.
7752       int V1Index = V2AdjIndex;
7753       int BlendMask[4] = {Mask[V2Index] - 4, 0, Mask[V1Index], 0};
7754       V2 = DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
7755                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7756
7757       // Now proceed to reconstruct the final blend as we have the necessary
7758       // high or low half formed.
7759       if (V2Index < 2) {
7760         LowV = V2;
7761         HighV = V1;
7762       } else {
7763         HighV = V2;
7764       }
7765       NewMask[V1Index] = 2; // We put the V1 element in V2[2].
7766       NewMask[V2Index] = 0; // We shifted the V2 element into V2[0].
7767     }
7768   } else if (NumV2Elements == 2) {
7769     if (Mask[0] < 4 && Mask[1] < 4) {
7770       // Handle the easy case where we have V1 in the low lanes and V2 in the
7771       // high lanes.
7772       NewMask[2] -= 4;
7773       NewMask[3] -= 4;
7774     } else if (Mask[2] < 4 && Mask[3] < 4) {
7775       // We also handle the reversed case because this utility may get called
7776       // when we detect a SHUFPS pattern but can't easily commute the shuffle to
7777       // arrange things in the right direction.
7778       NewMask[0] -= 4;
7779       NewMask[1] -= 4;
7780       HighV = V1;
7781       LowV = V2;
7782     } else {
7783       // We have a mixture of V1 and V2 in both low and high lanes. Rather than
7784       // trying to place elements directly, just blend them and set up the final
7785       // shuffle to place them.
7786
7787       // The first two blend mask elements are for V1, the second two are for
7788       // V2.
7789       int BlendMask[4] = {Mask[0] < 4 ? Mask[0] : Mask[1],
7790                           Mask[2] < 4 ? Mask[2] : Mask[3],
7791                           (Mask[0] >= 4 ? Mask[0] : Mask[1]) - 4,
7792                           (Mask[2] >= 4 ? Mask[2] : Mask[3]) - 4};
7793       V1 = DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
7794                        getV4X86ShuffleImm8ForMask(BlendMask, DL, DAG));
7795
7796       // Now we do a normal shuffle of V1 by giving V1 as both operands to
7797       // a blend.
7798       LowV = HighV = V1;
7799       NewMask[0] = Mask[0] < 4 ? 0 : 2;
7800       NewMask[1] = Mask[0] < 4 ? 2 : 0;
7801       NewMask[2] = Mask[2] < 4 ? 1 : 3;
7802       NewMask[3] = Mask[2] < 4 ? 3 : 1;
7803     }
7804   }
7805   return DAG.getNode(X86ISD::SHUFP, DL, VT, LowV, HighV,
7806                      getV4X86ShuffleImm8ForMask(NewMask, DL, DAG));
7807 }
7808
7809 /// \brief Lower 4-lane 32-bit floating point shuffles.
7810 ///
7811 /// Uses instructions exclusively from the floating point unit to minimize
7812 /// domain crossing penalties, as these are sufficient to implement all v4f32
7813 /// shuffles.
7814 static SDValue lowerV4F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7815                                        const X86Subtarget *Subtarget,
7816                                        SelectionDAG &DAG) {
7817   SDLoc DL(Op);
7818   assert(Op.getSimpleValueType() == MVT::v4f32 && "Bad shuffle type!");
7819   assert(V1.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7820   assert(V2.getSimpleValueType() == MVT::v4f32 && "Bad operand type!");
7821   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7822   ArrayRef<int> Mask = SVOp->getMask();
7823   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7824
7825   int NumV2Elements =
7826       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7827
7828   if (NumV2Elements == 0) {
7829     // Check for being able to broadcast a single element.
7830     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f32, V1,
7831                                                           Mask, Subtarget, DAG))
7832       return Broadcast;
7833
7834     // Use even/odd duplicate instructions for masks that match their pattern.
7835     if (Subtarget->hasSSE3()) {
7836       if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
7837         return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v4f32, V1);
7838       if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3}))
7839         return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v4f32, V1);
7840     }
7841
7842     if (Subtarget->hasAVX()) {
7843       // If we have AVX, we can use VPERMILPS which will allow folding a load
7844       // into the shuffle.
7845       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f32, V1,
7846                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7847     }
7848
7849     // Otherwise, use a straight shuffle of a single input vector. We pass the
7850     // input vector to both operands to simulate this with a SHUFPS.
7851     return DAG.getNode(X86ISD::SHUFP, DL, MVT::v4f32, V1, V1,
7852                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7853   }
7854
7855   // There are special ways we can lower some single-element blends. However, we
7856   // have custom ways we can lower more complex single-element blends below that
7857   // we defer to if both this and BLENDPS fail to match, so restrict this to
7858   // when the V2 input is targeting element 0 of the mask -- that is the fast
7859   // case here.
7860   if (NumV2Elements == 1 && Mask[0] >= 4)
7861     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4f32, V1, V2,
7862                                                          Mask, Subtarget, DAG))
7863       return V;
7864
7865   if (Subtarget->hasSSE41()) {
7866     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f32, V1, V2, Mask,
7867                                                   Subtarget, DAG))
7868       return Blend;
7869
7870     // Use INSERTPS if we can complete the shuffle efficiently.
7871     if (SDValue V = lowerVectorShuffleAsInsertPS(Op, V1, V2, Mask, DAG))
7872       return V;
7873
7874     if (!isSingleSHUFPSMask(Mask))
7875       if (SDValue BlendPerm = lowerVectorShuffleAsBlendAndPermute(
7876               DL, MVT::v4f32, V1, V2, Mask, DAG))
7877         return BlendPerm;
7878   }
7879
7880   // Use dedicated unpack instructions for masks that match their pattern.
7881   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7882     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V1, V2);
7883   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7884     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V1, V2);
7885   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7886     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f32, V2, V1);
7887   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7888     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f32, V2, V1);
7889
7890   // Otherwise fall back to a SHUFPS lowering strategy.
7891   return lowerVectorShuffleWithSHUFPS(DL, MVT::v4f32, Mask, V1, V2, DAG);
7892 }
7893
7894 /// \brief Lower 4-lane i32 vector shuffles.
7895 ///
7896 /// We try to handle these with integer-domain shuffles where we can, but for
7897 /// blends we use the floating point domain blend instructions.
7898 static SDValue lowerV4I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
7899                                        const X86Subtarget *Subtarget,
7900                                        SelectionDAG &DAG) {
7901   SDLoc DL(Op);
7902   assert(Op.getSimpleValueType() == MVT::v4i32 && "Bad shuffle type!");
7903   assert(V1.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7904   assert(V2.getSimpleValueType() == MVT::v4i32 && "Bad operand type!");
7905   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
7906   ArrayRef<int> Mask = SVOp->getMask();
7907   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
7908
7909   // Whenever we can lower this as a zext, that instruction is strictly faster
7910   // than any alternative. It also allows us to fold memory operands into the
7911   // shuffle in many cases.
7912   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v4i32, V1, V2,
7913                                                          Mask, Subtarget, DAG))
7914     return ZExt;
7915
7916   int NumV2Elements =
7917       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 4; });
7918
7919   if (NumV2Elements == 0) {
7920     // Check for being able to broadcast a single element.
7921     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i32, V1,
7922                                                           Mask, Subtarget, DAG))
7923       return Broadcast;
7924
7925     // Straight shuffle of a single input vector. For everything from SSE2
7926     // onward this has a single fast instruction with no scary immediates.
7927     // We coerce the shuffle pattern to be compatible with UNPCK instructions
7928     // but we aren't actually going to use the UNPCK instruction because doing
7929     // so prevents folding a load into this instruction or making a copy.
7930     const int UnpackLoMask[] = {0, 0, 1, 1};
7931     const int UnpackHiMask[] = {2, 2, 3, 3};
7932     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 1, 1}))
7933       Mask = UnpackLoMask;
7934     else if (isShuffleEquivalent(V1, V2, Mask, {2, 2, 3, 3}))
7935       Mask = UnpackHiMask;
7936
7937     return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v4i32, V1,
7938                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
7939   }
7940
7941   // Try to use shift instructions.
7942   if (SDValue Shift =
7943           lowerVectorShuffleAsShift(DL, MVT::v4i32, V1, V2, Mask, DAG))
7944     return Shift;
7945
7946   // There are special ways we can lower some single-element blends.
7947   if (NumV2Elements == 1)
7948     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v4i32, V1, V2,
7949                                                          Mask, Subtarget, DAG))
7950       return V;
7951
7952   // We have different paths for blend lowering, but they all must use the
7953   // *exact* same predicate.
7954   bool IsBlendSupported = Subtarget->hasSSE41();
7955   if (IsBlendSupported)
7956     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i32, V1, V2, Mask,
7957                                                   Subtarget, DAG))
7958       return Blend;
7959
7960   if (SDValue Masked =
7961           lowerVectorShuffleAsBitMask(DL, MVT::v4i32, V1, V2, Mask, DAG))
7962     return Masked;
7963
7964   // Use dedicated unpack instructions for masks that match their pattern.
7965   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 1, 5}))
7966     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V1, V2);
7967   if (isShuffleEquivalent(V1, V2, Mask, {2, 6, 3, 7}))
7968     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V1, V2);
7969   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 5, 1}))
7970     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i32, V2, V1);
7971   if (isShuffleEquivalent(V1, V2, Mask, {6, 2, 7, 3}))
7972     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i32, V2, V1);
7973
7974   // Try to use byte rotation instructions.
7975   // Its more profitable for pre-SSSE3 to use shuffles/unpacks.
7976   if (Subtarget->hasSSSE3())
7977     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
7978             DL, MVT::v4i32, V1, V2, Mask, Subtarget, DAG))
7979       return Rotate;
7980
7981   // If we have direct support for blends, we should lower by decomposing into
7982   // a permute. That will be faster than the domain cross.
7983   if (IsBlendSupported)
7984     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i32, V1, V2,
7985                                                       Mask, DAG);
7986
7987   // Try to lower by permuting the inputs into an unpack instruction.
7988   if (SDValue Unpack =
7989           lowerVectorShuffleAsUnpack(DL, MVT::v4i32, V1, V2, Mask, DAG))
7990     return Unpack;
7991
7992   // We implement this with SHUFPS because it can blend from two vectors.
7993   // Because we're going to eventually use SHUFPS, we use SHUFPS even to build
7994   // up the inputs, bypassing domain shift penalties that we would encur if we
7995   // directly used PSHUFD on Nehalem and older. For newer chips, this isn't
7996   // relevant.
7997   return DAG.getBitcast(
7998       MVT::v4i32,
7999       DAG.getVectorShuffle(MVT::v4f32, DL, DAG.getBitcast(MVT::v4f32, V1),
8000                            DAG.getBitcast(MVT::v4f32, V2), Mask));
8001 }
8002
8003 /// \brief Lowering of single-input v8i16 shuffles is the cornerstone of SSE2
8004 /// shuffle lowering, and the most complex part.
8005 ///
8006 /// The lowering strategy is to try to form pairs of input lanes which are
8007 /// targeted at the same half of the final vector, and then use a dword shuffle
8008 /// to place them onto the right half, and finally unpack the paired lanes into
8009 /// their final position.
8010 ///
8011 /// The exact breakdown of how to form these dword pairs and align them on the
8012 /// correct sides is really tricky. See the comments within the function for
8013 /// more of the details.
8014 ///
8015 /// This code also handles repeated 128-bit lanes of v8i16 shuffles, but each
8016 /// lane must shuffle the *exact* same way. In fact, you must pass a v8 Mask to
8017 /// this routine for it to work correctly. To shuffle a 256-bit or 512-bit i16
8018 /// vector, form the analogous 128-bit 8-element Mask.
8019 static SDValue lowerV8I16GeneralSingleInputVectorShuffle(
8020     SDLoc DL, MVT VT, SDValue V, MutableArrayRef<int> Mask,
8021     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
8022   assert(VT.getScalarType() == MVT::i16 && "Bad input type!");
8023   MVT PSHUFDVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
8024
8025   assert(Mask.size() == 8 && "Shuffle mask length doen't match!");
8026   MutableArrayRef<int> LoMask = Mask.slice(0, 4);
8027   MutableArrayRef<int> HiMask = Mask.slice(4, 4);
8028
8029   SmallVector<int, 4> LoInputs;
8030   std::copy_if(LoMask.begin(), LoMask.end(), std::back_inserter(LoInputs),
8031                [](int M) { return M >= 0; });
8032   std::sort(LoInputs.begin(), LoInputs.end());
8033   LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()), LoInputs.end());
8034   SmallVector<int, 4> HiInputs;
8035   std::copy_if(HiMask.begin(), HiMask.end(), std::back_inserter(HiInputs),
8036                [](int M) { return M >= 0; });
8037   std::sort(HiInputs.begin(), HiInputs.end());
8038   HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()), HiInputs.end());
8039   int NumLToL =
8040       std::lower_bound(LoInputs.begin(), LoInputs.end(), 4) - LoInputs.begin();
8041   int NumHToL = LoInputs.size() - NumLToL;
8042   int NumLToH =
8043       std::lower_bound(HiInputs.begin(), HiInputs.end(), 4) - HiInputs.begin();
8044   int NumHToH = HiInputs.size() - NumLToH;
8045   MutableArrayRef<int> LToLInputs(LoInputs.data(), NumLToL);
8046   MutableArrayRef<int> LToHInputs(HiInputs.data(), NumLToH);
8047   MutableArrayRef<int> HToLInputs(LoInputs.data() + NumLToL, NumHToL);
8048   MutableArrayRef<int> HToHInputs(HiInputs.data() + NumLToH, NumHToH);
8049
8050   // Simplify the 1-into-3 and 3-into-1 cases with a single pshufd. For all
8051   // such inputs we can swap two of the dwords across the half mark and end up
8052   // with <=2 inputs to each half in each half. Once there, we can fall through
8053   // to the generic code below. For example:
8054   //
8055   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8056   // Mask:  [0, 1, 2, 7, 4, 5, 6, 3] -----------------> [0, 1, 4, 7, 2, 3, 6, 5]
8057   //
8058   // However in some very rare cases we have a 1-into-3 or 3-into-1 on one half
8059   // and an existing 2-into-2 on the other half. In this case we may have to
8060   // pre-shuffle the 2-into-2 half to avoid turning it into a 3-into-1 or
8061   // 1-into-3 which could cause us to cycle endlessly fixing each side in turn.
8062   // Fortunately, we don't have to handle anything but a 2-into-2 pattern
8063   // because any other situation (including a 3-into-1 or 1-into-3 in the other
8064   // half than the one we target for fixing) will be fixed when we re-enter this
8065   // path. We will also combine away any sequence of PSHUFD instructions that
8066   // result into a single instruction. Here is an example of the tricky case:
8067   //
8068   // Input: [a, b, c, d, e, f, g, h] -PSHUFD[0,2,1,3]-> [a, b, e, f, c, d, g, h]
8069   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -THIS-IS-BAD!!!!-> [5, 7, 1, 0, 4, 7, 5, 3]
8070   //
8071   // This now has a 1-into-3 in the high half! Instead, we do two shuffles:
8072   //
8073   // Input: [a, b, c, d, e, f, g, h] PSHUFHW[0,2,1,3]-> [a, b, c, d, e, g, f, h]
8074   // Mask:  [3, 7, 1, 0, 2, 7, 3, 5] -----------------> [3, 7, 1, 0, 2, 7, 3, 6]
8075   //
8076   // Input: [a, b, c, d, e, g, f, h] -PSHUFD[0,2,1,3]-> [a, b, e, g, c, d, f, h]
8077   // Mask:  [3, 7, 1, 0, 2, 7, 3, 6] -----------------> [5, 7, 1, 0, 4, 7, 5, 6]
8078   //
8079   // The result is fine to be handled by the generic logic.
8080   auto balanceSides = [&](ArrayRef<int> AToAInputs, ArrayRef<int> BToAInputs,
8081                           ArrayRef<int> BToBInputs, ArrayRef<int> AToBInputs,
8082                           int AOffset, int BOffset) {
8083     assert((AToAInputs.size() == 3 || AToAInputs.size() == 1) &&
8084            "Must call this with A having 3 or 1 inputs from the A half.");
8085     assert((BToAInputs.size() == 1 || BToAInputs.size() == 3) &&
8086            "Must call this with B having 1 or 3 inputs from the B half.");
8087     assert(AToAInputs.size() + BToAInputs.size() == 4 &&
8088            "Must call this with either 3:1 or 1:3 inputs (summing to 4).");
8089
8090     // Compute the index of dword with only one word among the three inputs in
8091     // a half by taking the sum of the half with three inputs and subtracting
8092     // the sum of the actual three inputs. The difference is the remaining
8093     // slot.
8094     int ADWord, BDWord;
8095     int &TripleDWord = AToAInputs.size() == 3 ? ADWord : BDWord;
8096     int &OneInputDWord = AToAInputs.size() == 3 ? BDWord : ADWord;
8097     int TripleInputOffset = AToAInputs.size() == 3 ? AOffset : BOffset;
8098     ArrayRef<int> TripleInputs = AToAInputs.size() == 3 ? AToAInputs : BToAInputs;
8099     int OneInput = AToAInputs.size() == 3 ? BToAInputs[0] : AToAInputs[0];
8100     int TripleInputSum = 0 + 1 + 2 + 3 + (4 * TripleInputOffset);
8101     int TripleNonInputIdx =
8102         TripleInputSum - std::accumulate(TripleInputs.begin(), TripleInputs.end(), 0);
8103     TripleDWord = TripleNonInputIdx / 2;
8104
8105     // We use xor with one to compute the adjacent DWord to whichever one the
8106     // OneInput is in.
8107     OneInputDWord = (OneInput / 2) ^ 1;
8108
8109     // Check for one tricky case: We're fixing a 3<-1 or a 1<-3 shuffle for AToA
8110     // and BToA inputs. If there is also such a problem with the BToB and AToB
8111     // inputs, we don't try to fix it necessarily -- we'll recurse and see it in
8112     // the next pass. However, if we have a 2<-2 in the BToB and AToB inputs, it
8113     // is essential that we don't *create* a 3<-1 as then we might oscillate.
8114     if (BToBInputs.size() == 2 && AToBInputs.size() == 2) {
8115       // Compute how many inputs will be flipped by swapping these DWords. We
8116       // need
8117       // to balance this to ensure we don't form a 3-1 shuffle in the other
8118       // half.
8119       int NumFlippedAToBInputs =
8120           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord) +
8121           std::count(AToBInputs.begin(), AToBInputs.end(), 2 * ADWord + 1);
8122       int NumFlippedBToBInputs =
8123           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord) +
8124           std::count(BToBInputs.begin(), BToBInputs.end(), 2 * BDWord + 1);
8125       if ((NumFlippedAToBInputs == 1 &&
8126            (NumFlippedBToBInputs == 0 || NumFlippedBToBInputs == 2)) ||
8127           (NumFlippedBToBInputs == 1 &&
8128            (NumFlippedAToBInputs == 0 || NumFlippedAToBInputs == 2))) {
8129         // We choose whether to fix the A half or B half based on whether that
8130         // half has zero flipped inputs. At zero, we may not be able to fix it
8131         // with that half. We also bias towards fixing the B half because that
8132         // will more commonly be the high half, and we have to bias one way.
8133         auto FixFlippedInputs = [&V, &DL, &Mask, &DAG](int PinnedIdx, int DWord,
8134                                                        ArrayRef<int> Inputs) {
8135           int FixIdx = PinnedIdx ^ 1; // The adjacent slot to the pinned slot.
8136           bool IsFixIdxInput = std::find(Inputs.begin(), Inputs.end(),
8137                                          PinnedIdx ^ 1) != Inputs.end();
8138           // Determine whether the free index is in the flipped dword or the
8139           // unflipped dword based on where the pinned index is. We use this bit
8140           // in an xor to conditionally select the adjacent dword.
8141           int FixFreeIdx = 2 * (DWord ^ (PinnedIdx / 2 == DWord));
8142           bool IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8143                                              FixFreeIdx) != Inputs.end();
8144           if (IsFixIdxInput == IsFixFreeIdxInput)
8145             FixFreeIdx += 1;
8146           IsFixFreeIdxInput = std::find(Inputs.begin(), Inputs.end(),
8147                                         FixFreeIdx) != Inputs.end();
8148           assert(IsFixIdxInput != IsFixFreeIdxInput &&
8149                  "We need to be changing the number of flipped inputs!");
8150           int PSHUFHalfMask[] = {0, 1, 2, 3};
8151           std::swap(PSHUFHalfMask[FixFreeIdx % 4], PSHUFHalfMask[FixIdx % 4]);
8152           V = DAG.getNode(FixIdx < 4 ? X86ISD::PSHUFLW : X86ISD::PSHUFHW, DL,
8153                           MVT::v8i16, V,
8154                           getV4X86ShuffleImm8ForMask(PSHUFHalfMask, DL, DAG));
8155
8156           for (int &M : Mask)
8157             if (M != -1 && M == FixIdx)
8158               M = FixFreeIdx;
8159             else if (M != -1 && M == FixFreeIdx)
8160               M = FixIdx;
8161         };
8162         if (NumFlippedBToBInputs != 0) {
8163           int BPinnedIdx =
8164               BToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8165           FixFlippedInputs(BPinnedIdx, BDWord, BToBInputs);
8166         } else {
8167           assert(NumFlippedAToBInputs != 0 && "Impossible given predicates!");
8168           int APinnedIdx =
8169               AToAInputs.size() == 3 ? TripleNonInputIdx : OneInput;
8170           FixFlippedInputs(APinnedIdx, ADWord, AToBInputs);
8171         }
8172       }
8173     }
8174
8175     int PSHUFDMask[] = {0, 1, 2, 3};
8176     PSHUFDMask[ADWord] = BDWord;
8177     PSHUFDMask[BDWord] = ADWord;
8178     V = DAG.getBitcast(
8179         VT,
8180         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8181                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8182
8183     // Adjust the mask to match the new locations of A and B.
8184     for (int &M : Mask)
8185       if (M != -1 && M/2 == ADWord)
8186         M = 2 * BDWord + M % 2;
8187       else if (M != -1 && M/2 == BDWord)
8188         M = 2 * ADWord + M % 2;
8189
8190     // Recurse back into this routine to re-compute state now that this isn't
8191     // a 3 and 1 problem.
8192     return lowerV8I16GeneralSingleInputVectorShuffle(DL, VT, V, Mask, Subtarget,
8193                                                      DAG);
8194   };
8195   if ((NumLToL == 3 && NumHToL == 1) || (NumLToL == 1 && NumHToL == 3))
8196     return balanceSides(LToLInputs, HToLInputs, HToHInputs, LToHInputs, 0, 4);
8197   else if ((NumHToH == 3 && NumLToH == 1) || (NumHToH == 1 && NumLToH == 3))
8198     return balanceSides(HToHInputs, LToHInputs, LToLInputs, HToLInputs, 4, 0);
8199
8200   // At this point there are at most two inputs to the low and high halves from
8201   // each half. That means the inputs can always be grouped into dwords and
8202   // those dwords can then be moved to the correct half with a dword shuffle.
8203   // We use at most one low and one high word shuffle to collect these paired
8204   // inputs into dwords, and finally a dword shuffle to place them.
8205   int PSHUFLMask[4] = {-1, -1, -1, -1};
8206   int PSHUFHMask[4] = {-1, -1, -1, -1};
8207   int PSHUFDMask[4] = {-1, -1, -1, -1};
8208
8209   // First fix the masks for all the inputs that are staying in their
8210   // original halves. This will then dictate the targets of the cross-half
8211   // shuffles.
8212   auto fixInPlaceInputs =
8213       [&PSHUFDMask](ArrayRef<int> InPlaceInputs, ArrayRef<int> IncomingInputs,
8214                     MutableArrayRef<int> SourceHalfMask,
8215                     MutableArrayRef<int> HalfMask, int HalfOffset) {
8216     if (InPlaceInputs.empty())
8217       return;
8218     if (InPlaceInputs.size() == 1) {
8219       SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8220           InPlaceInputs[0] - HalfOffset;
8221       PSHUFDMask[InPlaceInputs[0] / 2] = InPlaceInputs[0] / 2;
8222       return;
8223     }
8224     if (IncomingInputs.empty()) {
8225       // Just fix all of the in place inputs.
8226       for (int Input : InPlaceInputs) {
8227         SourceHalfMask[Input - HalfOffset] = Input - HalfOffset;
8228         PSHUFDMask[Input / 2] = Input / 2;
8229       }
8230       return;
8231     }
8232
8233     assert(InPlaceInputs.size() == 2 && "Cannot handle 3 or 4 inputs!");
8234     SourceHalfMask[InPlaceInputs[0] - HalfOffset] =
8235         InPlaceInputs[0] - HalfOffset;
8236     // Put the second input next to the first so that they are packed into
8237     // a dword. We find the adjacent index by toggling the low bit.
8238     int AdjIndex = InPlaceInputs[0] ^ 1;
8239     SourceHalfMask[AdjIndex - HalfOffset] = InPlaceInputs[1] - HalfOffset;
8240     std::replace(HalfMask.begin(), HalfMask.end(), InPlaceInputs[1], AdjIndex);
8241     PSHUFDMask[AdjIndex / 2] = AdjIndex / 2;
8242   };
8243   fixInPlaceInputs(LToLInputs, HToLInputs, PSHUFLMask, LoMask, 0);
8244   fixInPlaceInputs(HToHInputs, LToHInputs, PSHUFHMask, HiMask, 4);
8245
8246   // Now gather the cross-half inputs and place them into a free dword of
8247   // their target half.
8248   // FIXME: This operation could almost certainly be simplified dramatically to
8249   // look more like the 3-1 fixing operation.
8250   auto moveInputsToRightHalf = [&PSHUFDMask](
8251       MutableArrayRef<int> IncomingInputs, ArrayRef<int> ExistingInputs,
8252       MutableArrayRef<int> SourceHalfMask, MutableArrayRef<int> HalfMask,
8253       MutableArrayRef<int> FinalSourceHalfMask, int SourceOffset,
8254       int DestOffset) {
8255     auto isWordClobbered = [](ArrayRef<int> SourceHalfMask, int Word) {
8256       return SourceHalfMask[Word] != -1 && SourceHalfMask[Word] != Word;
8257     };
8258     auto isDWordClobbered = [&isWordClobbered](ArrayRef<int> SourceHalfMask,
8259                                                int Word) {
8260       int LowWord = Word & ~1;
8261       int HighWord = Word | 1;
8262       return isWordClobbered(SourceHalfMask, LowWord) ||
8263              isWordClobbered(SourceHalfMask, HighWord);
8264     };
8265
8266     if (IncomingInputs.empty())
8267       return;
8268
8269     if (ExistingInputs.empty()) {
8270       // Map any dwords with inputs from them into the right half.
8271       for (int Input : IncomingInputs) {
8272         // If the source half mask maps over the inputs, turn those into
8273         // swaps and use the swapped lane.
8274         if (isWordClobbered(SourceHalfMask, Input - SourceOffset)) {
8275           if (SourceHalfMask[SourceHalfMask[Input - SourceOffset]] == -1) {
8276             SourceHalfMask[SourceHalfMask[Input - SourceOffset]] =
8277                 Input - SourceOffset;
8278             // We have to swap the uses in our half mask in one sweep.
8279             for (int &M : HalfMask)
8280               if (M == SourceHalfMask[Input - SourceOffset] + SourceOffset)
8281                 M = Input;
8282               else if (M == Input)
8283                 M = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8284           } else {
8285             assert(SourceHalfMask[SourceHalfMask[Input - SourceOffset]] ==
8286                        Input - SourceOffset &&
8287                    "Previous placement doesn't match!");
8288           }
8289           // Note that this correctly re-maps both when we do a swap and when
8290           // we observe the other side of the swap above. We rely on that to
8291           // avoid swapping the members of the input list directly.
8292           Input = SourceHalfMask[Input - SourceOffset] + SourceOffset;
8293         }
8294
8295         // Map the input's dword into the correct half.
8296         if (PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] == -1)
8297           PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] = Input / 2;
8298         else
8299           assert(PSHUFDMask[(Input - SourceOffset + DestOffset) / 2] ==
8300                      Input / 2 &&
8301                  "Previous placement doesn't match!");
8302       }
8303
8304       // And just directly shift any other-half mask elements to be same-half
8305       // as we will have mirrored the dword containing the element into the
8306       // same position within that half.
8307       for (int &M : HalfMask)
8308         if (M >= SourceOffset && M < SourceOffset + 4) {
8309           M = M - SourceOffset + DestOffset;
8310           assert(M >= 0 && "This should never wrap below zero!");
8311         }
8312       return;
8313     }
8314
8315     // Ensure we have the input in a viable dword of its current half. This
8316     // is particularly tricky because the original position may be clobbered
8317     // by inputs being moved and *staying* in that half.
8318     if (IncomingInputs.size() == 1) {
8319       if (isWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8320         int InputFixed = std::find(std::begin(SourceHalfMask),
8321                                    std::end(SourceHalfMask), -1) -
8322                          std::begin(SourceHalfMask) + SourceOffset;
8323         SourceHalfMask[InputFixed - SourceOffset] =
8324             IncomingInputs[0] - SourceOffset;
8325         std::replace(HalfMask.begin(), HalfMask.end(), IncomingInputs[0],
8326                      InputFixed);
8327         IncomingInputs[0] = InputFixed;
8328       }
8329     } else if (IncomingInputs.size() == 2) {
8330       if (IncomingInputs[0] / 2 != IncomingInputs[1] / 2 ||
8331           isDWordClobbered(SourceHalfMask, IncomingInputs[0] - SourceOffset)) {
8332         // We have two non-adjacent or clobbered inputs we need to extract from
8333         // the source half. To do this, we need to map them into some adjacent
8334         // dword slot in the source mask.
8335         int InputsFixed[2] = {IncomingInputs[0] - SourceOffset,
8336                               IncomingInputs[1] - SourceOffset};
8337
8338         // If there is a free slot in the source half mask adjacent to one of
8339         // the inputs, place the other input in it. We use (Index XOR 1) to
8340         // compute an adjacent index.
8341         if (!isWordClobbered(SourceHalfMask, InputsFixed[0]) &&
8342             SourceHalfMask[InputsFixed[0] ^ 1] == -1) {
8343           SourceHalfMask[InputsFixed[0]] = InputsFixed[0];
8344           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8345           InputsFixed[1] = InputsFixed[0] ^ 1;
8346         } else if (!isWordClobbered(SourceHalfMask, InputsFixed[1]) &&
8347                    SourceHalfMask[InputsFixed[1] ^ 1] == -1) {
8348           SourceHalfMask[InputsFixed[1]] = InputsFixed[1];
8349           SourceHalfMask[InputsFixed[1] ^ 1] = InputsFixed[0];
8350           InputsFixed[0] = InputsFixed[1] ^ 1;
8351         } else if (SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] == -1 &&
8352                    SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] == -1) {
8353           // The two inputs are in the same DWord but it is clobbered and the
8354           // adjacent DWord isn't used at all. Move both inputs to the free
8355           // slot.
8356           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1)] = InputsFixed[0];
8357           SourceHalfMask[2 * ((InputsFixed[0] / 2) ^ 1) + 1] = InputsFixed[1];
8358           InputsFixed[0] = 2 * ((InputsFixed[0] / 2) ^ 1);
8359           InputsFixed[1] = 2 * ((InputsFixed[0] / 2) ^ 1) + 1;
8360         } else {
8361           // The only way we hit this point is if there is no clobbering
8362           // (because there are no off-half inputs to this half) and there is no
8363           // free slot adjacent to one of the inputs. In this case, we have to
8364           // swap an input with a non-input.
8365           for (int i = 0; i < 4; ++i)
8366             assert((SourceHalfMask[i] == -1 || SourceHalfMask[i] == i) &&
8367                    "We can't handle any clobbers here!");
8368           assert(InputsFixed[1] != (InputsFixed[0] ^ 1) &&
8369                  "Cannot have adjacent inputs here!");
8370
8371           SourceHalfMask[InputsFixed[0] ^ 1] = InputsFixed[1];
8372           SourceHalfMask[InputsFixed[1]] = InputsFixed[0] ^ 1;
8373
8374           // We also have to update the final source mask in this case because
8375           // it may need to undo the above swap.
8376           for (int &M : FinalSourceHalfMask)
8377             if (M == (InputsFixed[0] ^ 1) + SourceOffset)
8378               M = InputsFixed[1] + SourceOffset;
8379             else if (M == InputsFixed[1] + SourceOffset)
8380               M = (InputsFixed[0] ^ 1) + SourceOffset;
8381
8382           InputsFixed[1] = InputsFixed[0] ^ 1;
8383         }
8384
8385         // Point everything at the fixed inputs.
8386         for (int &M : HalfMask)
8387           if (M == IncomingInputs[0])
8388             M = InputsFixed[0] + SourceOffset;
8389           else if (M == IncomingInputs[1])
8390             M = InputsFixed[1] + SourceOffset;
8391
8392         IncomingInputs[0] = InputsFixed[0] + SourceOffset;
8393         IncomingInputs[1] = InputsFixed[1] + SourceOffset;
8394       }
8395     } else {
8396       llvm_unreachable("Unhandled input size!");
8397     }
8398
8399     // Now hoist the DWord down to the right half.
8400     int FreeDWord = (PSHUFDMask[DestOffset / 2] == -1 ? 0 : 1) + DestOffset / 2;
8401     assert(PSHUFDMask[FreeDWord] == -1 && "DWord not free");
8402     PSHUFDMask[FreeDWord] = IncomingInputs[0] / 2;
8403     for (int &M : HalfMask)
8404       for (int Input : IncomingInputs)
8405         if (M == Input)
8406           M = FreeDWord * 2 + Input % 2;
8407   };
8408   moveInputsToRightHalf(HToLInputs, LToLInputs, PSHUFHMask, LoMask, HiMask,
8409                         /*SourceOffset*/ 4, /*DestOffset*/ 0);
8410   moveInputsToRightHalf(LToHInputs, HToHInputs, PSHUFLMask, HiMask, LoMask,
8411                         /*SourceOffset*/ 0, /*DestOffset*/ 4);
8412
8413   // Now enact all the shuffles we've computed to move the inputs into their
8414   // target half.
8415   if (!isNoopShuffleMask(PSHUFLMask))
8416     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8417                     getV4X86ShuffleImm8ForMask(PSHUFLMask, DL, DAG));
8418   if (!isNoopShuffleMask(PSHUFHMask))
8419     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8420                     getV4X86ShuffleImm8ForMask(PSHUFHMask, DL, DAG));
8421   if (!isNoopShuffleMask(PSHUFDMask))
8422     V = DAG.getBitcast(
8423         VT,
8424         DAG.getNode(X86ISD::PSHUFD, DL, PSHUFDVT, DAG.getBitcast(PSHUFDVT, V),
8425                     getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
8426
8427   // At this point, each half should contain all its inputs, and we can then
8428   // just shuffle them into their final position.
8429   assert(std::count_if(LoMask.begin(), LoMask.end(),
8430                        [](int M) { return M >= 4; }) == 0 &&
8431          "Failed to lift all the high half inputs to the low mask!");
8432   assert(std::count_if(HiMask.begin(), HiMask.end(),
8433                        [](int M) { return M >= 0 && M < 4; }) == 0 &&
8434          "Failed to lift all the low half inputs to the high mask!");
8435
8436   // Do a half shuffle for the low mask.
8437   if (!isNoopShuffleMask(LoMask))
8438     V = DAG.getNode(X86ISD::PSHUFLW, DL, VT, V,
8439                     getV4X86ShuffleImm8ForMask(LoMask, DL, DAG));
8440
8441   // Do a half shuffle with the high mask after shifting its values down.
8442   for (int &M : HiMask)
8443     if (M >= 0)
8444       M -= 4;
8445   if (!isNoopShuffleMask(HiMask))
8446     V = DAG.getNode(X86ISD::PSHUFHW, DL, VT, V,
8447                     getV4X86ShuffleImm8ForMask(HiMask, DL, DAG));
8448
8449   return V;
8450 }
8451
8452 /// \brief Helper to form a PSHUFB-based shuffle+blend.
8453 static SDValue lowerVectorShuffleAsPSHUFB(SDLoc DL, MVT VT, SDValue V1,
8454                                           SDValue V2, ArrayRef<int> Mask,
8455                                           SelectionDAG &DAG, bool &V1InUse,
8456                                           bool &V2InUse) {
8457   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
8458   SDValue V1Mask[16];
8459   SDValue V2Mask[16];
8460   V1InUse = false;
8461   V2InUse = false;
8462
8463   int Size = Mask.size();
8464   int Scale = 16 / Size;
8465   for (int i = 0; i < 16; ++i) {
8466     if (Mask[i / Scale] == -1) {
8467       V1Mask[i] = V2Mask[i] = DAG.getUNDEF(MVT::i8);
8468     } else {
8469       const int ZeroMask = 0x80;
8470       int V1Idx = Mask[i / Scale] < Size ? Mask[i / Scale] * Scale + i % Scale
8471                                           : ZeroMask;
8472       int V2Idx = Mask[i / Scale] < Size
8473                       ? ZeroMask
8474                       : (Mask[i / Scale] - Size) * Scale + i % Scale;
8475       if (Zeroable[i / Scale])
8476         V1Idx = V2Idx = ZeroMask;
8477       V1Mask[i] = DAG.getConstant(V1Idx, DL, MVT::i8);
8478       V2Mask[i] = DAG.getConstant(V2Idx, DL, MVT::i8);
8479       V1InUse |= (ZeroMask != V1Idx);
8480       V2InUse |= (ZeroMask != V2Idx);
8481     }
8482   }
8483
8484   if (V1InUse)
8485     V1 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8486                      DAG.getBitcast(MVT::v16i8, V1),
8487                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V1Mask));
8488   if (V2InUse)
8489     V2 = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v16i8,
8490                      DAG.getBitcast(MVT::v16i8, V2),
8491                      DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v16i8, V2Mask));
8492
8493   // If we need shuffled inputs from both, blend the two.
8494   SDValue V;
8495   if (V1InUse && V2InUse)
8496     V = DAG.getNode(ISD::OR, DL, MVT::v16i8, V1, V2);
8497   else
8498     V = V1InUse ? V1 : V2;
8499
8500   // Cast the result back to the correct type.
8501   return DAG.getBitcast(VT, V);
8502 }
8503
8504 /// \brief Generic lowering of 8-lane i16 shuffles.
8505 ///
8506 /// This handles both single-input shuffles and combined shuffle/blends with
8507 /// two inputs. The single input shuffles are immediately delegated to
8508 /// a dedicated lowering routine.
8509 ///
8510 /// The blends are lowered in one of three fundamental ways. If there are few
8511 /// enough inputs, it delegates to a basic UNPCK-based strategy. If the shuffle
8512 /// of the input is significantly cheaper when lowered as an interleaving of
8513 /// the two inputs, try to interleave them. Otherwise, blend the low and high
8514 /// halves of the inputs separately (making them have relatively few inputs)
8515 /// and then concatenate them.
8516 static SDValue lowerV8I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8517                                        const X86Subtarget *Subtarget,
8518                                        SelectionDAG &DAG) {
8519   SDLoc DL(Op);
8520   assert(Op.getSimpleValueType() == MVT::v8i16 && "Bad shuffle type!");
8521   assert(V1.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8522   assert(V2.getSimpleValueType() == MVT::v8i16 && "Bad operand type!");
8523   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8524   ArrayRef<int> OrigMask = SVOp->getMask();
8525   int MaskStorage[8] = {OrigMask[0], OrigMask[1], OrigMask[2], OrigMask[3],
8526                         OrigMask[4], OrigMask[5], OrigMask[6], OrigMask[7]};
8527   MutableArrayRef<int> Mask(MaskStorage);
8528
8529   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
8530
8531   // Whenever we can lower this as a zext, that instruction is strictly faster
8532   // than any alternative.
8533   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8534           DL, MVT::v8i16, V1, V2, OrigMask, Subtarget, DAG))
8535     return ZExt;
8536
8537   auto isV1 = [](int M) { return M >= 0 && M < 8; };
8538   (void)isV1;
8539   auto isV2 = [](int M) { return M >= 8; };
8540
8541   int NumV2Inputs = std::count_if(Mask.begin(), Mask.end(), isV2);
8542
8543   if (NumV2Inputs == 0) {
8544     // Check for being able to broadcast a single element.
8545     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i16, V1,
8546                                                           Mask, Subtarget, DAG))
8547       return Broadcast;
8548
8549     // Try to use shift instructions.
8550     if (SDValue Shift =
8551             lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V1, Mask, DAG))
8552       return Shift;
8553
8554     // Use dedicated unpack instructions for masks that match their pattern.
8555     if (isShuffleEquivalent(V1, V1, Mask, {0, 0, 1, 1, 2, 2, 3, 3}))
8556       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V1);
8557     if (isShuffleEquivalent(V1, V1, Mask, {4, 4, 5, 5, 6, 6, 7, 7}))
8558       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V1);
8559
8560     // Try to use byte rotation instructions.
8561     if (SDValue Rotate = lowerVectorShuffleAsByteRotate(DL, MVT::v8i16, V1, V1,
8562                                                         Mask, Subtarget, DAG))
8563       return Rotate;
8564
8565     return lowerV8I16GeneralSingleInputVectorShuffle(DL, MVT::v8i16, V1, Mask,
8566                                                      Subtarget, DAG);
8567   }
8568
8569   assert(std::any_of(Mask.begin(), Mask.end(), isV1) &&
8570          "All single-input shuffles should be canonicalized to be V1-input "
8571          "shuffles.");
8572
8573   // Try to use shift instructions.
8574   if (SDValue Shift =
8575           lowerVectorShuffleAsShift(DL, MVT::v8i16, V1, V2, Mask, DAG))
8576     return Shift;
8577
8578   // There are special ways we can lower some single-element blends.
8579   if (NumV2Inputs == 1)
8580     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v8i16, V1, V2,
8581                                                          Mask, Subtarget, DAG))
8582       return V;
8583
8584   // We have different paths for blend lowering, but they all must use the
8585   // *exact* same predicate.
8586   bool IsBlendSupported = Subtarget->hasSSE41();
8587   if (IsBlendSupported)
8588     if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i16, V1, V2, Mask,
8589                                                   Subtarget, DAG))
8590       return Blend;
8591
8592   if (SDValue Masked =
8593           lowerVectorShuffleAsBitMask(DL, MVT::v8i16, V1, V2, Mask, DAG))
8594     return Masked;
8595
8596   // Use dedicated unpack instructions for masks that match their pattern.
8597   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 2, 10, 3, 11}))
8598     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i16, V1, V2);
8599   if (isShuffleEquivalent(V1, V2, Mask, {4, 12, 5, 13, 6, 14, 7, 15}))
8600     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i16, V1, V2);
8601
8602   // Try to use byte rotation instructions.
8603   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8604           DL, MVT::v8i16, V1, V2, Mask, Subtarget, DAG))
8605     return Rotate;
8606
8607   if (SDValue BitBlend =
8608           lowerVectorShuffleAsBitBlend(DL, MVT::v8i16, V1, V2, Mask, DAG))
8609     return BitBlend;
8610
8611   if (SDValue Unpack =
8612           lowerVectorShuffleAsUnpack(DL, MVT::v8i16, V1, V2, Mask, DAG))
8613     return Unpack;
8614
8615   // If we can't directly blend but can use PSHUFB, that will be better as it
8616   // can both shuffle and set up the inefficient blend.
8617   if (!IsBlendSupported && Subtarget->hasSSSE3()) {
8618     bool V1InUse, V2InUse;
8619     return lowerVectorShuffleAsPSHUFB(DL, MVT::v8i16, V1, V2, Mask, DAG,
8620                                       V1InUse, V2InUse);
8621   }
8622
8623   // We can always bit-blend if we have to so the fallback strategy is to
8624   // decompose into single-input permutes and blends.
8625   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i16, V1, V2,
8626                                                       Mask, DAG);
8627 }
8628
8629 /// \brief Check whether a compaction lowering can be done by dropping even
8630 /// elements and compute how many times even elements must be dropped.
8631 ///
8632 /// This handles shuffles which take every Nth element where N is a power of
8633 /// two. Example shuffle masks:
8634 ///
8635 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14,  0,  2,  4,  6,  8, 10, 12, 14
8636 ///  N = 1:  0,  2,  4,  6,  8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30
8637 ///  N = 2:  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12,  0,  4,  8, 12
8638 ///  N = 2:  0,  4,  8, 12, 16, 20, 24, 28,  0,  4,  8, 12, 16, 20, 24, 28
8639 ///  N = 3:  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8,  0,  8
8640 ///  N = 3:  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24,  0,  8, 16, 24
8641 ///
8642 /// Any of these lanes can of course be undef.
8643 ///
8644 /// This routine only supports N <= 3.
8645 /// FIXME: Evaluate whether either AVX or AVX-512 have any opportunities here
8646 /// for larger N.
8647 ///
8648 /// \returns N above, or the number of times even elements must be dropped if
8649 /// there is such a number. Otherwise returns zero.
8650 static int canLowerByDroppingEvenElements(ArrayRef<int> Mask) {
8651   // Figure out whether we're looping over two inputs or just one.
8652   bool IsSingleInput = isSingleInputShuffleMask(Mask);
8653
8654   // The modulus for the shuffle vector entries is based on whether this is
8655   // a single input or not.
8656   int ShuffleModulus = Mask.size() * (IsSingleInput ? 1 : 2);
8657   assert(isPowerOf2_32((uint32_t)ShuffleModulus) &&
8658          "We should only be called with masks with a power-of-2 size!");
8659
8660   uint64_t ModMask = (uint64_t)ShuffleModulus - 1;
8661
8662   // We track whether the input is viable for all power-of-2 strides 2^1, 2^2,
8663   // and 2^3 simultaneously. This is because we may have ambiguity with
8664   // partially undef inputs.
8665   bool ViableForN[3] = {true, true, true};
8666
8667   for (int i = 0, e = Mask.size(); i < e; ++i) {
8668     // Ignore undef lanes, we'll optimistically collapse them to the pattern we
8669     // want.
8670     if (Mask[i] == -1)
8671       continue;
8672
8673     bool IsAnyViable = false;
8674     for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8675       if (ViableForN[j]) {
8676         uint64_t N = j + 1;
8677
8678         // The shuffle mask must be equal to (i * 2^N) % M.
8679         if ((uint64_t)Mask[i] == (((uint64_t)i << N) & ModMask))
8680           IsAnyViable = true;
8681         else
8682           ViableForN[j] = false;
8683       }
8684     // Early exit if we exhaust the possible powers of two.
8685     if (!IsAnyViable)
8686       break;
8687   }
8688
8689   for (unsigned j = 0; j != array_lengthof(ViableForN); ++j)
8690     if (ViableForN[j])
8691       return j + 1;
8692
8693   // Return 0 as there is no viable power of two.
8694   return 0;
8695 }
8696
8697 /// \brief Generic lowering of v16i8 shuffles.
8698 ///
8699 /// This is a hybrid strategy to lower v16i8 vectors. It first attempts to
8700 /// detect any complexity reducing interleaving. If that doesn't help, it uses
8701 /// UNPCK to spread the i8 elements across two i16-element vectors, and uses
8702 /// the existing lowering for v8i16 blends on each half, finally PACK-ing them
8703 /// back together.
8704 static SDValue lowerV16I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8705                                        const X86Subtarget *Subtarget,
8706                                        SelectionDAG &DAG) {
8707   SDLoc DL(Op);
8708   assert(Op.getSimpleValueType() == MVT::v16i8 && "Bad shuffle type!");
8709   assert(V1.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8710   assert(V2.getSimpleValueType() == MVT::v16i8 && "Bad operand type!");
8711   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
8712   ArrayRef<int> Mask = SVOp->getMask();
8713   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
8714
8715   // Try to use shift instructions.
8716   if (SDValue Shift =
8717           lowerVectorShuffleAsShift(DL, MVT::v16i8, V1, V2, Mask, DAG))
8718     return Shift;
8719
8720   // Try to use byte rotation instructions.
8721   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
8722           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8723     return Rotate;
8724
8725   // Try to use a zext lowering.
8726   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(
8727           DL, MVT::v16i8, V1, V2, Mask, Subtarget, DAG))
8728     return ZExt;
8729
8730   int NumV2Elements =
8731       std::count_if(Mask.begin(), Mask.end(), [](int M) { return M >= 16; });
8732
8733   // For single-input shuffles, there are some nicer lowering tricks we can use.
8734   if (NumV2Elements == 0) {
8735     // Check for being able to broadcast a single element.
8736     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i8, V1,
8737                                                           Mask, Subtarget, DAG))
8738       return Broadcast;
8739
8740     // Check whether we can widen this to an i16 shuffle by duplicating bytes.
8741     // Notably, this handles splat and partial-splat shuffles more efficiently.
8742     // However, it only makes sense if the pre-duplication shuffle simplifies
8743     // things significantly. Currently, this means we need to be able to
8744     // express the pre-duplication shuffle as an i16 shuffle.
8745     //
8746     // FIXME: We should check for other patterns which can be widened into an
8747     // i16 shuffle as well.
8748     auto canWidenViaDuplication = [](ArrayRef<int> Mask) {
8749       for (int i = 0; i < 16; i += 2)
8750         if (Mask[i] != -1 && Mask[i + 1] != -1 && Mask[i] != Mask[i + 1])
8751           return false;
8752
8753       return true;
8754     };
8755     auto tryToWidenViaDuplication = [&]() -> SDValue {
8756       if (!canWidenViaDuplication(Mask))
8757         return SDValue();
8758       SmallVector<int, 4> LoInputs;
8759       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(LoInputs),
8760                    [](int M) { return M >= 0 && M < 8; });
8761       std::sort(LoInputs.begin(), LoInputs.end());
8762       LoInputs.erase(std::unique(LoInputs.begin(), LoInputs.end()),
8763                      LoInputs.end());
8764       SmallVector<int, 4> HiInputs;
8765       std::copy_if(Mask.begin(), Mask.end(), std::back_inserter(HiInputs),
8766                    [](int M) { return M >= 8; });
8767       std::sort(HiInputs.begin(), HiInputs.end());
8768       HiInputs.erase(std::unique(HiInputs.begin(), HiInputs.end()),
8769                      HiInputs.end());
8770
8771       bool TargetLo = LoInputs.size() >= HiInputs.size();
8772       ArrayRef<int> InPlaceInputs = TargetLo ? LoInputs : HiInputs;
8773       ArrayRef<int> MovingInputs = TargetLo ? HiInputs : LoInputs;
8774
8775       int PreDupI16Shuffle[] = {-1, -1, -1, -1, -1, -1, -1, -1};
8776       SmallDenseMap<int, int, 8> LaneMap;
8777       for (int I : InPlaceInputs) {
8778         PreDupI16Shuffle[I/2] = I/2;
8779         LaneMap[I] = I;
8780       }
8781       int j = TargetLo ? 0 : 4, je = j + 4;
8782       for (int i = 0, ie = MovingInputs.size(); i < ie; ++i) {
8783         // Check if j is already a shuffle of this input. This happens when
8784         // there are two adjacent bytes after we move the low one.
8785         if (PreDupI16Shuffle[j] != MovingInputs[i] / 2) {
8786           // If we haven't yet mapped the input, search for a slot into which
8787           // we can map it.
8788           while (j < je && PreDupI16Shuffle[j] != -1)
8789             ++j;
8790
8791           if (j == je)
8792             // We can't place the inputs into a single half with a simple i16 shuffle, so bail.
8793             return SDValue();
8794
8795           // Map this input with the i16 shuffle.
8796           PreDupI16Shuffle[j] = MovingInputs[i] / 2;
8797         }
8798
8799         // Update the lane map based on the mapping we ended up with.
8800         LaneMap[MovingInputs[i]] = 2 * j + MovingInputs[i] % 2;
8801       }
8802       V1 = DAG.getBitcast(
8803           MVT::v16i8,
8804           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8805                                DAG.getUNDEF(MVT::v8i16), PreDupI16Shuffle));
8806
8807       // Unpack the bytes to form the i16s that will be shuffled into place.
8808       V1 = DAG.getNode(TargetLo ? X86ISD::UNPCKL : X86ISD::UNPCKH, DL,
8809                        MVT::v16i8, V1, V1);
8810
8811       int PostDupI16Shuffle[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8812       for (int i = 0; i < 16; ++i)
8813         if (Mask[i] != -1) {
8814           int MappedMask = LaneMap[Mask[i]] - (TargetLo ? 0 : 8);
8815           assert(MappedMask < 8 && "Invalid v8 shuffle mask!");
8816           if (PostDupI16Shuffle[i / 2] == -1)
8817             PostDupI16Shuffle[i / 2] = MappedMask;
8818           else
8819             assert(PostDupI16Shuffle[i / 2] == MappedMask &&
8820                    "Conflicting entrties in the original shuffle!");
8821         }
8822       return DAG.getBitcast(
8823           MVT::v16i8,
8824           DAG.getVectorShuffle(MVT::v8i16, DL, DAG.getBitcast(MVT::v8i16, V1),
8825                                DAG.getUNDEF(MVT::v8i16), PostDupI16Shuffle));
8826     };
8827     if (SDValue V = tryToWidenViaDuplication())
8828       return V;
8829   }
8830
8831   // Use dedicated unpack instructions for masks that match their pattern.
8832   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8833                                          0, 16, 1, 17, 2, 18, 3, 19,
8834                                          // High half.
8835                                          4, 20, 5, 21, 6, 22, 7, 23}))
8836     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V1, V2);
8837   if (isShuffleEquivalent(V1, V2, Mask, {// Low half.
8838                                          8, 24, 9, 25, 10, 26, 11, 27,
8839                                          // High half.
8840                                          12, 28, 13, 29, 14, 30, 15, 31}))
8841     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V1, V2);
8842
8843   // Check for SSSE3 which lets us lower all v16i8 shuffles much more directly
8844   // with PSHUFB. It is important to do this before we attempt to generate any
8845   // blends but after all of the single-input lowerings. If the single input
8846   // lowerings can find an instruction sequence that is faster than a PSHUFB, we
8847   // want to preserve that and we can DAG combine any longer sequences into
8848   // a PSHUFB in the end. But once we start blending from multiple inputs,
8849   // the complexity of DAG combining bad patterns back into PSHUFB is too high,
8850   // and there are *very* few patterns that would actually be faster than the
8851   // PSHUFB approach because of its ability to zero lanes.
8852   //
8853   // FIXME: The only exceptions to the above are blends which are exact
8854   // interleavings with direct instructions supporting them. We currently don't
8855   // handle those well here.
8856   if (Subtarget->hasSSSE3()) {
8857     bool V1InUse = false;
8858     bool V2InUse = false;
8859
8860     SDValue PSHUFB = lowerVectorShuffleAsPSHUFB(DL, MVT::v16i8, V1, V2, Mask,
8861                                                 DAG, V1InUse, V2InUse);
8862
8863     // If both V1 and V2 are in use and we can use a direct blend or an unpack,
8864     // do so. This avoids using them to handle blends-with-zero which is
8865     // important as a single pshufb is significantly faster for that.
8866     if (V1InUse && V2InUse) {
8867       if (Subtarget->hasSSE41())
8868         if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i8, V1, V2,
8869                                                       Mask, Subtarget, DAG))
8870           return Blend;
8871
8872       // We can use an unpack to do the blending rather than an or in some
8873       // cases. Even though the or may be (very minorly) more efficient, we
8874       // preference this lowering because there are common cases where part of
8875       // the complexity of the shuffles goes away when we do the final blend as
8876       // an unpack.
8877       // FIXME: It might be worth trying to detect if the unpack-feeding
8878       // shuffles will both be pshufb, in which case we shouldn't bother with
8879       // this.
8880       if (SDValue Unpack =
8881               lowerVectorShuffleAsUnpack(DL, MVT::v16i8, V1, V2, Mask, DAG))
8882         return Unpack;
8883     }
8884
8885     return PSHUFB;
8886   }
8887
8888   // There are special ways we can lower some single-element blends.
8889   if (NumV2Elements == 1)
8890     if (SDValue V = lowerVectorShuffleAsElementInsertion(DL, MVT::v16i8, V1, V2,
8891                                                          Mask, Subtarget, DAG))
8892       return V;
8893
8894   if (SDValue BitBlend =
8895           lowerVectorShuffleAsBitBlend(DL, MVT::v16i8, V1, V2, Mask, DAG))
8896     return BitBlend;
8897
8898   // Check whether a compaction lowering can be done. This handles shuffles
8899   // which take every Nth element for some even N. See the helper function for
8900   // details.
8901   //
8902   // We special case these as they can be particularly efficiently handled with
8903   // the PACKUSB instruction on x86 and they show up in common patterns of
8904   // rearranging bytes to truncate wide elements.
8905   if (int NumEvenDrops = canLowerByDroppingEvenElements(Mask)) {
8906     // NumEvenDrops is the power of two stride of the elements. Another way of
8907     // thinking about it is that we need to drop the even elements this many
8908     // times to get the original input.
8909     bool IsSingleInput = isSingleInputShuffleMask(Mask);
8910
8911     // First we need to zero all the dropped bytes.
8912     assert(NumEvenDrops <= 3 &&
8913            "No support for dropping even elements more than 3 times.");
8914     // We use the mask type to pick which bytes are preserved based on how many
8915     // elements are dropped.
8916     MVT MaskVTs[] = { MVT::v8i16, MVT::v4i32, MVT::v2i64 };
8917     SDValue ByteClearMask = DAG.getBitcast(
8918         MVT::v16i8, DAG.getConstant(0xFF, DL, MaskVTs[NumEvenDrops - 1]));
8919     V1 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V1, ByteClearMask);
8920     if (!IsSingleInput)
8921       V2 = DAG.getNode(ISD::AND, DL, MVT::v16i8, V2, ByteClearMask);
8922
8923     // Now pack things back together.
8924     V1 = DAG.getBitcast(MVT::v8i16, V1);
8925     V2 = IsSingleInput ? V1 : DAG.getBitcast(MVT::v8i16, V2);
8926     SDValue Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, V1, V2);
8927     for (int i = 1; i < NumEvenDrops; ++i) {
8928       Result = DAG.getBitcast(MVT::v8i16, Result);
8929       Result = DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, Result, Result);
8930     }
8931
8932     return Result;
8933   }
8934
8935   // Handle multi-input cases by blending single-input shuffles.
8936   if (NumV2Elements > 0)
8937     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v16i8, V1, V2,
8938                                                       Mask, DAG);
8939
8940   // The fallback path for single-input shuffles widens this into two v8i16
8941   // vectors with unpacks, shuffles those, and then pulls them back together
8942   // with a pack.
8943   SDValue V = V1;
8944
8945   int LoBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8946   int HiBlendMask[8] = {-1, -1, -1, -1, -1, -1, -1, -1};
8947   for (int i = 0; i < 16; ++i)
8948     if (Mask[i] >= 0)
8949       (i < 8 ? LoBlendMask[i] : HiBlendMask[i % 8]) = Mask[i];
8950
8951   SDValue Zero = getZeroVector(MVT::v8i16, Subtarget, DAG, DL);
8952
8953   SDValue VLoHalf, VHiHalf;
8954   // Check if any of the odd lanes in the v16i8 are used. If not, we can mask
8955   // them out and avoid using UNPCK{L,H} to extract the elements of V as
8956   // i16s.
8957   if (std::none_of(std::begin(LoBlendMask), std::end(LoBlendMask),
8958                    [](int M) { return M >= 0 && M % 2 == 1; }) &&
8959       std::none_of(std::begin(HiBlendMask), std::end(HiBlendMask),
8960                    [](int M) { return M >= 0 && M % 2 == 1; })) {
8961     // Use a mask to drop the high bytes.
8962     VLoHalf = DAG.getBitcast(MVT::v8i16, V);
8963     VLoHalf = DAG.getNode(ISD::AND, DL, MVT::v8i16, VLoHalf,
8964                      DAG.getConstant(0x00FF, DL, MVT::v8i16));
8965
8966     // This will be a single vector shuffle instead of a blend so nuke VHiHalf.
8967     VHiHalf = DAG.getUNDEF(MVT::v8i16);
8968
8969     // Squash the masks to point directly into VLoHalf.
8970     for (int &M : LoBlendMask)
8971       if (M >= 0)
8972         M /= 2;
8973     for (int &M : HiBlendMask)
8974       if (M >= 0)
8975         M /= 2;
8976   } else {
8977     // Otherwise just unpack the low half of V into VLoHalf and the high half into
8978     // VHiHalf so that we can blend them as i16s.
8979     VLoHalf = DAG.getBitcast(
8980         MVT::v8i16, DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i8, V, Zero));
8981     VHiHalf = DAG.getBitcast(
8982         MVT::v8i16, DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i8, V, Zero));
8983   }
8984
8985   SDValue LoV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, LoBlendMask);
8986   SDValue HiV = DAG.getVectorShuffle(MVT::v8i16, DL, VLoHalf, VHiHalf, HiBlendMask);
8987
8988   return DAG.getNode(X86ISD::PACKUS, DL, MVT::v16i8, LoV, HiV);
8989 }
8990
8991 /// \brief Dispatching routine to lower various 128-bit x86 vector shuffles.
8992 ///
8993 /// This routine breaks down the specific type of 128-bit shuffle and
8994 /// dispatches to the lowering routines accordingly.
8995 static SDValue lower128BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
8996                                         MVT VT, const X86Subtarget *Subtarget,
8997                                         SelectionDAG &DAG) {
8998   switch (VT.SimpleTy) {
8999   case MVT::v2i64:
9000     return lowerV2I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9001   case MVT::v2f64:
9002     return lowerV2F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
9003   case MVT::v4i32:
9004     return lowerV4I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9005   case MVT::v4f32:
9006     return lowerV4F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
9007   case MVT::v8i16:
9008     return lowerV8I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
9009   case MVT::v16i8:
9010     return lowerV16I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
9011
9012   default:
9013     llvm_unreachable("Unimplemented!");
9014   }
9015 }
9016
9017 /// \brief Helper function to test whether a shuffle mask could be
9018 /// simplified by widening the elements being shuffled.
9019 ///
9020 /// Appends the mask for wider elements in WidenedMask if valid. Otherwise
9021 /// leaves it in an unspecified state.
9022 ///
9023 /// NOTE: This must handle normal vector shuffle masks and *target* vector
9024 /// shuffle masks. The latter have the special property of a '-2' representing
9025 /// a zero-ed lane of a vector.
9026 static bool canWidenShuffleElements(ArrayRef<int> Mask,
9027                                     SmallVectorImpl<int> &WidenedMask) {
9028   for (int i = 0, Size = Mask.size(); i < Size; i += 2) {
9029     // If both elements are undef, its trivial.
9030     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] == SM_SentinelUndef) {
9031       WidenedMask.push_back(SM_SentinelUndef);
9032       continue;
9033     }
9034
9035     // Check for an undef mask and a mask value properly aligned to fit with
9036     // a pair of values. If we find such a case, use the non-undef mask's value.
9037     if (Mask[i] == SM_SentinelUndef && Mask[i + 1] >= 0 && Mask[i + 1] % 2 == 1) {
9038       WidenedMask.push_back(Mask[i + 1] / 2);
9039       continue;
9040     }
9041     if (Mask[i + 1] == SM_SentinelUndef && Mask[i] >= 0 && Mask[i] % 2 == 0) {
9042       WidenedMask.push_back(Mask[i] / 2);
9043       continue;
9044     }
9045
9046     // When zeroing, we need to spread the zeroing across both lanes to widen.
9047     if (Mask[i] == SM_SentinelZero || Mask[i + 1] == SM_SentinelZero) {
9048       if ((Mask[i] == SM_SentinelZero || Mask[i] == SM_SentinelUndef) &&
9049           (Mask[i + 1] == SM_SentinelZero || Mask[i + 1] == SM_SentinelUndef)) {
9050         WidenedMask.push_back(SM_SentinelZero);
9051         continue;
9052       }
9053       return false;
9054     }
9055
9056     // Finally check if the two mask values are adjacent and aligned with
9057     // a pair.
9058     if (Mask[i] != SM_SentinelUndef && Mask[i] % 2 == 0 && Mask[i] + 1 == Mask[i + 1]) {
9059       WidenedMask.push_back(Mask[i] / 2);
9060       continue;
9061     }
9062
9063     // Otherwise we can't safely widen the elements used in this shuffle.
9064     return false;
9065   }
9066   assert(WidenedMask.size() == Mask.size() / 2 &&
9067          "Incorrect size of mask after widening the elements!");
9068
9069   return true;
9070 }
9071
9072 /// \brief Generic routine to split vector shuffle into half-sized shuffles.
9073 ///
9074 /// This routine just extracts two subvectors, shuffles them independently, and
9075 /// then concatenates them back together. This should work effectively with all
9076 /// AVX vector shuffle types.
9077 static SDValue splitAndLowerVectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9078                                           SDValue V2, ArrayRef<int> Mask,
9079                                           SelectionDAG &DAG) {
9080   assert(VT.getSizeInBits() >= 256 &&
9081          "Only for 256-bit or wider vector shuffles!");
9082   assert(V1.getSimpleValueType() == VT && "Bad operand type!");
9083   assert(V2.getSimpleValueType() == VT && "Bad operand type!");
9084
9085   ArrayRef<int> LoMask = Mask.slice(0, Mask.size() / 2);
9086   ArrayRef<int> HiMask = Mask.slice(Mask.size() / 2);
9087
9088   int NumElements = VT.getVectorNumElements();
9089   int SplitNumElements = NumElements / 2;
9090   MVT ScalarVT = VT.getScalarType();
9091   MVT SplitVT = MVT::getVectorVT(ScalarVT, NumElements / 2);
9092
9093   // Rather than splitting build-vectors, just build two narrower build
9094   // vectors. This helps shuffling with splats and zeros.
9095   auto SplitVector = [&](SDValue V) {
9096     while (V.getOpcode() == ISD::BITCAST)
9097       V = V->getOperand(0);
9098
9099     MVT OrigVT = V.getSimpleValueType();
9100     int OrigNumElements = OrigVT.getVectorNumElements();
9101     int OrigSplitNumElements = OrigNumElements / 2;
9102     MVT OrigScalarVT = OrigVT.getScalarType();
9103     MVT OrigSplitVT = MVT::getVectorVT(OrigScalarVT, OrigNumElements / 2);
9104
9105     SDValue LoV, HiV;
9106
9107     auto *BV = dyn_cast<BuildVectorSDNode>(V);
9108     if (!BV) {
9109       LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9110                         DAG.getIntPtrConstant(0, DL));
9111       HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigSplitVT, V,
9112                         DAG.getIntPtrConstant(OrigSplitNumElements, DL));
9113     } else {
9114
9115       SmallVector<SDValue, 16> LoOps, HiOps;
9116       for (int i = 0; i < OrigSplitNumElements; ++i) {
9117         LoOps.push_back(BV->getOperand(i));
9118         HiOps.push_back(BV->getOperand(i + OrigSplitNumElements));
9119       }
9120       LoV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, LoOps);
9121       HiV = DAG.getNode(ISD::BUILD_VECTOR, DL, OrigSplitVT, HiOps);
9122     }
9123     return std::make_pair(DAG.getBitcast(SplitVT, LoV),
9124                           DAG.getBitcast(SplitVT, HiV));
9125   };
9126
9127   SDValue LoV1, HiV1, LoV2, HiV2;
9128   std::tie(LoV1, HiV1) = SplitVector(V1);
9129   std::tie(LoV2, HiV2) = SplitVector(V2);
9130
9131   // Now create two 4-way blends of these half-width vectors.
9132   auto HalfBlend = [&](ArrayRef<int> HalfMask) {
9133     bool UseLoV1 = false, UseHiV1 = false, UseLoV2 = false, UseHiV2 = false;
9134     SmallVector<int, 32> V1BlendMask, V2BlendMask, BlendMask;
9135     for (int i = 0; i < SplitNumElements; ++i) {
9136       int M = HalfMask[i];
9137       if (M >= NumElements) {
9138         if (M >= NumElements + SplitNumElements)
9139           UseHiV2 = true;
9140         else
9141           UseLoV2 = true;
9142         V2BlendMask.push_back(M - NumElements);
9143         V1BlendMask.push_back(-1);
9144         BlendMask.push_back(SplitNumElements + i);
9145       } else if (M >= 0) {
9146         if (M >= SplitNumElements)
9147           UseHiV1 = true;
9148         else
9149           UseLoV1 = true;
9150         V2BlendMask.push_back(-1);
9151         V1BlendMask.push_back(M);
9152         BlendMask.push_back(i);
9153       } else {
9154         V2BlendMask.push_back(-1);
9155         V1BlendMask.push_back(-1);
9156         BlendMask.push_back(-1);
9157       }
9158     }
9159
9160     // Because the lowering happens after all combining takes place, we need to
9161     // manually combine these blend masks as much as possible so that we create
9162     // a minimal number of high-level vector shuffle nodes.
9163
9164     // First try just blending the halves of V1 or V2.
9165     if (!UseLoV1 && !UseHiV1 && !UseLoV2 && !UseHiV2)
9166       return DAG.getUNDEF(SplitVT);
9167     if (!UseLoV2 && !UseHiV2)
9168       return DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9169     if (!UseLoV1 && !UseHiV1)
9170       return DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9171
9172     SDValue V1Blend, V2Blend;
9173     if (UseLoV1 && UseHiV1) {
9174       V1Blend =
9175         DAG.getVectorShuffle(SplitVT, DL, LoV1, HiV1, V1BlendMask);
9176     } else {
9177       // We only use half of V1 so map the usage down into the final blend mask.
9178       V1Blend = UseLoV1 ? LoV1 : HiV1;
9179       for (int i = 0; i < SplitNumElements; ++i)
9180         if (BlendMask[i] >= 0 && BlendMask[i] < SplitNumElements)
9181           BlendMask[i] = V1BlendMask[i] - (UseLoV1 ? 0 : SplitNumElements);
9182     }
9183     if (UseLoV2 && UseHiV2) {
9184       V2Blend =
9185         DAG.getVectorShuffle(SplitVT, DL, LoV2, HiV2, V2BlendMask);
9186     } else {
9187       // We only use half of V2 so map the usage down into the final blend mask.
9188       V2Blend = UseLoV2 ? LoV2 : HiV2;
9189       for (int i = 0; i < SplitNumElements; ++i)
9190         if (BlendMask[i] >= SplitNumElements)
9191           BlendMask[i] = V2BlendMask[i] + (UseLoV2 ? SplitNumElements : 0);
9192     }
9193     return DAG.getVectorShuffle(SplitVT, DL, V1Blend, V2Blend, BlendMask);
9194   };
9195   SDValue Lo = HalfBlend(LoMask);
9196   SDValue Hi = HalfBlend(HiMask);
9197   return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
9198 }
9199
9200 /// \brief Either split a vector in halves or decompose the shuffles and the
9201 /// blend.
9202 ///
9203 /// This is provided as a good fallback for many lowerings of non-single-input
9204 /// shuffles with more than one 128-bit lane. In those cases, we want to select
9205 /// between splitting the shuffle into 128-bit components and stitching those
9206 /// back together vs. extracting the single-input shuffles and blending those
9207 /// results.
9208 static SDValue lowerVectorShuffleAsSplitOrBlend(SDLoc DL, MVT VT, SDValue V1,
9209                                                 SDValue V2, ArrayRef<int> Mask,
9210                                                 SelectionDAG &DAG) {
9211   assert(!isSingleInputShuffleMask(Mask) && "This routine must not be used to "
9212                                             "lower single-input shuffles as it "
9213                                             "could then recurse on itself.");
9214   int Size = Mask.size();
9215
9216   // If this can be modeled as a broadcast of two elements followed by a blend,
9217   // prefer that lowering. This is especially important because broadcasts can
9218   // often fold with memory operands.
9219   auto DoBothBroadcast = [&] {
9220     int V1BroadcastIdx = -1, V2BroadcastIdx = -1;
9221     for (int M : Mask)
9222       if (M >= Size) {
9223         if (V2BroadcastIdx == -1)
9224           V2BroadcastIdx = M - Size;
9225         else if (M - Size != V2BroadcastIdx)
9226           return false;
9227       } else if (M >= 0) {
9228         if (V1BroadcastIdx == -1)
9229           V1BroadcastIdx = M;
9230         else if (M != V1BroadcastIdx)
9231           return false;
9232       }
9233     return true;
9234   };
9235   if (DoBothBroadcast())
9236     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask,
9237                                                       DAG);
9238
9239   // If the inputs all stem from a single 128-bit lane of each input, then we
9240   // split them rather than blending because the split will decompose to
9241   // unusually few instructions.
9242   int LaneCount = VT.getSizeInBits() / 128;
9243   int LaneSize = Size / LaneCount;
9244   SmallBitVector LaneInputs[2];
9245   LaneInputs[0].resize(LaneCount, false);
9246   LaneInputs[1].resize(LaneCount, false);
9247   for (int i = 0; i < Size; ++i)
9248     if (Mask[i] >= 0)
9249       LaneInputs[Mask[i] / Size][(Mask[i] % Size) / LaneSize] = true;
9250   if (LaneInputs[0].count() <= 1 && LaneInputs[1].count() <= 1)
9251     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9252
9253   // Otherwise, just fall back to decomposed shuffles and a blend. This requires
9254   // that the decomposed single-input shuffles don't end up here.
9255   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9256 }
9257
9258 /// \brief Lower a vector shuffle crossing multiple 128-bit lanes as
9259 /// a permutation and blend of those lanes.
9260 ///
9261 /// This essentially blends the out-of-lane inputs to each lane into the lane
9262 /// from a permuted copy of the vector. This lowering strategy results in four
9263 /// instructions in the worst case for a single-input cross lane shuffle which
9264 /// is lower than any other fully general cross-lane shuffle strategy I'm aware
9265 /// of. Special cases for each particular shuffle pattern should be handled
9266 /// prior to trying this lowering.
9267 static SDValue lowerVectorShuffleAsLanePermuteAndBlend(SDLoc DL, MVT VT,
9268                                                        SDValue V1, SDValue V2,
9269                                                        ArrayRef<int> Mask,
9270                                                        SelectionDAG &DAG) {
9271   // FIXME: This should probably be generalized for 512-bit vectors as well.
9272   assert(VT.getSizeInBits() == 256 && "Only for 256-bit vector shuffles!");
9273   int LaneSize = Mask.size() / 2;
9274
9275   // If there are only inputs from one 128-bit lane, splitting will in fact be
9276   // less expensive. The flags track whether the given lane contains an element
9277   // that crosses to another lane.
9278   bool LaneCrossing[2] = {false, false};
9279   for (int i = 0, Size = Mask.size(); i < Size; ++i)
9280     if (Mask[i] >= 0 && (Mask[i] % Size) / LaneSize != i / LaneSize)
9281       LaneCrossing[(Mask[i] % Size) / LaneSize] = true;
9282   if (!LaneCrossing[0] || !LaneCrossing[1])
9283     return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
9284
9285   if (isSingleInputShuffleMask(Mask)) {
9286     SmallVector<int, 32> FlippedBlendMask;
9287     for (int i = 0, Size = Mask.size(); i < Size; ++i)
9288       FlippedBlendMask.push_back(
9289           Mask[i] < 0 ? -1 : (((Mask[i] % Size) / LaneSize == i / LaneSize)
9290                                   ? Mask[i]
9291                                   : Mask[i] % LaneSize +
9292                                         (i / LaneSize) * LaneSize + Size));
9293
9294     // Flip the vector, and blend the results which should now be in-lane. The
9295     // VPERM2X128 mask uses the low 2 bits for the low source and bits 4 and
9296     // 5 for the high source. The value 3 selects the high half of source 2 and
9297     // the value 2 selects the low half of source 2. We only use source 2 to
9298     // allow folding it into a memory operand.
9299     unsigned PERMMask = 3 | 2 << 4;
9300     SDValue Flipped = DAG.getNode(X86ISD::VPERM2X128, DL, VT, DAG.getUNDEF(VT),
9301                                   V1, DAG.getConstant(PERMMask, DL, MVT::i8));
9302     return DAG.getVectorShuffle(VT, DL, V1, Flipped, FlippedBlendMask);
9303   }
9304
9305   // This now reduces to two single-input shuffles of V1 and V2 which at worst
9306   // will be handled by the above logic and a blend of the results, much like
9307   // other patterns in AVX.
9308   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, VT, V1, V2, Mask, DAG);
9309 }
9310
9311 /// \brief Handle lowering 2-lane 128-bit shuffles.
9312 static SDValue lowerV2X128VectorShuffle(SDLoc DL, MVT VT, SDValue V1,
9313                                         SDValue V2, ArrayRef<int> Mask,
9314                                         const X86Subtarget *Subtarget,
9315                                         SelectionDAG &DAG) {
9316   // TODO: If minimizing size and one of the inputs is a zero vector and the
9317   // the zero vector has only one use, we could use a VPERM2X128 to save the
9318   // instruction bytes needed to explicitly generate the zero vector.
9319
9320   // Blends are faster and handle all the non-lane-crossing cases.
9321   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, VT, V1, V2, Mask,
9322                                                 Subtarget, DAG))
9323     return Blend;
9324
9325   bool IsV1Zero = ISD::isBuildVectorAllZeros(V1.getNode());
9326   bool IsV2Zero = ISD::isBuildVectorAllZeros(V2.getNode());
9327
9328   // If either input operand is a zero vector, use VPERM2X128 because its mask
9329   // allows us to replace the zero input with an implicit zero.
9330   if (!IsV1Zero && !IsV2Zero) {
9331     // Check for patterns which can be matched with a single insert of a 128-bit
9332     // subvector.
9333     bool OnlyUsesV1 = isShuffleEquivalent(V1, V2, Mask, {0, 1, 0, 1});
9334     if (OnlyUsesV1 || isShuffleEquivalent(V1, V2, Mask, {0, 1, 4, 5})) {
9335       MVT SubVT = MVT::getVectorVT(VT.getVectorElementType(),
9336                                    VT.getVectorNumElements() / 2);
9337       SDValue LoV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, V1,
9338                                 DAG.getIntPtrConstant(0, DL));
9339       SDValue HiV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT,
9340                                 OnlyUsesV1 ? V1 : V2,
9341                                 DAG.getIntPtrConstant(0, DL));
9342       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LoV, HiV);
9343     }
9344   }
9345
9346   // Otherwise form a 128-bit permutation. After accounting for undefs,
9347   // convert the 64-bit shuffle mask selection values into 128-bit
9348   // selection bits by dividing the indexes by 2 and shifting into positions
9349   // defined by a vperm2*128 instruction's immediate control byte.
9350
9351   // The immediate permute control byte looks like this:
9352   //    [1:0] - select 128 bits from sources for low half of destination
9353   //    [2]   - ignore
9354   //    [3]   - zero low half of destination
9355   //    [5:4] - select 128 bits from sources for high half of destination
9356   //    [6]   - ignore
9357   //    [7]   - zero high half of destination
9358
9359   int MaskLO = Mask[0];
9360   if (MaskLO == SM_SentinelUndef)
9361     MaskLO = Mask[1] == SM_SentinelUndef ? 0 : Mask[1];
9362
9363   int MaskHI = Mask[2];
9364   if (MaskHI == SM_SentinelUndef)
9365     MaskHI = Mask[3] == SM_SentinelUndef ? 0 : Mask[3];
9366
9367   unsigned PermMask = MaskLO / 2 | (MaskHI / 2) << 4;
9368
9369   // If either input is a zero vector, replace it with an undef input.
9370   // Shuffle mask values <  4 are selecting elements of V1.
9371   // Shuffle mask values >= 4 are selecting elements of V2.
9372   // Adjust each half of the permute mask by clearing the half that was
9373   // selecting the zero vector and setting the zero mask bit.
9374   if (IsV1Zero) {
9375     V1 = DAG.getUNDEF(VT);
9376     if (MaskLO < 4)
9377       PermMask = (PermMask & 0xf0) | 0x08;
9378     if (MaskHI < 4)
9379       PermMask = (PermMask & 0x0f) | 0x80;
9380   }
9381   if (IsV2Zero) {
9382     V2 = DAG.getUNDEF(VT);
9383     if (MaskLO >= 4)
9384       PermMask = (PermMask & 0xf0) | 0x08;
9385     if (MaskHI >= 4)
9386       PermMask = (PermMask & 0x0f) | 0x80;
9387   }
9388
9389   return DAG.getNode(X86ISD::VPERM2X128, DL, VT, V1, V2,
9390                      DAG.getConstant(PermMask, DL, MVT::i8));
9391 }
9392
9393 /// \brief Lower a vector shuffle by first fixing the 128-bit lanes and then
9394 /// shuffling each lane.
9395 ///
9396 /// This will only succeed when the result of fixing the 128-bit lanes results
9397 /// in a single-input non-lane-crossing shuffle with a repeating shuffle mask in
9398 /// each 128-bit lanes. This handles many cases where we can quickly blend away
9399 /// the lane crosses early and then use simpler shuffles within each lane.
9400 ///
9401 /// FIXME: It might be worthwhile at some point to support this without
9402 /// requiring the 128-bit lane-relative shuffles to be repeating, but currently
9403 /// in x86 only floating point has interesting non-repeating shuffles, and even
9404 /// those are still *marginally* more expensive.
9405 static SDValue lowerVectorShuffleByMerging128BitLanes(
9406     SDLoc DL, MVT VT, SDValue V1, SDValue V2, ArrayRef<int> Mask,
9407     const X86Subtarget *Subtarget, SelectionDAG &DAG) {
9408   assert(!isSingleInputShuffleMask(Mask) &&
9409          "This is only useful with multiple inputs.");
9410
9411   int Size = Mask.size();
9412   int LaneSize = 128 / VT.getScalarSizeInBits();
9413   int NumLanes = Size / LaneSize;
9414   assert(NumLanes > 1 && "Only handles 256-bit and wider shuffles.");
9415
9416   // See if we can build a hypothetical 128-bit lane-fixing shuffle mask. Also
9417   // check whether the in-128-bit lane shuffles share a repeating pattern.
9418   SmallVector<int, 4> Lanes;
9419   Lanes.resize(NumLanes, -1);
9420   SmallVector<int, 4> InLaneMask;
9421   InLaneMask.resize(LaneSize, -1);
9422   for (int i = 0; i < Size; ++i) {
9423     if (Mask[i] < 0)
9424       continue;
9425
9426     int j = i / LaneSize;
9427
9428     if (Lanes[j] < 0) {
9429       // First entry we've seen for this lane.
9430       Lanes[j] = Mask[i] / LaneSize;
9431     } else if (Lanes[j] != Mask[i] / LaneSize) {
9432       // This doesn't match the lane selected previously!
9433       return SDValue();
9434     }
9435
9436     // Check that within each lane we have a consistent shuffle mask.
9437     int k = i % LaneSize;
9438     if (InLaneMask[k] < 0) {
9439       InLaneMask[k] = Mask[i] % LaneSize;
9440     } else if (InLaneMask[k] != Mask[i] % LaneSize) {
9441       // This doesn't fit a repeating in-lane mask.
9442       return SDValue();
9443     }
9444   }
9445
9446   // First shuffle the lanes into place.
9447   MVT LaneVT = MVT::getVectorVT(VT.isFloatingPoint() ? MVT::f64 : MVT::i64,
9448                                 VT.getSizeInBits() / 64);
9449   SmallVector<int, 8> LaneMask;
9450   LaneMask.resize(NumLanes * 2, -1);
9451   for (int i = 0; i < NumLanes; ++i)
9452     if (Lanes[i] >= 0) {
9453       LaneMask[2 * i + 0] = 2*Lanes[i] + 0;
9454       LaneMask[2 * i + 1] = 2*Lanes[i] + 1;
9455     }
9456
9457   V1 = DAG.getBitcast(LaneVT, V1);
9458   V2 = DAG.getBitcast(LaneVT, V2);
9459   SDValue LaneShuffle = DAG.getVectorShuffle(LaneVT, DL, V1, V2, LaneMask);
9460
9461   // Cast it back to the type we actually want.
9462   LaneShuffle = DAG.getBitcast(VT, LaneShuffle);
9463
9464   // Now do a simple shuffle that isn't lane crossing.
9465   SmallVector<int, 8> NewMask;
9466   NewMask.resize(Size, -1);
9467   for (int i = 0; i < Size; ++i)
9468     if (Mask[i] >= 0)
9469       NewMask[i] = (i / LaneSize) * LaneSize + Mask[i] % LaneSize;
9470   assert(!is128BitLaneCrossingShuffleMask(VT, NewMask) &&
9471          "Must not introduce lane crosses at this point!");
9472
9473   return DAG.getVectorShuffle(VT, DL, LaneShuffle, DAG.getUNDEF(VT), NewMask);
9474 }
9475
9476 /// \brief Test whether the specified input (0 or 1) is in-place blended by the
9477 /// given mask.
9478 ///
9479 /// This returns true if the elements from a particular input are already in the
9480 /// slot required by the given mask and require no permutation.
9481 static bool isShuffleMaskInputInPlace(int Input, ArrayRef<int> Mask) {
9482   assert((Input == 0 || Input == 1) && "Only two inputs to shuffles.");
9483   int Size = Mask.size();
9484   for (int i = 0; i < Size; ++i)
9485     if (Mask[i] >= 0 && Mask[i] / Size == Input && Mask[i] % Size != i)
9486       return false;
9487
9488   return true;
9489 }
9490
9491 static SDValue lowerVectorShuffleWithSHUFPD(SDLoc DL, MVT VT,
9492                                             ArrayRef<int> Mask, SDValue V1,
9493                                             SDValue V2, SelectionDAG &DAG) {
9494
9495   // Mask for V8F64: 0/1,  8/9,  2/3,  10/11, 4/5, ..
9496   // Mask for V4F64; 0/1,  4/5,  2/3,  6/7..
9497   assert(VT.getScalarSizeInBits() == 64 && "Unexpected data type for VSHUFPD");
9498   int NumElts = VT.getVectorNumElements();
9499   bool ShufpdMask = true;
9500   bool CommutableMask = true;
9501   unsigned Immediate = 0;
9502   for (int i = 0; i < NumElts; ++i) {
9503     if (Mask[i] < 0)
9504       continue;
9505     int Val = (i & 6) + NumElts * (i & 1);
9506     int CommutVal = (i & 0xe) + NumElts * ((i & 1)^1);
9507     if (Mask[i] < Val ||  Mask[i] > Val + 1)
9508       ShufpdMask = false;
9509     if (Mask[i] < CommutVal ||  Mask[i] > CommutVal + 1)
9510       CommutableMask = false;
9511     Immediate |= (Mask[i] % 2) << i;
9512   }
9513   if (ShufpdMask)
9514     return DAG.getNode(X86ISD::SHUFP, DL, VT, V1, V2,
9515                        DAG.getConstant(Immediate, DL, MVT::i8));
9516   if (CommutableMask)
9517     return DAG.getNode(X86ISD::SHUFP, DL, VT, V2, V1,
9518                        DAG.getConstant(Immediate, DL, MVT::i8));
9519   return SDValue();
9520 }
9521
9522 /// \brief Handle lowering of 4-lane 64-bit floating point shuffles.
9523 ///
9524 /// Also ends up handling lowering of 4-lane 64-bit integer shuffles when AVX2
9525 /// isn't available.
9526 static SDValue lowerV4F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9527                                        const X86Subtarget *Subtarget,
9528                                        SelectionDAG &DAG) {
9529   SDLoc DL(Op);
9530   assert(V1.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9531   assert(V2.getSimpleValueType() == MVT::v4f64 && "Bad operand type!");
9532   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9533   ArrayRef<int> Mask = SVOp->getMask();
9534   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9535
9536   SmallVector<int, 4> WidenedMask;
9537   if (canWidenShuffleElements(Mask, WidenedMask))
9538     return lowerV2X128VectorShuffle(DL, MVT::v4f64, V1, V2, Mask, Subtarget,
9539                                     DAG);
9540
9541   if (isSingleInputShuffleMask(Mask)) {
9542     // Check for being able to broadcast a single element.
9543     if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4f64, V1,
9544                                                           Mask, Subtarget, DAG))
9545       return Broadcast;
9546
9547     // Use low duplicate instructions for masks that match their pattern.
9548     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2}))
9549       return DAG.getNode(X86ISD::MOVDDUP, DL, MVT::v4f64, V1);
9550
9551     if (!is128BitLaneCrossingShuffleMask(MVT::v4f64, Mask)) {
9552       // Non-half-crossing single input shuffles can be lowerid with an
9553       // interleaved permutation.
9554       unsigned VPERMILPMask = (Mask[0] == 1) | ((Mask[1] == 1) << 1) |
9555                               ((Mask[2] == 3) << 2) | ((Mask[3] == 3) << 3);
9556       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v4f64, V1,
9557                          DAG.getConstant(VPERMILPMask, DL, MVT::i8));
9558     }
9559
9560     // With AVX2 we have direct support for this permutation.
9561     if (Subtarget->hasAVX2())
9562       return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4f64, V1,
9563                          getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9564
9565     // Otherwise, fall back.
9566     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v4f64, V1, V2, Mask,
9567                                                    DAG);
9568   }
9569
9570   // X86 has dedicated unpack instructions that can handle specific blend
9571   // operations: UNPCKH and UNPCKL.
9572   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9573     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V1, V2);
9574   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9575     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V1, V2);
9576   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9577     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4f64, V2, V1);
9578   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9579     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4f64, V2, V1);
9580
9581   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4f64, V1, V2, Mask,
9582                                                 Subtarget, DAG))
9583     return Blend;
9584
9585   // Check if the blend happens to exactly fit that of SHUFPD.
9586   if (SDValue Op =
9587       lowerVectorShuffleWithSHUFPD(DL, MVT::v4f64, Mask, V1, V2, DAG))
9588     return Op;
9589
9590   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9591   // shuffle. However, if we have AVX2 and either inputs are already in place,
9592   // we will be able to shuffle even across lanes the other input in a single
9593   // instruction so skip this pattern.
9594   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9595                                  isShuffleMaskInputInPlace(1, Mask))))
9596     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9597             DL, MVT::v4f64, V1, V2, Mask, Subtarget, DAG))
9598       return Result;
9599
9600   // If we have AVX2 then we always want to lower with a blend because an v4 we
9601   // can fully permute the elements.
9602   if (Subtarget->hasAVX2())
9603     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4f64, V1, V2,
9604                                                       Mask, DAG);
9605
9606   // Otherwise fall back on generic lowering.
9607   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v4f64, V1, V2, Mask, DAG);
9608 }
9609
9610 /// \brief Handle lowering of 4-lane 64-bit integer shuffles.
9611 ///
9612 /// This routine is only called when we have AVX2 and thus a reasonable
9613 /// instruction set for v4i64 shuffling..
9614 static SDValue lowerV4I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9615                                        const X86Subtarget *Subtarget,
9616                                        SelectionDAG &DAG) {
9617   SDLoc DL(Op);
9618   assert(V1.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9619   assert(V2.getSimpleValueType() == MVT::v4i64 && "Bad operand type!");
9620   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9621   ArrayRef<int> Mask = SVOp->getMask();
9622   assert(Mask.size() == 4 && "Unexpected mask size for v4 shuffle!");
9623   assert(Subtarget->hasAVX2() && "We can only lower v4i64 with AVX2!");
9624
9625   SmallVector<int, 4> WidenedMask;
9626   if (canWidenShuffleElements(Mask, WidenedMask))
9627     return lowerV2X128VectorShuffle(DL, MVT::v4i64, V1, V2, Mask, Subtarget,
9628                                     DAG);
9629
9630   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v4i64, V1, V2, Mask,
9631                                                 Subtarget, DAG))
9632     return Blend;
9633
9634   // Check for being able to broadcast a single element.
9635   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v4i64, V1,
9636                                                         Mask, Subtarget, DAG))
9637     return Broadcast;
9638
9639   // When the shuffle is mirrored between the 128-bit lanes of the unit, we can
9640   // use lower latency instructions that will operate on both 128-bit lanes.
9641   SmallVector<int, 2> RepeatedMask;
9642   if (is128BitLaneRepeatedShuffleMask(MVT::v4i64, Mask, RepeatedMask)) {
9643     if (isSingleInputShuffleMask(Mask)) {
9644       int PSHUFDMask[] = {-1, -1, -1, -1};
9645       for (int i = 0; i < 2; ++i)
9646         if (RepeatedMask[i] >= 0) {
9647           PSHUFDMask[2 * i] = 2 * RepeatedMask[i];
9648           PSHUFDMask[2 * i + 1] = 2 * RepeatedMask[i] + 1;
9649         }
9650       return DAG.getBitcast(
9651           MVT::v4i64,
9652           DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32,
9653                       DAG.getBitcast(MVT::v8i32, V1),
9654                       getV4X86ShuffleImm8ForMask(PSHUFDMask, DL, DAG)));
9655     }
9656   }
9657
9658   // AVX2 provides a direct instruction for permuting a single input across
9659   // lanes.
9660   if (isSingleInputShuffleMask(Mask))
9661     return DAG.getNode(X86ISD::VPERMI, DL, MVT::v4i64, V1,
9662                        getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
9663
9664   // Try to use shift instructions.
9665   if (SDValue Shift =
9666           lowerVectorShuffleAsShift(DL, MVT::v4i64, V1, V2, Mask, DAG))
9667     return Shift;
9668
9669   // Use dedicated unpack instructions for masks that match their pattern.
9670   if (isShuffleEquivalent(V1, V2, Mask, {0, 4, 2, 6}))
9671     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V1, V2);
9672   if (isShuffleEquivalent(V1, V2, Mask, {1, 5, 3, 7}))
9673     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V1, V2);
9674   if (isShuffleEquivalent(V1, V2, Mask, {4, 0, 6, 2}))
9675     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v4i64, V2, V1);
9676   if (isShuffleEquivalent(V1, V2, Mask, {5, 1, 7, 3}))
9677     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v4i64, V2, V1);
9678
9679   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9680   // shuffle. However, if we have AVX2 and either inputs are already in place,
9681   // we will be able to shuffle even across lanes the other input in a single
9682   // instruction so skip this pattern.
9683   if (!(Subtarget->hasAVX2() && (isShuffleMaskInputInPlace(0, Mask) ||
9684                                  isShuffleMaskInputInPlace(1, Mask))))
9685     if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9686             DL, MVT::v4i64, V1, V2, Mask, Subtarget, DAG))
9687       return Result;
9688
9689   // Otherwise fall back on generic blend lowering.
9690   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v4i64, V1, V2,
9691                                                     Mask, DAG);
9692 }
9693
9694 /// \brief Handle lowering of 8-lane 32-bit floating point shuffles.
9695 ///
9696 /// Also ends up handling lowering of 8-lane 32-bit integer shuffles when AVX2
9697 /// isn't available.
9698 static SDValue lowerV8F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9699                                        const X86Subtarget *Subtarget,
9700                                        SelectionDAG &DAG) {
9701   SDLoc DL(Op);
9702   assert(V1.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9703   assert(V2.getSimpleValueType() == MVT::v8f32 && "Bad operand type!");
9704   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9705   ArrayRef<int> Mask = SVOp->getMask();
9706   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9707
9708   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8f32, V1, V2, Mask,
9709                                                 Subtarget, DAG))
9710     return Blend;
9711
9712   // Check for being able to broadcast a single element.
9713   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8f32, V1,
9714                                                         Mask, Subtarget, DAG))
9715     return Broadcast;
9716
9717   // If the shuffle mask is repeated in each 128-bit lane, we have many more
9718   // options to efficiently lower the shuffle.
9719   SmallVector<int, 4> RepeatedMask;
9720   if (is128BitLaneRepeatedShuffleMask(MVT::v8f32, Mask, RepeatedMask)) {
9721     assert(RepeatedMask.size() == 4 &&
9722            "Repeated masks must be half the mask width!");
9723
9724     // Use even/odd duplicate instructions for masks that match their pattern.
9725     if (isShuffleEquivalent(V1, V2, Mask, {0, 0, 2, 2, 4, 4, 6, 6}))
9726       return DAG.getNode(X86ISD::MOVSLDUP, DL, MVT::v8f32, V1);
9727     if (isShuffleEquivalent(V1, V2, Mask, {1, 1, 3, 3, 5, 5, 7, 7}))
9728       return DAG.getNode(X86ISD::MOVSHDUP, DL, MVT::v8f32, V1);
9729
9730     if (isSingleInputShuffleMask(Mask))
9731       return DAG.getNode(X86ISD::VPERMILPI, DL, MVT::v8f32, V1,
9732                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9733
9734     // Use dedicated unpack instructions for masks that match their pattern.
9735     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9736       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V1, V2);
9737     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9738       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V1, V2);
9739     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9740       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f32, V2, V1);
9741     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9742       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f32, V2, V1);
9743
9744     // Otherwise, fall back to a SHUFPS sequence. Here it is important that we
9745     // have already handled any direct blends. We also need to squash the
9746     // repeated mask into a simulated v4f32 mask.
9747     for (int i = 0; i < 4; ++i)
9748       if (RepeatedMask[i] >= 8)
9749         RepeatedMask[i] -= 4;
9750     return lowerVectorShuffleWithSHUFPS(DL, MVT::v8f32, RepeatedMask, V1, V2, DAG);
9751   }
9752
9753   // If we have a single input shuffle with different shuffle patterns in the
9754   // two 128-bit lanes use the variable mask to VPERMILPS.
9755   if (isSingleInputShuffleMask(Mask)) {
9756     SDValue VPermMask[8];
9757     for (int i = 0; i < 8; ++i)
9758       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9759                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9760     if (!is128BitLaneCrossingShuffleMask(MVT::v8f32, Mask))
9761       return DAG.getNode(
9762           X86ISD::VPERMILPV, DL, MVT::v8f32, V1,
9763           DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask));
9764
9765     if (Subtarget->hasAVX2())
9766       return DAG.getNode(
9767           X86ISD::VPERMV, DL, MVT::v8f32,
9768           DAG.getBitcast(MVT::v8f32, DAG.getNode(ISD::BUILD_VECTOR, DL,
9769                                                  MVT::v8i32, VPermMask)),
9770           V1);
9771
9772     // Otherwise, fall back.
9773     return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v8f32, V1, V2, Mask,
9774                                                    DAG);
9775   }
9776
9777   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9778   // shuffle.
9779   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9780           DL, MVT::v8f32, V1, V2, Mask, Subtarget, DAG))
9781     return Result;
9782
9783   // If we have AVX2 then we always want to lower with a blend because at v8 we
9784   // can fully permute the elements.
9785   if (Subtarget->hasAVX2())
9786     return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8f32, V1, V2,
9787                                                       Mask, DAG);
9788
9789   // Otherwise fall back on generic lowering.
9790   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v8f32, V1, V2, Mask, DAG);
9791 }
9792
9793 /// \brief Handle lowering of 8-lane 32-bit integer shuffles.
9794 ///
9795 /// This routine is only called when we have AVX2 and thus a reasonable
9796 /// instruction set for v8i32 shuffling..
9797 static SDValue lowerV8I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9798                                        const X86Subtarget *Subtarget,
9799                                        SelectionDAG &DAG) {
9800   SDLoc DL(Op);
9801   assert(V1.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9802   assert(V2.getSimpleValueType() == MVT::v8i32 && "Bad operand type!");
9803   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9804   ArrayRef<int> Mask = SVOp->getMask();
9805   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
9806   assert(Subtarget->hasAVX2() && "We can only lower v8i32 with AVX2!");
9807
9808   // Whenever we can lower this as a zext, that instruction is strictly faster
9809   // than any alternative. It also allows us to fold memory operands into the
9810   // shuffle in many cases.
9811   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v8i32, V1, V2,
9812                                                          Mask, Subtarget, DAG))
9813     return ZExt;
9814
9815   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v8i32, V1, V2, Mask,
9816                                                 Subtarget, DAG))
9817     return Blend;
9818
9819   // Check for being able to broadcast a single element.
9820   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v8i32, V1,
9821                                                         Mask, Subtarget, DAG))
9822     return Broadcast;
9823
9824   // If the shuffle mask is repeated in each 128-bit lane we can use more
9825   // efficient instructions that mirror the shuffles across the two 128-bit
9826   // lanes.
9827   SmallVector<int, 4> RepeatedMask;
9828   if (is128BitLaneRepeatedShuffleMask(MVT::v8i32, Mask, RepeatedMask)) {
9829     assert(RepeatedMask.size() == 4 && "Unexpected repeated mask size!");
9830     if (isSingleInputShuffleMask(Mask))
9831       return DAG.getNode(X86ISD::PSHUFD, DL, MVT::v8i32, V1,
9832                          getV4X86ShuffleImm8ForMask(RepeatedMask, DL, DAG));
9833
9834     // Use dedicated unpack instructions for masks that match their pattern.
9835     if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 1, 9, 4, 12, 5, 13}))
9836       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V1, V2);
9837     if (isShuffleEquivalent(V1, V2, Mask, {2, 10, 3, 11, 6, 14, 7, 15}))
9838       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V1, V2);
9839     if (isShuffleEquivalent(V1, V2, Mask, {8, 0, 9, 1, 12, 4, 13, 5}))
9840       return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i32, V2, V1);
9841     if (isShuffleEquivalent(V1, V2, Mask, {10, 2, 11, 3, 14, 6, 15, 7}))
9842       return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i32, V2, V1);
9843   }
9844
9845   // Try to use shift instructions.
9846   if (SDValue Shift =
9847           lowerVectorShuffleAsShift(DL, MVT::v8i32, V1, V2, Mask, DAG))
9848     return Shift;
9849
9850   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9851           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9852     return Rotate;
9853
9854   // If the shuffle patterns aren't repeated but it is a single input, directly
9855   // generate a cross-lane VPERMD instruction.
9856   if (isSingleInputShuffleMask(Mask)) {
9857     SDValue VPermMask[8];
9858     for (int i = 0; i < 8; ++i)
9859       VPermMask[i] = Mask[i] < 0 ? DAG.getUNDEF(MVT::i32)
9860                                  : DAG.getConstant(Mask[i], DL, MVT::i32);
9861     return DAG.getNode(
9862         X86ISD::VPERMV, DL, MVT::v8i32,
9863         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v8i32, VPermMask), V1);
9864   }
9865
9866   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9867   // shuffle.
9868   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9869           DL, MVT::v8i32, V1, V2, Mask, Subtarget, DAG))
9870     return Result;
9871
9872   // Otherwise fall back on generic blend lowering.
9873   return lowerVectorShuffleAsDecomposedShuffleBlend(DL, MVT::v8i32, V1, V2,
9874                                                     Mask, DAG);
9875 }
9876
9877 /// \brief Handle lowering of 16-lane 16-bit integer shuffles.
9878 ///
9879 /// This routine is only called when we have AVX2 and thus a reasonable
9880 /// instruction set for v16i16 shuffling..
9881 static SDValue lowerV16I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9882                                         const X86Subtarget *Subtarget,
9883                                         SelectionDAG &DAG) {
9884   SDLoc DL(Op);
9885   assert(V1.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9886   assert(V2.getSimpleValueType() == MVT::v16i16 && "Bad operand type!");
9887   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9888   ArrayRef<int> Mask = SVOp->getMask();
9889   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
9890   assert(Subtarget->hasAVX2() && "We can only lower v16i16 with AVX2!");
9891
9892   // Whenever we can lower this as a zext, that instruction is strictly faster
9893   // than any alternative. It also allows us to fold memory operands into the
9894   // shuffle in many cases.
9895   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v16i16, V1, V2,
9896                                                          Mask, Subtarget, DAG))
9897     return ZExt;
9898
9899   // Check for being able to broadcast a single element.
9900   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v16i16, V1,
9901                                                         Mask, Subtarget, DAG))
9902     return Broadcast;
9903
9904   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v16i16, V1, V2, Mask,
9905                                                 Subtarget, DAG))
9906     return Blend;
9907
9908   // Use dedicated unpack instructions for masks that match their pattern.
9909   if (isShuffleEquivalent(V1, V2, Mask,
9910                           {// First 128-bit lane:
9911                            0, 16, 1, 17, 2, 18, 3, 19,
9912                            // Second 128-bit lane:
9913                            8, 24, 9, 25, 10, 26, 11, 27}))
9914     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i16, V1, V2);
9915   if (isShuffleEquivalent(V1, V2, Mask,
9916                           {// First 128-bit lane:
9917                            4, 20, 5, 21, 6, 22, 7, 23,
9918                            // Second 128-bit lane:
9919                            12, 28, 13, 29, 14, 30, 15, 31}))
9920     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i16, V1, V2);
9921
9922   // Try to use shift instructions.
9923   if (SDValue Shift =
9924           lowerVectorShuffleAsShift(DL, MVT::v16i16, V1, V2, Mask, DAG))
9925     return Shift;
9926
9927   // Try to use byte rotation instructions.
9928   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
9929           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9930     return Rotate;
9931
9932   if (isSingleInputShuffleMask(Mask)) {
9933     // There are no generalized cross-lane shuffle operations available on i16
9934     // element types.
9935     if (is128BitLaneCrossingShuffleMask(MVT::v16i16, Mask))
9936       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v16i16, V1, V2,
9937                                                      Mask, DAG);
9938
9939     SmallVector<int, 8> RepeatedMask;
9940     if (is128BitLaneRepeatedShuffleMask(MVT::v16i16, Mask, RepeatedMask)) {
9941       // As this is a single-input shuffle, the repeated mask should be
9942       // a strictly valid v8i16 mask that we can pass through to the v8i16
9943       // lowering to handle even the v16 case.
9944       return lowerV8I16GeneralSingleInputVectorShuffle(
9945           DL, MVT::v16i16, V1, RepeatedMask, Subtarget, DAG);
9946     }
9947
9948     SDValue PSHUFBMask[32];
9949     for (int i = 0; i < 16; ++i) {
9950       if (Mask[i] == -1) {
9951         PSHUFBMask[2 * i] = PSHUFBMask[2 * i + 1] = DAG.getUNDEF(MVT::i8);
9952         continue;
9953       }
9954
9955       int M = i < 8 ? Mask[i] : Mask[i] - 8;
9956       assert(M >= 0 && M < 8 && "Invalid single-input mask!");
9957       PSHUFBMask[2 * i] = DAG.getConstant(2 * M, DL, MVT::i8);
9958       PSHUFBMask[2 * i + 1] = DAG.getConstant(2 * M + 1, DL, MVT::i8);
9959     }
9960     return DAG.getBitcast(MVT::v16i16,
9961                           DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8,
9962                                       DAG.getBitcast(MVT::v32i8, V1),
9963                                       DAG.getNode(ISD::BUILD_VECTOR, DL,
9964                                                   MVT::v32i8, PSHUFBMask)));
9965   }
9966
9967   // Try to simplify this by merging 128-bit lanes to enable a lane-based
9968   // shuffle.
9969   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
9970           DL, MVT::v16i16, V1, V2, Mask, Subtarget, DAG))
9971     return Result;
9972
9973   // Otherwise fall back on generic lowering.
9974   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v16i16, V1, V2, Mask, DAG);
9975 }
9976
9977 /// \brief Handle lowering of 32-lane 8-bit integer shuffles.
9978 ///
9979 /// This routine is only called when we have AVX2 and thus a reasonable
9980 /// instruction set for v32i8 shuffling..
9981 static SDValue lowerV32I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
9982                                        const X86Subtarget *Subtarget,
9983                                        SelectionDAG &DAG) {
9984   SDLoc DL(Op);
9985   assert(V1.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9986   assert(V2.getSimpleValueType() == MVT::v32i8 && "Bad operand type!");
9987   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
9988   ArrayRef<int> Mask = SVOp->getMask();
9989   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
9990   assert(Subtarget->hasAVX2() && "We can only lower v32i8 with AVX2!");
9991
9992   // Whenever we can lower this as a zext, that instruction is strictly faster
9993   // than any alternative. It also allows us to fold memory operands into the
9994   // shuffle in many cases.
9995   if (SDValue ZExt = lowerVectorShuffleAsZeroOrAnyExtend(DL, MVT::v32i8, V1, V2,
9996                                                          Mask, Subtarget, DAG))
9997     return ZExt;
9998
9999   // Check for being able to broadcast a single element.
10000   if (SDValue Broadcast = lowerVectorShuffleAsBroadcast(DL, MVT::v32i8, V1,
10001                                                         Mask, Subtarget, DAG))
10002     return Broadcast;
10003
10004   if (SDValue Blend = lowerVectorShuffleAsBlend(DL, MVT::v32i8, V1, V2, Mask,
10005                                                 Subtarget, DAG))
10006     return Blend;
10007
10008   // Use dedicated unpack instructions for masks that match their pattern.
10009   // Note that these are repeated 128-bit lane unpacks, not unpacks across all
10010   // 256-bit lanes.
10011   if (isShuffleEquivalent(
10012           V1, V2, Mask,
10013           {// First 128-bit lane:
10014            0, 32, 1, 33, 2, 34, 3, 35, 4, 36, 5, 37, 6, 38, 7, 39,
10015            // Second 128-bit lane:
10016            16, 48, 17, 49, 18, 50, 19, 51, 20, 52, 21, 53, 22, 54, 23, 55}))
10017     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v32i8, V1, V2);
10018   if (isShuffleEquivalent(
10019           V1, V2, Mask,
10020           {// First 128-bit lane:
10021            8, 40, 9, 41, 10, 42, 11, 43, 12, 44, 13, 45, 14, 46, 15, 47,
10022            // Second 128-bit lane:
10023            24, 56, 25, 57, 26, 58, 27, 59, 28, 60, 29, 61, 30, 62, 31, 63}))
10024     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v32i8, V1, V2);
10025
10026   // Try to use shift instructions.
10027   if (SDValue Shift =
10028           lowerVectorShuffleAsShift(DL, MVT::v32i8, V1, V2, Mask, DAG))
10029     return Shift;
10030
10031   // Try to use byte rotation instructions.
10032   if (SDValue Rotate = lowerVectorShuffleAsByteRotate(
10033           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10034     return Rotate;
10035
10036   if (isSingleInputShuffleMask(Mask)) {
10037     // There are no generalized cross-lane shuffle operations available on i8
10038     // element types.
10039     if (is128BitLaneCrossingShuffleMask(MVT::v32i8, Mask))
10040       return lowerVectorShuffleAsLanePermuteAndBlend(DL, MVT::v32i8, V1, V2,
10041                                                      Mask, DAG);
10042
10043     SDValue PSHUFBMask[32];
10044     for (int i = 0; i < 32; ++i)
10045       PSHUFBMask[i] =
10046           Mask[i] < 0
10047               ? DAG.getUNDEF(MVT::i8)
10048               : DAG.getConstant(Mask[i] < 16 ? Mask[i] : Mask[i] - 16, DL,
10049                                 MVT::i8);
10050
10051     return DAG.getNode(
10052         X86ISD::PSHUFB, DL, MVT::v32i8, V1,
10053         DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, PSHUFBMask));
10054   }
10055
10056   // Try to simplify this by merging 128-bit lanes to enable a lane-based
10057   // shuffle.
10058   if (SDValue Result = lowerVectorShuffleByMerging128BitLanes(
10059           DL, MVT::v32i8, V1, V2, Mask, Subtarget, DAG))
10060     return Result;
10061
10062   // Otherwise fall back on generic lowering.
10063   return lowerVectorShuffleAsSplitOrBlend(DL, MVT::v32i8, V1, V2, Mask, DAG);
10064 }
10065
10066 /// \brief High-level routine to lower various 256-bit x86 vector shuffles.
10067 ///
10068 /// This routine either breaks down the specific type of a 256-bit x86 vector
10069 /// shuffle or splits it into two 128-bit shuffles and fuses the results back
10070 /// together based on the available instructions.
10071 static SDValue lower256BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10072                                         MVT VT, const X86Subtarget *Subtarget,
10073                                         SelectionDAG &DAG) {
10074   SDLoc DL(Op);
10075   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10076   ArrayRef<int> Mask = SVOp->getMask();
10077
10078   // If we have a single input to the zero element, insert that into V1 if we
10079   // can do so cheaply.
10080   int NumElts = VT.getVectorNumElements();
10081   int NumV2Elements = std::count_if(Mask.begin(), Mask.end(), [NumElts](int M) {
10082     return M >= NumElts;
10083   });
10084
10085   if (NumV2Elements == 1 && Mask[0] >= NumElts)
10086     if (SDValue Insertion = lowerVectorShuffleAsElementInsertion(
10087                               DL, VT, V1, V2, Mask, Subtarget, DAG))
10088       return Insertion;
10089
10090   // There is a really nice hard cut-over between AVX1 and AVX2 that means we can
10091   // check for those subtargets here and avoid much of the subtarget querying in
10092   // the per-vector-type lowering routines. With AVX1 we have essentially *zero*
10093   // ability to manipulate a 256-bit vector with integer types. Since we'll use
10094   // floating point types there eventually, just immediately cast everything to
10095   // a float and operate entirely in that domain.
10096   if (VT.isInteger() && !Subtarget->hasAVX2()) {
10097     int ElementBits = VT.getScalarSizeInBits();
10098     if (ElementBits < 32)
10099       // No floating point type available, decompose into 128-bit vectors.
10100       return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10101
10102     MVT FpVT = MVT::getVectorVT(MVT::getFloatingPointVT(ElementBits),
10103                                 VT.getVectorNumElements());
10104     V1 = DAG.getBitcast(FpVT, V1);
10105     V2 = DAG.getBitcast(FpVT, V2);
10106     return DAG.getBitcast(VT, DAG.getVectorShuffle(FpVT, DL, V1, V2, Mask));
10107   }
10108
10109   switch (VT.SimpleTy) {
10110   case MVT::v4f64:
10111     return lowerV4F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10112   case MVT::v4i64:
10113     return lowerV4I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10114   case MVT::v8f32:
10115     return lowerV8F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10116   case MVT::v8i32:
10117     return lowerV8I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10118   case MVT::v16i16:
10119     return lowerV16I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10120   case MVT::v32i8:
10121     return lowerV32I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10122
10123   default:
10124     llvm_unreachable("Not a valid 256-bit x86 vector type!");
10125   }
10126 }
10127
10128 /// \brief Handle lowering of 8-lane 64-bit floating point shuffles.
10129 static SDValue lowerV8F64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10130                                        const X86Subtarget *Subtarget,
10131                                        SelectionDAG &DAG) {
10132   SDLoc DL(Op);
10133   assert(V1.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10134   assert(V2.getSimpleValueType() == MVT::v8f64 && "Bad operand type!");
10135   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10136   ArrayRef<int> Mask = SVOp->getMask();
10137   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10138
10139   // X86 has dedicated unpack instructions that can handle specific blend
10140   // operations: UNPCKH and UNPCKL.
10141   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10142     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8f64, V1, V2);
10143   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10144     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8f64, V1, V2);
10145
10146   // FIXME: Implement direct support for this type!
10147   return splitAndLowerVectorShuffle(DL, MVT::v8f64, V1, V2, Mask, DAG);
10148 }
10149
10150 /// \brief Handle lowering of 16-lane 32-bit floating point shuffles.
10151 static SDValue lowerV16F32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10152                                        const X86Subtarget *Subtarget,
10153                                        SelectionDAG &DAG) {
10154   SDLoc DL(Op);
10155   assert(V1.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10156   assert(V2.getSimpleValueType() == MVT::v16f32 && "Bad operand type!");
10157   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10158   ArrayRef<int> Mask = SVOp->getMask();
10159   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10160
10161   // Use dedicated unpack instructions for masks that match their pattern.
10162   if (isShuffleEquivalent(V1, V2, Mask,
10163                           {// First 128-bit lane.
10164                            0, 16, 1, 17, 4, 20, 5, 21,
10165                            // Second 128-bit lane.
10166                            8, 24, 9, 25, 12, 28, 13, 29}))
10167     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16f32, V1, V2);
10168   if (isShuffleEquivalent(V1, V2, Mask,
10169                           {// First 128-bit lane.
10170                            2, 18, 3, 19, 6, 22, 7, 23,
10171                            // Second 128-bit lane.
10172                            10, 26, 11, 27, 14, 30, 15, 31}))
10173     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16f32, V1, V2);
10174
10175   // FIXME: Implement direct support for this type!
10176   return splitAndLowerVectorShuffle(DL, MVT::v16f32, V1, V2, Mask, DAG);
10177 }
10178
10179 /// \brief Handle lowering of 8-lane 64-bit integer shuffles.
10180 static SDValue lowerV8I64VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10181                                        const X86Subtarget *Subtarget,
10182                                        SelectionDAG &DAG) {
10183   SDLoc DL(Op);
10184   assert(V1.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10185   assert(V2.getSimpleValueType() == MVT::v8i64 && "Bad operand type!");
10186   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10187   ArrayRef<int> Mask = SVOp->getMask();
10188   assert(Mask.size() == 8 && "Unexpected mask size for v8 shuffle!");
10189
10190   // X86 has dedicated unpack instructions that can handle specific blend
10191   // operations: UNPCKH and UNPCKL.
10192   if (isShuffleEquivalent(V1, V2, Mask, {0, 8, 2, 10, 4, 12, 6, 14}))
10193     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v8i64, V1, V2);
10194   if (isShuffleEquivalent(V1, V2, Mask, {1, 9, 3, 11, 5, 13, 7, 15}))
10195     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v8i64, V1, V2);
10196
10197   // FIXME: Implement direct support for this type!
10198   return splitAndLowerVectorShuffle(DL, MVT::v8i64, V1, V2, Mask, DAG);
10199 }
10200
10201 /// \brief Handle lowering of 16-lane 32-bit integer shuffles.
10202 static SDValue lowerV16I32VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10203                                        const X86Subtarget *Subtarget,
10204                                        SelectionDAG &DAG) {
10205   SDLoc DL(Op);
10206   assert(V1.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10207   assert(V2.getSimpleValueType() == MVT::v16i32 && "Bad operand type!");
10208   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10209   ArrayRef<int> Mask = SVOp->getMask();
10210   assert(Mask.size() == 16 && "Unexpected mask size for v16 shuffle!");
10211
10212   // Use dedicated unpack instructions for masks that match their pattern.
10213   if (isShuffleEquivalent(V1, V2, Mask,
10214                           {// First 128-bit lane.
10215                            0, 16, 1, 17, 4, 20, 5, 21,
10216                            // Second 128-bit lane.
10217                            8, 24, 9, 25, 12, 28, 13, 29}))
10218     return DAG.getNode(X86ISD::UNPCKL, DL, MVT::v16i32, V1, V2);
10219   if (isShuffleEquivalent(V1, V2, Mask,
10220                           {// First 128-bit lane.
10221                            2, 18, 3, 19, 6, 22, 7, 23,
10222                            // Second 128-bit lane.
10223                            10, 26, 11, 27, 14, 30, 15, 31}))
10224     return DAG.getNode(X86ISD::UNPCKH, DL, MVT::v16i32, V1, V2);
10225
10226   // FIXME: Implement direct support for this type!
10227   return splitAndLowerVectorShuffle(DL, MVT::v16i32, V1, V2, Mask, DAG);
10228 }
10229
10230 /// \brief Handle lowering of 32-lane 16-bit integer shuffles.
10231 static SDValue lowerV32I16VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10232                                         const X86Subtarget *Subtarget,
10233                                         SelectionDAG &DAG) {
10234   SDLoc DL(Op);
10235   assert(V1.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10236   assert(V2.getSimpleValueType() == MVT::v32i16 && "Bad operand type!");
10237   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10238   ArrayRef<int> Mask = SVOp->getMask();
10239   assert(Mask.size() == 32 && "Unexpected mask size for v32 shuffle!");
10240   assert(Subtarget->hasBWI() && "We can only lower v32i16 with AVX-512-BWI!");
10241
10242   // FIXME: Implement direct support for this type!
10243   return splitAndLowerVectorShuffle(DL, MVT::v32i16, V1, V2, Mask, DAG);
10244 }
10245
10246 /// \brief Handle lowering of 64-lane 8-bit integer shuffles.
10247 static SDValue lowerV64I8VectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10248                                        const X86Subtarget *Subtarget,
10249                                        SelectionDAG &DAG) {
10250   SDLoc DL(Op);
10251   assert(V1.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10252   assert(V2.getSimpleValueType() == MVT::v64i8 && "Bad operand type!");
10253   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10254   ArrayRef<int> Mask = SVOp->getMask();
10255   assert(Mask.size() == 64 && "Unexpected mask size for v64 shuffle!");
10256   assert(Subtarget->hasBWI() && "We can only lower v64i8 with AVX-512-BWI!");
10257
10258   // FIXME: Implement direct support for this type!
10259   return splitAndLowerVectorShuffle(DL, MVT::v64i8, V1, V2, Mask, DAG);
10260 }
10261
10262 /// \brief High-level routine to lower various 512-bit x86 vector shuffles.
10263 ///
10264 /// This routine either breaks down the specific type of a 512-bit x86 vector
10265 /// shuffle or splits it into two 256-bit shuffles and fuses the results back
10266 /// together based on the available instructions.
10267 static SDValue lower512BitVectorShuffle(SDValue Op, SDValue V1, SDValue V2,
10268                                         MVT VT, const X86Subtarget *Subtarget,
10269                                         SelectionDAG &DAG) {
10270   SDLoc DL(Op);
10271   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10272   ArrayRef<int> Mask = SVOp->getMask();
10273   assert(Subtarget->hasAVX512() &&
10274          "Cannot lower 512-bit vectors w/ basic ISA!");
10275
10276   // Check for being able to broadcast a single element.
10277   if (SDValue Broadcast =
10278           lowerVectorShuffleAsBroadcast(DL, VT, V1, Mask, Subtarget, DAG))
10279     return Broadcast;
10280
10281   // Dispatch to each element type for lowering. If we don't have supprot for
10282   // specific element type shuffles at 512 bits, immediately split them and
10283   // lower them. Each lowering routine of a given type is allowed to assume that
10284   // the requisite ISA extensions for that element type are available.
10285   switch (VT.SimpleTy) {
10286   case MVT::v8f64:
10287     return lowerV8F64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10288   case MVT::v16f32:
10289     return lowerV16F32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10290   case MVT::v8i64:
10291     return lowerV8I64VectorShuffle(Op, V1, V2, Subtarget, DAG);
10292   case MVT::v16i32:
10293     return lowerV16I32VectorShuffle(Op, V1, V2, Subtarget, DAG);
10294   case MVT::v32i16:
10295     if (Subtarget->hasBWI())
10296       return lowerV32I16VectorShuffle(Op, V1, V2, Subtarget, DAG);
10297     break;
10298   case MVT::v64i8:
10299     if (Subtarget->hasBWI())
10300       return lowerV64I8VectorShuffle(Op, V1, V2, Subtarget, DAG);
10301     break;
10302
10303   default:
10304     llvm_unreachable("Not a valid 512-bit x86 vector type!");
10305   }
10306
10307   // Otherwise fall back on splitting.
10308   return splitAndLowerVectorShuffle(DL, VT, V1, V2, Mask, DAG);
10309 }
10310
10311 /// \brief Top-level lowering for x86 vector shuffles.
10312 ///
10313 /// This handles decomposition, canonicalization, and lowering of all x86
10314 /// vector shuffles. Most of the specific lowering strategies are encapsulated
10315 /// above in helper routines. The canonicalization attempts to widen shuffles
10316 /// to involve fewer lanes of wider elements, consolidate symmetric patterns
10317 /// s.t. only one of the two inputs needs to be tested, etc.
10318 static SDValue lowerVectorShuffle(SDValue Op, const X86Subtarget *Subtarget,
10319                                   SelectionDAG &DAG) {
10320   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(Op);
10321   ArrayRef<int> Mask = SVOp->getMask();
10322   SDValue V1 = Op.getOperand(0);
10323   SDValue V2 = Op.getOperand(1);
10324   MVT VT = Op.getSimpleValueType();
10325   int NumElements = VT.getVectorNumElements();
10326   SDLoc dl(Op);
10327
10328   assert(VT.getSizeInBits() != 64 && "Can't lower MMX shuffles");
10329
10330   bool V1IsUndef = V1.getOpcode() == ISD::UNDEF;
10331   bool V2IsUndef = V2.getOpcode() == ISD::UNDEF;
10332   if (V1IsUndef && V2IsUndef)
10333     return DAG.getUNDEF(VT);
10334
10335   // When we create a shuffle node we put the UNDEF node to second operand,
10336   // but in some cases the first operand may be transformed to UNDEF.
10337   // In this case we should just commute the node.
10338   if (V1IsUndef)
10339     return DAG.getCommutedVectorShuffle(*SVOp);
10340
10341   // Check for non-undef masks pointing at an undef vector and make the masks
10342   // undef as well. This makes it easier to match the shuffle based solely on
10343   // the mask.
10344   if (V2IsUndef)
10345     for (int M : Mask)
10346       if (M >= NumElements) {
10347         SmallVector<int, 8> NewMask(Mask.begin(), Mask.end());
10348         for (int &M : NewMask)
10349           if (M >= NumElements)
10350             M = -1;
10351         return DAG.getVectorShuffle(VT, dl, V1, V2, NewMask);
10352       }
10353
10354   // We actually see shuffles that are entirely re-arrangements of a set of
10355   // zero inputs. This mostly happens while decomposing complex shuffles into
10356   // simple ones. Directly lower these as a buildvector of zeros.
10357   SmallBitVector Zeroable = computeZeroableShuffleElements(Mask, V1, V2);
10358   if (Zeroable.all())
10359     return getZeroVector(VT, Subtarget, DAG, dl);
10360
10361   // Try to collapse shuffles into using a vector type with fewer elements but
10362   // wider element types. We cap this to not form integers or floating point
10363   // elements wider than 64 bits, but it might be interesting to form i128
10364   // integers to handle flipping the low and high halves of AVX 256-bit vectors.
10365   SmallVector<int, 16> WidenedMask;
10366   if (VT.getScalarSizeInBits() < 64 &&
10367       canWidenShuffleElements(Mask, WidenedMask)) {
10368     MVT NewEltVT = VT.isFloatingPoint()
10369                        ? MVT::getFloatingPointVT(VT.getScalarSizeInBits() * 2)
10370                        : MVT::getIntegerVT(VT.getScalarSizeInBits() * 2);
10371     MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
10372     // Make sure that the new vector type is legal. For example, v2f64 isn't
10373     // legal on SSE1.
10374     if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
10375       V1 = DAG.getBitcast(NewVT, V1);
10376       V2 = DAG.getBitcast(NewVT, V2);
10377       return DAG.getBitcast(
10378           VT, DAG.getVectorShuffle(NewVT, dl, V1, V2, WidenedMask));
10379     }
10380   }
10381
10382   int NumV1Elements = 0, NumUndefElements = 0, NumV2Elements = 0;
10383   for (int M : SVOp->getMask())
10384     if (M < 0)
10385       ++NumUndefElements;
10386     else if (M < NumElements)
10387       ++NumV1Elements;
10388     else
10389       ++NumV2Elements;
10390
10391   // Commute the shuffle as needed such that more elements come from V1 than
10392   // V2. This allows us to match the shuffle pattern strictly on how many
10393   // elements come from V1 without handling the symmetric cases.
10394   if (NumV2Elements > NumV1Elements)
10395     return DAG.getCommutedVectorShuffle(*SVOp);
10396
10397   // When the number of V1 and V2 elements are the same, try to minimize the
10398   // number of uses of V2 in the low half of the vector. When that is tied,
10399   // ensure that the sum of indices for V1 is equal to or lower than the sum
10400   // indices for V2. When those are equal, try to ensure that the number of odd
10401   // indices for V1 is lower than the number of odd indices for V2.
10402   if (NumV1Elements == NumV2Elements) {
10403     int LowV1Elements = 0, LowV2Elements = 0;
10404     for (int M : SVOp->getMask().slice(0, NumElements / 2))
10405       if (M >= NumElements)
10406         ++LowV2Elements;
10407       else if (M >= 0)
10408         ++LowV1Elements;
10409     if (LowV2Elements > LowV1Elements) {
10410       return DAG.getCommutedVectorShuffle(*SVOp);
10411     } else if (LowV2Elements == LowV1Elements) {
10412       int SumV1Indices = 0, SumV2Indices = 0;
10413       for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10414         if (SVOp->getMask()[i] >= NumElements)
10415           SumV2Indices += i;
10416         else if (SVOp->getMask()[i] >= 0)
10417           SumV1Indices += i;
10418       if (SumV2Indices < SumV1Indices) {
10419         return DAG.getCommutedVectorShuffle(*SVOp);
10420       } else if (SumV2Indices == SumV1Indices) {
10421         int NumV1OddIndices = 0, NumV2OddIndices = 0;
10422         for (int i = 0, Size = SVOp->getMask().size(); i < Size; ++i)
10423           if (SVOp->getMask()[i] >= NumElements)
10424             NumV2OddIndices += i % 2;
10425           else if (SVOp->getMask()[i] >= 0)
10426             NumV1OddIndices += i % 2;
10427         if (NumV2OddIndices < NumV1OddIndices)
10428           return DAG.getCommutedVectorShuffle(*SVOp);
10429       }
10430     }
10431   }
10432
10433   // For each vector width, delegate to a specialized lowering routine.
10434   if (VT.getSizeInBits() == 128)
10435     return lower128BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10436
10437   if (VT.getSizeInBits() == 256)
10438     return lower256BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10439
10440   // Force AVX-512 vectors to be scalarized for now.
10441   // FIXME: Implement AVX-512 support!
10442   if (VT.getSizeInBits() == 512)
10443     return lower512BitVectorShuffle(Op, V1, V2, VT, Subtarget, DAG);
10444
10445   llvm_unreachable("Unimplemented!");
10446 }
10447
10448 // This function assumes its argument is a BUILD_VECTOR of constants or
10449 // undef SDNodes. i.e: ISD::isBuildVectorOfConstantSDNodes(BuildVector) is
10450 // true.
10451 static bool BUILD_VECTORtoBlendMask(BuildVectorSDNode *BuildVector,
10452                                     unsigned &MaskValue) {
10453   MaskValue = 0;
10454   unsigned NumElems = BuildVector->getNumOperands();
10455   // There are 2 lanes if (NumElems > 8), and 1 lane otherwise.
10456   unsigned NumLanes = (NumElems - 1) / 8 + 1;
10457   unsigned NumElemsInLane = NumElems / NumLanes;
10458
10459   // Blend for v16i16 should be symetric for the both lanes.
10460   for (unsigned i = 0; i < NumElemsInLane; ++i) {
10461     SDValue EltCond = BuildVector->getOperand(i);
10462     SDValue SndLaneEltCond =
10463         (NumLanes == 2) ? BuildVector->getOperand(i + NumElemsInLane) : EltCond;
10464
10465     int Lane1Cond = -1, Lane2Cond = -1;
10466     if (isa<ConstantSDNode>(EltCond))
10467       Lane1Cond = !isZero(EltCond);
10468     if (isa<ConstantSDNode>(SndLaneEltCond))
10469       Lane2Cond = !isZero(SndLaneEltCond);
10470
10471     if (Lane1Cond == Lane2Cond || Lane2Cond < 0)
10472       // Lane1Cond != 0, means we want the first argument.
10473       // Lane1Cond == 0, means we want the second argument.
10474       // The encoding of this argument is 0 for the first argument, 1
10475       // for the second. Therefore, invert the condition.
10476       MaskValue |= !Lane1Cond << i;
10477     else if (Lane1Cond < 0)
10478       MaskValue |= !Lane2Cond << i;
10479     else
10480       return false;
10481   }
10482   return true;
10483 }
10484
10485 /// \brief Try to lower a VSELECT instruction to a vector shuffle.
10486 static SDValue lowerVSELECTtoVectorShuffle(SDValue Op,
10487                                            const X86Subtarget *Subtarget,
10488                                            SelectionDAG &DAG) {
10489   SDValue Cond = Op.getOperand(0);
10490   SDValue LHS = Op.getOperand(1);
10491   SDValue RHS = Op.getOperand(2);
10492   SDLoc dl(Op);
10493   MVT VT = Op.getSimpleValueType();
10494
10495   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
10496     return SDValue();
10497   auto *CondBV = cast<BuildVectorSDNode>(Cond);
10498
10499   // Only non-legal VSELECTs reach this lowering, convert those into generic
10500   // shuffles and re-use the shuffle lowering path for blends.
10501   SmallVector<int, 32> Mask;
10502   for (int i = 0, Size = VT.getVectorNumElements(); i < Size; ++i) {
10503     SDValue CondElt = CondBV->getOperand(i);
10504     Mask.push_back(
10505         isa<ConstantSDNode>(CondElt) ? i + (isZero(CondElt) ? Size : 0) : -1);
10506   }
10507   return DAG.getVectorShuffle(VT, dl, LHS, RHS, Mask);
10508 }
10509
10510 SDValue X86TargetLowering::LowerVSELECT(SDValue Op, SelectionDAG &DAG) const {
10511   // A vselect where all conditions and data are constants can be optimized into
10512   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
10513   if (ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(0).getNode()) &&
10514       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(1).getNode()) &&
10515       ISD::isBuildVectorOfConstantSDNodes(Op.getOperand(2).getNode()))
10516     return SDValue();
10517
10518   // Try to lower this to a blend-style vector shuffle. This can handle all
10519   // constant condition cases.
10520   if (SDValue BlendOp = lowerVSELECTtoVectorShuffle(Op, Subtarget, DAG))
10521     return BlendOp;
10522
10523   // Variable blends are only legal from SSE4.1 onward.
10524   if (!Subtarget->hasSSE41())
10525     return SDValue();
10526
10527   // Only some types will be legal on some subtargets. If we can emit a legal
10528   // VSELECT-matching blend, return Op, and but if we need to expand, return
10529   // a null value.
10530   switch (Op.getSimpleValueType().SimpleTy) {
10531   default:
10532     // Most of the vector types have blends past SSE4.1.
10533     return Op;
10534
10535   case MVT::v32i8:
10536     // The byte blends for AVX vectors were introduced only in AVX2.
10537     if (Subtarget->hasAVX2())
10538       return Op;
10539
10540     return SDValue();
10541
10542   case MVT::v8i16:
10543   case MVT::v16i16:
10544     // AVX-512 BWI and VLX features support VSELECT with i16 elements.
10545     if (Subtarget->hasBWI() && Subtarget->hasVLX())
10546       return Op;
10547
10548     // FIXME: We should custom lower this by fixing the condition and using i8
10549     // blends.
10550     return SDValue();
10551   }
10552 }
10553
10554 static SDValue LowerEXTRACT_VECTOR_ELT_SSE4(SDValue Op, SelectionDAG &DAG) {
10555   MVT VT = Op.getSimpleValueType();
10556   SDLoc dl(Op);
10557
10558   if (!Op.getOperand(0).getSimpleValueType().is128BitVector())
10559     return SDValue();
10560
10561   if (VT.getSizeInBits() == 8) {
10562     SDValue Extract = DAG.getNode(X86ISD::PEXTRB, dl, MVT::i32,
10563                                   Op.getOperand(0), Op.getOperand(1));
10564     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10565                                   DAG.getValueType(VT));
10566     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10567   }
10568
10569   if (VT.getSizeInBits() == 16) {
10570     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10571     // If Idx is 0, it's cheaper to do a move instead of a pextrw.
10572     if (Idx == 0)
10573       return DAG.getNode(
10574           ISD::TRUNCATE, dl, MVT::i16,
10575           DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10576                       DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10577                       Op.getOperand(1)));
10578     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, MVT::i32,
10579                                   Op.getOperand(0), Op.getOperand(1));
10580     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, MVT::i32, Extract,
10581                                   DAG.getValueType(VT));
10582     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10583   }
10584
10585   if (VT == MVT::f32) {
10586     // EXTRACTPS outputs to a GPR32 register which will require a movd to copy
10587     // the result back to FR32 register. It's only worth matching if the
10588     // result has a single use which is a store or a bitcast to i32.  And in
10589     // the case of a store, it's not worth it if the index is a constant 0,
10590     // because a MOVSSmr can be used instead, which is smaller and faster.
10591     if (!Op.hasOneUse())
10592       return SDValue();
10593     SDNode *User = *Op.getNode()->use_begin();
10594     if ((User->getOpcode() != ISD::STORE ||
10595          (isa<ConstantSDNode>(Op.getOperand(1)) &&
10596           cast<ConstantSDNode>(Op.getOperand(1))->isNullValue())) &&
10597         (User->getOpcode() != ISD::BITCAST ||
10598          User->getValueType(0) != MVT::i32))
10599       return SDValue();
10600     SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10601                                   DAG.getBitcast(MVT::v4i32, Op.getOperand(0)),
10602                                   Op.getOperand(1));
10603     return DAG.getBitcast(MVT::f32, Extract);
10604   }
10605
10606   if (VT == MVT::i32 || VT == MVT::i64) {
10607     // ExtractPS/pextrq works with constant index.
10608     if (isa<ConstantSDNode>(Op.getOperand(1)))
10609       return Op;
10610   }
10611   return SDValue();
10612 }
10613
10614 /// Extract one bit from mask vector, like v16i1 or v8i1.
10615 /// AVX-512 feature.
10616 SDValue
10617 X86TargetLowering::ExtractBitFromMaskVector(SDValue Op, SelectionDAG &DAG) const {
10618   SDValue Vec = Op.getOperand(0);
10619   SDLoc dl(Vec);
10620   MVT VecVT = Vec.getSimpleValueType();
10621   SDValue Idx = Op.getOperand(1);
10622   MVT EltVT = Op.getSimpleValueType();
10623
10624   assert((EltVT == MVT::i1) && "Unexpected operands in ExtractBitFromMaskVector");
10625   assert((VecVT.getVectorNumElements() <= 16 || Subtarget->hasBWI()) &&
10626          "Unexpected vector type in ExtractBitFromMaskVector");
10627
10628   // variable index can't be handled in mask registers,
10629   // extend vector to VR512
10630   if (!isa<ConstantSDNode>(Idx)) {
10631     MVT ExtVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10632     SDValue Ext = DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVT, Vec);
10633     SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
10634                               ExtVT.getVectorElementType(), Ext, Idx);
10635     return DAG.getNode(ISD::TRUNCATE, dl, EltVT, Elt);
10636   }
10637
10638   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10639   const TargetRegisterClass* rc = getRegClassFor(VecVT);
10640   if (!Subtarget->hasDQI() && (VecVT.getVectorNumElements() <= 8))
10641     rc = getRegClassFor(MVT::v16i1);
10642   unsigned MaxSift = rc->getSize()*8 - 1;
10643   Vec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, Vec,
10644                     DAG.getConstant(MaxSift - IdxVal, dl, MVT::i8));
10645   Vec = DAG.getNode(X86ISD::VSRLI, dl, VecVT, Vec,
10646                     DAG.getConstant(MaxSift, dl, MVT::i8));
10647   return DAG.getNode(X86ISD::VEXTRACT, dl, MVT::i1, Vec,
10648                        DAG.getIntPtrConstant(0, dl));
10649 }
10650
10651 SDValue
10652 X86TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
10653                                            SelectionDAG &DAG) const {
10654   SDLoc dl(Op);
10655   SDValue Vec = Op.getOperand(0);
10656   MVT VecVT = Vec.getSimpleValueType();
10657   SDValue Idx = Op.getOperand(1);
10658
10659   if (Op.getSimpleValueType() == MVT::i1)
10660     return ExtractBitFromMaskVector(Op, DAG);
10661
10662   if (!isa<ConstantSDNode>(Idx)) {
10663     if (VecVT.is512BitVector() ||
10664         (VecVT.is256BitVector() && Subtarget->hasInt256() &&
10665          VecVT.getVectorElementType().getSizeInBits() == 32)) {
10666
10667       MVT MaskEltVT =
10668         MVT::getIntegerVT(VecVT.getVectorElementType().getSizeInBits());
10669       MVT MaskVT = MVT::getVectorVT(MaskEltVT, VecVT.getSizeInBits() /
10670                                     MaskEltVT.getSizeInBits());
10671
10672       Idx = DAG.getZExtOrTrunc(Idx, dl, MaskEltVT);
10673       SDValue Mask = DAG.getNode(X86ISD::VINSERT, dl, MaskVT,
10674                                 getZeroVector(MaskVT, Subtarget, DAG, dl),
10675                                 Idx, DAG.getConstant(0, dl, getPointerTy()));
10676       SDValue Perm = DAG.getNode(X86ISD::VPERMV, dl, VecVT, Mask, Vec);
10677       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(),
10678                         Perm, DAG.getConstant(0, dl, getPointerTy()));
10679     }
10680     return SDValue();
10681   }
10682
10683   // If this is a 256-bit vector result, first extract the 128-bit vector and
10684   // then extract the element from the 128-bit vector.
10685   if (VecVT.is256BitVector() || VecVT.is512BitVector()) {
10686
10687     unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10688     // Get the 128-bit vector.
10689     Vec = Extract128BitVector(Vec, IdxVal, DAG, dl);
10690     MVT EltVT = VecVT.getVectorElementType();
10691
10692     unsigned ElemsPerChunk = 128 / EltVT.getSizeInBits();
10693
10694     //if (IdxVal >= NumElems/2)
10695     //  IdxVal -= NumElems/2;
10696     IdxVal -= (IdxVal/ElemsPerChunk)*ElemsPerChunk;
10697     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, Op.getValueType(), Vec,
10698                        DAG.getConstant(IdxVal, dl, MVT::i32));
10699   }
10700
10701   assert(VecVT.is128BitVector() && "Unexpected vector length");
10702
10703   if (Subtarget->hasSSE41())
10704     if (SDValue Res = LowerEXTRACT_VECTOR_ELT_SSE4(Op, DAG))
10705       return Res;
10706
10707   MVT VT = Op.getSimpleValueType();
10708   // TODO: handle v16i8.
10709   if (VT.getSizeInBits() == 16) {
10710     SDValue Vec = Op.getOperand(0);
10711     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10712     if (Idx == 0)
10713       return DAG.getNode(ISD::TRUNCATE, dl, MVT::i16,
10714                          DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i32,
10715                                      DAG.getBitcast(MVT::v4i32, Vec),
10716                                      Op.getOperand(1)));
10717     // Transform it so it match pextrw which produces a 32-bit result.
10718     MVT EltVT = MVT::i32;
10719     SDValue Extract = DAG.getNode(X86ISD::PEXTRW, dl, EltVT,
10720                                   Op.getOperand(0), Op.getOperand(1));
10721     SDValue Assert  = DAG.getNode(ISD::AssertZext, dl, EltVT, Extract,
10722                                   DAG.getValueType(VT));
10723     return DAG.getNode(ISD::TRUNCATE, dl, VT, Assert);
10724   }
10725
10726   if (VT.getSizeInBits() == 32) {
10727     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10728     if (Idx == 0)
10729       return Op;
10730
10731     // SHUFPS the element to the lowest double word, then movss.
10732     int Mask[4] = { static_cast<int>(Idx), -1, -1, -1 };
10733     MVT VVT = Op.getOperand(0).getSimpleValueType();
10734     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10735                                        DAG.getUNDEF(VVT), Mask);
10736     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10737                        DAG.getIntPtrConstant(0, dl));
10738   }
10739
10740   if (VT.getSizeInBits() == 64) {
10741     // FIXME: .td only matches this for <2 x f64>, not <2 x i64> on 32b
10742     // FIXME: seems like this should be unnecessary if mov{h,l}pd were taught
10743     //        to match extract_elt for f64.
10744     unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
10745     if (Idx == 0)
10746       return Op;
10747
10748     // UNPCKHPD the element to the lowest double word, then movsd.
10749     // Note if the lower 64 bits of the result of the UNPCKHPD is then stored
10750     // to a f64mem, the whole operation is folded into a single MOVHPDmr.
10751     int Mask[2] = { 1, -1 };
10752     MVT VVT = Op.getOperand(0).getSimpleValueType();
10753     SDValue Vec = DAG.getVectorShuffle(VVT, dl, Op.getOperand(0),
10754                                        DAG.getUNDEF(VVT), Mask);
10755     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT, Vec,
10756                        DAG.getIntPtrConstant(0, dl));
10757   }
10758
10759   return SDValue();
10760 }
10761
10762 /// Insert one bit to mask vector, like v16i1 or v8i1.
10763 /// AVX-512 feature.
10764 SDValue
10765 X86TargetLowering::InsertBitToMaskVector(SDValue Op, SelectionDAG &DAG) const {
10766   SDLoc dl(Op);
10767   SDValue Vec = Op.getOperand(0);
10768   SDValue Elt = Op.getOperand(1);
10769   SDValue Idx = Op.getOperand(2);
10770   MVT VecVT = Vec.getSimpleValueType();
10771
10772   if (!isa<ConstantSDNode>(Idx)) {
10773     // Non constant index. Extend source and destination,
10774     // insert element and then truncate the result.
10775     MVT ExtVecVT = (VecVT == MVT::v8i1 ?  MVT::v8i64 : MVT::v16i32);
10776     MVT ExtEltVT = (VecVT == MVT::v8i1 ?  MVT::i64 : MVT::i32);
10777     SDValue ExtOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, ExtVecVT,
10778       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtVecVT, Vec),
10779       DAG.getNode(ISD::ZERO_EXTEND, dl, ExtEltVT, Elt), Idx);
10780     return DAG.getNode(ISD::TRUNCATE, dl, VecVT, ExtOp);
10781   }
10782
10783   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10784   SDValue EltInVec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VecVT, Elt);
10785   if (IdxVal)
10786     EltInVec = DAG.getNode(X86ISD::VSHLI, dl, VecVT, EltInVec,
10787                            DAG.getConstant(IdxVal, dl, MVT::i8));
10788   if (Vec.getOpcode() == ISD::UNDEF)
10789     return EltInVec;
10790   return DAG.getNode(ISD::OR, dl, VecVT, Vec, EltInVec);
10791 }
10792
10793 SDValue X86TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
10794                                                   SelectionDAG &DAG) const {
10795   MVT VT = Op.getSimpleValueType();
10796   MVT EltVT = VT.getVectorElementType();
10797
10798   if (EltVT == MVT::i1)
10799     return InsertBitToMaskVector(Op, DAG);
10800
10801   SDLoc dl(Op);
10802   SDValue N0 = Op.getOperand(0);
10803   SDValue N1 = Op.getOperand(1);
10804   SDValue N2 = Op.getOperand(2);
10805   if (!isa<ConstantSDNode>(N2))
10806     return SDValue();
10807   auto *N2C = cast<ConstantSDNode>(N2);
10808   unsigned IdxVal = N2C->getZExtValue();
10809
10810   // If the vector is wider than 128 bits, extract the 128-bit subvector, insert
10811   // into that, and then insert the subvector back into the result.
10812   if (VT.is256BitVector() || VT.is512BitVector()) {
10813     // With a 256-bit vector, we can insert into the zero element efficiently
10814     // using a blend if we have AVX or AVX2 and the right data type.
10815     if (VT.is256BitVector() && IdxVal == 0) {
10816       // TODO: It is worthwhile to cast integer to floating point and back
10817       // and incur a domain crossing penalty if that's what we'll end up
10818       // doing anyway after extracting to a 128-bit vector.
10819       if ((Subtarget->hasAVX() && (EltVT == MVT::f64 || EltVT == MVT::f32)) ||
10820           (Subtarget->hasAVX2() && EltVT == MVT::i32)) {
10821         SDValue N1Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, N1);
10822         N2 = DAG.getIntPtrConstant(1, dl);
10823         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1Vec, N2);
10824       }
10825     }
10826
10827     // Get the desired 128-bit vector chunk.
10828     SDValue V = Extract128BitVector(N0, IdxVal, DAG, dl);
10829
10830     // Insert the element into the desired chunk.
10831     unsigned NumEltsIn128 = 128 / EltVT.getSizeInBits();
10832     unsigned IdxIn128 = IdxVal - (IdxVal / NumEltsIn128) * NumEltsIn128;
10833
10834     V = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, V.getValueType(), V, N1,
10835                     DAG.getConstant(IdxIn128, dl, MVT::i32));
10836
10837     // Insert the changed part back into the bigger vector
10838     return Insert128BitVector(N0, V, IdxVal, DAG, dl);
10839   }
10840   assert(VT.is128BitVector() && "Only 128-bit vector types should be left!");
10841
10842   if (Subtarget->hasSSE41()) {
10843     if (EltVT.getSizeInBits() == 8 || EltVT.getSizeInBits() == 16) {
10844       unsigned Opc;
10845       if (VT == MVT::v8i16) {
10846         Opc = X86ISD::PINSRW;
10847       } else {
10848         assert(VT == MVT::v16i8);
10849         Opc = X86ISD::PINSRB;
10850       }
10851
10852       // Transform it so it match pinsr{b,w} which expects a GR32 as its second
10853       // argument.
10854       if (N1.getValueType() != MVT::i32)
10855         N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10856       if (N2.getValueType() != MVT::i32)
10857         N2 = DAG.getIntPtrConstant(IdxVal, dl);
10858       return DAG.getNode(Opc, dl, VT, N0, N1, N2);
10859     }
10860
10861     if (EltVT == MVT::f32) {
10862       // Bits [7:6] of the constant are the source select. This will always be
10863       //   zero here. The DAG Combiner may combine an extract_elt index into
10864       //   these bits. For example (insert (extract, 3), 2) could be matched by
10865       //   putting the '3' into bits [7:6] of X86ISD::INSERTPS.
10866       // Bits [5:4] of the constant are the destination select. This is the
10867       //   value of the incoming immediate.
10868       // Bits [3:0] of the constant are the zero mask. The DAG Combiner may
10869       //   combine either bitwise AND or insert of float 0.0 to set these bits.
10870
10871       const Function *F = DAG.getMachineFunction().getFunction();
10872       bool MinSize = F->hasFnAttribute(Attribute::MinSize);
10873       if (IdxVal == 0 && (!MinSize || !MayFoldLoad(N1))) {
10874         // If this is an insertion of 32-bits into the low 32-bits of
10875         // a vector, we prefer to generate a blend with immediate rather
10876         // than an insertps. Blends are simpler operations in hardware and so
10877         // will always have equal or better performance than insertps.
10878         // But if optimizing for size and there's a load folding opportunity,
10879         // generate insertps because blendps does not have a 32-bit memory
10880         // operand form.
10881         N2 = DAG.getIntPtrConstant(1, dl);
10882         N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10883         return DAG.getNode(X86ISD::BLENDI, dl, VT, N0, N1, N2);
10884       }
10885       N2 = DAG.getIntPtrConstant(IdxVal << 4, dl);
10886       // Create this as a scalar to vector..
10887       N1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4f32, N1);
10888       return DAG.getNode(X86ISD::INSERTPS, dl, VT, N0, N1, N2);
10889     }
10890
10891     if (EltVT == MVT::i32 || EltVT == MVT::i64) {
10892       // PINSR* works with constant index.
10893       return Op;
10894     }
10895   }
10896
10897   if (EltVT == MVT::i8)
10898     return SDValue();
10899
10900   if (EltVT.getSizeInBits() == 16) {
10901     // Transform it so it match pinsrw which expects a 16-bit value in a GR32
10902     // as its second argument.
10903     if (N1.getValueType() != MVT::i32)
10904       N1 = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, N1);
10905     if (N2.getValueType() != MVT::i32)
10906       N2 = DAG.getIntPtrConstant(IdxVal, dl);
10907     return DAG.getNode(X86ISD::PINSRW, dl, VT, N0, N1, N2);
10908   }
10909   return SDValue();
10910 }
10911
10912 static SDValue LowerSCALAR_TO_VECTOR(SDValue Op, SelectionDAG &DAG) {
10913   SDLoc dl(Op);
10914   MVT OpVT = Op.getSimpleValueType();
10915
10916   // If this is a 256-bit vector result, first insert into a 128-bit
10917   // vector and then insert into the 256-bit vector.
10918   if (!OpVT.is128BitVector()) {
10919     // Insert into a 128-bit vector.
10920     unsigned SizeFactor = OpVT.getSizeInBits()/128;
10921     MVT VT128 = MVT::getVectorVT(OpVT.getVectorElementType(),
10922                                  OpVT.getVectorNumElements() / SizeFactor);
10923
10924     Op = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT128, Op.getOperand(0));
10925
10926     // Insert the 128-bit vector.
10927     return Insert128BitVector(DAG.getUNDEF(OpVT), Op, 0, DAG, dl);
10928   }
10929
10930   if (OpVT == MVT::v1i64 &&
10931       Op.getOperand(0).getValueType() == MVT::i64)
10932     return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v1i64, Op.getOperand(0));
10933
10934   SDValue AnyExt = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Op.getOperand(0));
10935   assert(OpVT.is128BitVector() && "Expected an SSE type!");
10936   return DAG.getBitcast(
10937       OpVT, DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32, AnyExt));
10938 }
10939
10940 // Lower a node with an EXTRACT_SUBVECTOR opcode.  This may result in
10941 // a simple subregister reference or explicit instructions to grab
10942 // upper bits of a vector.
10943 static SDValue LowerEXTRACT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10944                                       SelectionDAG &DAG) {
10945   SDLoc dl(Op);
10946   SDValue In =  Op.getOperand(0);
10947   SDValue Idx = Op.getOperand(1);
10948   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10949   MVT ResVT   = Op.getSimpleValueType();
10950   MVT InVT    = In.getSimpleValueType();
10951
10952   if (Subtarget->hasFp256()) {
10953     if (ResVT.is128BitVector() &&
10954         (InVT.is256BitVector() || InVT.is512BitVector()) &&
10955         isa<ConstantSDNode>(Idx)) {
10956       return Extract128BitVector(In, IdxVal, DAG, dl);
10957     }
10958     if (ResVT.is256BitVector() && InVT.is512BitVector() &&
10959         isa<ConstantSDNode>(Idx)) {
10960       return Extract256BitVector(In, IdxVal, DAG, dl);
10961     }
10962   }
10963   return SDValue();
10964 }
10965
10966 // Lower a node with an INSERT_SUBVECTOR opcode.  This may result in a
10967 // simple superregister reference or explicit instructions to insert
10968 // the upper bits of a vector.
10969 static SDValue LowerINSERT_SUBVECTOR(SDValue Op, const X86Subtarget *Subtarget,
10970                                      SelectionDAG &DAG) {
10971   if (!Subtarget->hasAVX())
10972     return SDValue();
10973
10974   SDLoc dl(Op);
10975   SDValue Vec = Op.getOperand(0);
10976   SDValue SubVec = Op.getOperand(1);
10977   SDValue Idx = Op.getOperand(2);
10978
10979   if (!isa<ConstantSDNode>(Idx))
10980     return SDValue();
10981
10982   unsigned IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
10983   MVT OpVT = Op.getSimpleValueType();
10984   MVT SubVecVT = SubVec.getSimpleValueType();
10985
10986   // Fold two 16-byte subvector loads into one 32-byte load:
10987   // (insert_subvector (insert_subvector undef, (load addr), 0),
10988   //                   (load addr + 16), Elts/2)
10989   // --> load32 addr
10990   if ((IdxVal == OpVT.getVectorNumElements() / 2) &&
10991       Vec.getOpcode() == ISD::INSERT_SUBVECTOR &&
10992       OpVT.is256BitVector() && SubVecVT.is128BitVector() &&
10993       !Subtarget->isUnalignedMem32Slow()) {
10994     SDValue SubVec2 = Vec.getOperand(1);
10995     if (auto *Idx2 = dyn_cast<ConstantSDNode>(Vec.getOperand(2))) {
10996       if (Idx2->getZExtValue() == 0) {
10997         SDValue Ops[] = { SubVec2, SubVec };
10998         if (SDValue Ld = EltsFromConsecutiveLoads(OpVT, Ops, dl, DAG, false))
10999           return Ld;
11000       }
11001     }
11002   }
11003
11004   if ((OpVT.is256BitVector() || OpVT.is512BitVector()) &&
11005       SubVecVT.is128BitVector())
11006     return Insert128BitVector(Vec, SubVec, IdxVal, DAG, dl);
11007
11008   if (OpVT.is512BitVector() && SubVecVT.is256BitVector())
11009     return Insert256BitVector(Vec, SubVec, IdxVal, DAG, dl);
11010
11011   if (OpVT.getVectorElementType() == MVT::i1) {
11012     if (IdxVal == 0  && Vec.getOpcode() == ISD::UNDEF) // the operation is legal
11013       return Op;
11014     SDValue ZeroIdx = DAG.getIntPtrConstant(0, dl);
11015     SDValue Undef = DAG.getUNDEF(OpVT);
11016     unsigned NumElems = OpVT.getVectorNumElements();
11017     SDValue ShiftBits = DAG.getConstant(NumElems/2, dl, MVT::i8);
11018
11019     if (IdxVal == OpVT.getVectorNumElements() / 2) {
11020       // Zero upper bits of the Vec
11021       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11022       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11023
11024       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11025                                  SubVec, ZeroIdx);
11026       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11027       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11028     }
11029     if (IdxVal == 0) {
11030       SDValue Vec2 = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, OpVT, Undef,
11031                                  SubVec, ZeroIdx);
11032       // Zero upper bits of the Vec2
11033       Vec2 = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec2, ShiftBits);
11034       Vec2 = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec2, ShiftBits);
11035       // Zero lower bits of the Vec
11036       Vec = DAG.getNode(X86ISD::VSRLI, dl, OpVT, Vec, ShiftBits);
11037       Vec = DAG.getNode(X86ISD::VSHLI, dl, OpVT, Vec, ShiftBits);
11038       // Merge them together
11039       return DAG.getNode(ISD::OR, dl, OpVT, Vec, Vec2);
11040     }
11041   }
11042   return SDValue();
11043 }
11044
11045 // ConstantPool, JumpTable, GlobalAddress, and ExternalSymbol are lowered as
11046 // their target countpart wrapped in the X86ISD::Wrapper node. Suppose N is
11047 // one of the above mentioned nodes. It has to be wrapped because otherwise
11048 // Select(N) returns N. So the raw TargetGlobalAddress nodes, etc. can only
11049 // be used to form addressing mode. These wrapped nodes will be selected
11050 // into MOV32ri.
11051 SDValue
11052 X86TargetLowering::LowerConstantPool(SDValue Op, SelectionDAG &DAG) const {
11053   ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
11054
11055   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11056   // global base reg.
11057   unsigned char OpFlag = 0;
11058   unsigned WrapperKind = X86ISD::Wrapper;
11059   CodeModel::Model M = DAG.getTarget().getCodeModel();
11060
11061   if (Subtarget->isPICStyleRIPRel() &&
11062       (M == CodeModel::Small || M == CodeModel::Kernel))
11063     WrapperKind = X86ISD::WrapperRIP;
11064   else if (Subtarget->isPICStyleGOT())
11065     OpFlag = X86II::MO_GOTOFF;
11066   else if (Subtarget->isPICStyleStubPIC())
11067     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11068
11069   SDValue Result = DAG.getTargetConstantPool(CP->getConstVal(), getPointerTy(),
11070                                              CP->getAlignment(),
11071                                              CP->getOffset(), OpFlag);
11072   SDLoc DL(CP);
11073   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11074   // With PIC, the address is actually $g + Offset.
11075   if (OpFlag) {
11076     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11077                          DAG.getNode(X86ISD::GlobalBaseReg,
11078                                      SDLoc(), getPointerTy()),
11079                          Result);
11080   }
11081
11082   return Result;
11083 }
11084
11085 SDValue X86TargetLowering::LowerJumpTable(SDValue Op, SelectionDAG &DAG) const {
11086   JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
11087
11088   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11089   // global base reg.
11090   unsigned char OpFlag = 0;
11091   unsigned WrapperKind = X86ISD::Wrapper;
11092   CodeModel::Model M = DAG.getTarget().getCodeModel();
11093
11094   if (Subtarget->isPICStyleRIPRel() &&
11095       (M == CodeModel::Small || M == CodeModel::Kernel))
11096     WrapperKind = X86ISD::WrapperRIP;
11097   else if (Subtarget->isPICStyleGOT())
11098     OpFlag = X86II::MO_GOTOFF;
11099   else if (Subtarget->isPICStyleStubPIC())
11100     OpFlag = X86II::MO_PIC_BASE_OFFSET;
11101
11102   SDValue Result = DAG.getTargetJumpTable(JT->getIndex(), getPointerTy(),
11103                                           OpFlag);
11104   SDLoc DL(JT);
11105   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11106
11107   // With PIC, the address is actually $g + Offset.
11108   if (OpFlag)
11109     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11110                          DAG.getNode(X86ISD::GlobalBaseReg,
11111                                      SDLoc(), getPointerTy()),
11112                          Result);
11113
11114   return Result;
11115 }
11116
11117 SDValue
11118 X86TargetLowering::LowerExternalSymbol(SDValue Op, SelectionDAG &DAG) const {
11119   const char *Sym = cast<ExternalSymbolSDNode>(Op)->getSymbol();
11120
11121   // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11122   // global base reg.
11123   unsigned char OpFlag = 0;
11124   unsigned WrapperKind = X86ISD::Wrapper;
11125   CodeModel::Model M = DAG.getTarget().getCodeModel();
11126
11127   if (Subtarget->isPICStyleRIPRel() &&
11128       (M == CodeModel::Small || M == CodeModel::Kernel)) {
11129     if (Subtarget->isTargetDarwin() || Subtarget->isTargetELF())
11130       OpFlag = X86II::MO_GOTPCREL;
11131     WrapperKind = X86ISD::WrapperRIP;
11132   } else if (Subtarget->isPICStyleGOT()) {
11133     OpFlag = X86II::MO_GOT;
11134   } else if (Subtarget->isPICStyleStubPIC()) {
11135     OpFlag = X86II::MO_DARWIN_NONLAZY_PIC_BASE;
11136   } else if (Subtarget->isPICStyleStubNoDynamic()) {
11137     OpFlag = X86II::MO_DARWIN_NONLAZY;
11138   }
11139
11140   SDValue Result = DAG.getTargetExternalSymbol(Sym, getPointerTy(), OpFlag);
11141
11142   SDLoc DL(Op);
11143   Result = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11144
11145   // With PIC, the address is actually $g + Offset.
11146   if (DAG.getTarget().getRelocationModel() == Reloc::PIC_ &&
11147       !Subtarget->is64Bit()) {
11148     Result = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11149                          DAG.getNode(X86ISD::GlobalBaseReg,
11150                                      SDLoc(), getPointerTy()),
11151                          Result);
11152   }
11153
11154   // For symbols that require a load from a stub to get the address, emit the
11155   // load.
11156   if (isGlobalStubReference(OpFlag))
11157     Result = DAG.getLoad(getPointerTy(), DL, DAG.getEntryNode(), Result,
11158                          MachinePointerInfo::getGOT(), false, false, false, 0);
11159
11160   return Result;
11161 }
11162
11163 SDValue
11164 X86TargetLowering::LowerBlockAddress(SDValue Op, SelectionDAG &DAG) const {
11165   // Create the TargetBlockAddressAddress node.
11166   unsigned char OpFlags =
11167     Subtarget->ClassifyBlockAddressReference();
11168   CodeModel::Model M = DAG.getTarget().getCodeModel();
11169   const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
11170   int64_t Offset = cast<BlockAddressSDNode>(Op)->getOffset();
11171   SDLoc dl(Op);
11172   SDValue Result = DAG.getTargetBlockAddress(BA, getPointerTy(), Offset,
11173                                              OpFlags);
11174
11175   if (Subtarget->isPICStyleRIPRel() &&
11176       (M == CodeModel::Small || M == CodeModel::Kernel))
11177     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11178   else
11179     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11180
11181   // With PIC, the address is actually $g + Offset.
11182   if (isGlobalRelativeToPICBase(OpFlags)) {
11183     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11184                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11185                          Result);
11186   }
11187
11188   return Result;
11189 }
11190
11191 SDValue
11192 X86TargetLowering::LowerGlobalAddress(const GlobalValue *GV, SDLoc dl,
11193                                       int64_t Offset, SelectionDAG &DAG) const {
11194   // Create the TargetGlobalAddress node, folding in the constant
11195   // offset if it is legal.
11196   unsigned char OpFlags =
11197       Subtarget->ClassifyGlobalReference(GV, DAG.getTarget());
11198   CodeModel::Model M = DAG.getTarget().getCodeModel();
11199   SDValue Result;
11200   if (OpFlags == X86II::MO_NO_FLAG &&
11201       X86::isOffsetSuitableForCodeModel(Offset, M)) {
11202     // A direct static reference to a global.
11203     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), Offset);
11204     Offset = 0;
11205   } else {
11206     Result = DAG.getTargetGlobalAddress(GV, dl, getPointerTy(), 0, OpFlags);
11207   }
11208
11209   if (Subtarget->isPICStyleRIPRel() &&
11210       (M == CodeModel::Small || M == CodeModel::Kernel))
11211     Result = DAG.getNode(X86ISD::WrapperRIP, dl, getPointerTy(), Result);
11212   else
11213     Result = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), Result);
11214
11215   // With PIC, the address is actually $g + Offset.
11216   if (isGlobalRelativeToPICBase(OpFlags)) {
11217     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(),
11218                          DAG.getNode(X86ISD::GlobalBaseReg, dl, getPointerTy()),
11219                          Result);
11220   }
11221
11222   // For globals that require a load from a stub to get the address, emit the
11223   // load.
11224   if (isGlobalStubReference(OpFlags))
11225     Result = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(), Result,
11226                          MachinePointerInfo::getGOT(), false, false, false, 0);
11227
11228   // If there was a non-zero offset that we didn't fold, create an explicit
11229   // addition for it.
11230   if (Offset != 0)
11231     Result = DAG.getNode(ISD::ADD, dl, getPointerTy(), Result,
11232                          DAG.getConstant(Offset, dl, getPointerTy()));
11233
11234   return Result;
11235 }
11236
11237 SDValue
11238 X86TargetLowering::LowerGlobalAddress(SDValue Op, SelectionDAG &DAG) const {
11239   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
11240   int64_t Offset = cast<GlobalAddressSDNode>(Op)->getOffset();
11241   return LowerGlobalAddress(GV, SDLoc(Op), Offset, DAG);
11242 }
11243
11244 static SDValue
11245 GetTLSADDR(SelectionDAG &DAG, SDValue Chain, GlobalAddressSDNode *GA,
11246            SDValue *InFlag, const EVT PtrVT, unsigned ReturnReg,
11247            unsigned char OperandFlags, bool LocalDynamic = false) {
11248   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11249   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11250   SDLoc dl(GA);
11251   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11252                                            GA->getValueType(0),
11253                                            GA->getOffset(),
11254                                            OperandFlags);
11255
11256   X86ISD::NodeType CallType = LocalDynamic ? X86ISD::TLSBASEADDR
11257                                            : X86ISD::TLSADDR;
11258
11259   if (InFlag) {
11260     SDValue Ops[] = { Chain,  TGA, *InFlag };
11261     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11262   } else {
11263     SDValue Ops[]  = { Chain, TGA };
11264     Chain = DAG.getNode(CallType, dl, NodeTys, Ops);
11265   }
11266
11267   // TLSADDR will be codegen'ed as call. Inform MFI that function has calls.
11268   MFI->setAdjustsStack(true);
11269   MFI->setHasCalls(true);
11270
11271   SDValue Flag = Chain.getValue(1);
11272   return DAG.getCopyFromReg(Chain, dl, ReturnReg, PtrVT, Flag);
11273 }
11274
11275 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 32 bit
11276 static SDValue
11277 LowerToTLSGeneralDynamicModel32(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11278                                 const EVT PtrVT) {
11279   SDValue InFlag;
11280   SDLoc dl(GA);  // ? function entry point might be better
11281   SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11282                                    DAG.getNode(X86ISD::GlobalBaseReg,
11283                                                SDLoc(), PtrVT), InFlag);
11284   InFlag = Chain.getValue(1);
11285
11286   return GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX, X86II::MO_TLSGD);
11287 }
11288
11289 // Lower ISD::GlobalTLSAddress using the "general dynamic" model, 64 bit
11290 static SDValue
11291 LowerToTLSGeneralDynamicModel64(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11292                                 const EVT PtrVT) {
11293   return GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT,
11294                     X86::RAX, X86II::MO_TLSGD);
11295 }
11296
11297 static SDValue LowerToTLSLocalDynamicModel(GlobalAddressSDNode *GA,
11298                                            SelectionDAG &DAG,
11299                                            const EVT PtrVT,
11300                                            bool is64Bit) {
11301   SDLoc dl(GA);
11302
11303   // Get the start address of the TLS block for this module.
11304   X86MachineFunctionInfo* MFI = DAG.getMachineFunction()
11305       .getInfo<X86MachineFunctionInfo>();
11306   MFI->incNumLocalDynamicTLSAccesses();
11307
11308   SDValue Base;
11309   if (is64Bit) {
11310     Base = GetTLSADDR(DAG, DAG.getEntryNode(), GA, nullptr, PtrVT, X86::RAX,
11311                       X86II::MO_TLSLD, /*LocalDynamic=*/true);
11312   } else {
11313     SDValue InFlag;
11314     SDValue Chain = DAG.getCopyToReg(DAG.getEntryNode(), dl, X86::EBX,
11315         DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT), InFlag);
11316     InFlag = Chain.getValue(1);
11317     Base = GetTLSADDR(DAG, Chain, GA, &InFlag, PtrVT, X86::EAX,
11318                       X86II::MO_TLSLDM, /*LocalDynamic=*/true);
11319   }
11320
11321   // Note: the CleanupLocalDynamicTLSPass will remove redundant computations
11322   // of Base.
11323
11324   // Build x@dtpoff.
11325   unsigned char OperandFlags = X86II::MO_DTPOFF;
11326   unsigned WrapperKind = X86ISD::Wrapper;
11327   SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11328                                            GA->getValueType(0),
11329                                            GA->getOffset(), OperandFlags);
11330   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11331
11332   // Add x@dtpoff with the base.
11333   return DAG.getNode(ISD::ADD, dl, PtrVT, Offset, Base);
11334 }
11335
11336 // Lower ISD::GlobalTLSAddress using the "initial exec" or "local exec" model.
11337 static SDValue LowerToTLSExecModel(GlobalAddressSDNode *GA, SelectionDAG &DAG,
11338                                    const EVT PtrVT, TLSModel::Model model,
11339                                    bool is64Bit, bool isPIC) {
11340   SDLoc dl(GA);
11341
11342   // Get the Thread Pointer, which is %gs:0 (32-bit) or %fs:0 (64-bit).
11343   Value *Ptr = Constant::getNullValue(Type::getInt8PtrTy(*DAG.getContext(),
11344                                                          is64Bit ? 257 : 256));
11345
11346   SDValue ThreadPointer =
11347       DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), DAG.getIntPtrConstant(0, dl),
11348                   MachinePointerInfo(Ptr), false, false, false, 0);
11349
11350   unsigned char OperandFlags = 0;
11351   // Most TLS accesses are not RIP relative, even on x86-64.  One exception is
11352   // initialexec.
11353   unsigned WrapperKind = X86ISD::Wrapper;
11354   if (model == TLSModel::LocalExec) {
11355     OperandFlags = is64Bit ? X86II::MO_TPOFF : X86II::MO_NTPOFF;
11356   } else if (model == TLSModel::InitialExec) {
11357     if (is64Bit) {
11358       OperandFlags = X86II::MO_GOTTPOFF;
11359       WrapperKind = X86ISD::WrapperRIP;
11360     } else {
11361       OperandFlags = isPIC ? X86II::MO_GOTNTPOFF : X86II::MO_INDNTPOFF;
11362     }
11363   } else {
11364     llvm_unreachable("Unexpected model");
11365   }
11366
11367   // emit "addl x@ntpoff,%eax" (local exec)
11368   // or "addl x@indntpoff,%eax" (initial exec)
11369   // or "addl x@gotntpoff(%ebx) ,%eax" (initial exec, 32-bit pic)
11370   SDValue TGA =
11371       DAG.getTargetGlobalAddress(GA->getGlobal(), dl, GA->getValueType(0),
11372                                  GA->getOffset(), OperandFlags);
11373   SDValue Offset = DAG.getNode(WrapperKind, dl, PtrVT, TGA);
11374
11375   if (model == TLSModel::InitialExec) {
11376     if (isPIC && !is64Bit) {
11377       Offset = DAG.getNode(ISD::ADD, dl, PtrVT,
11378                            DAG.getNode(X86ISD::GlobalBaseReg, SDLoc(), PtrVT),
11379                            Offset);
11380     }
11381
11382     Offset = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), Offset,
11383                          MachinePointerInfo::getGOT(), false, false, false, 0);
11384   }
11385
11386   // The address of the thread local variable is the add of the thread
11387   // pointer with the offset of the variable.
11388   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
11389 }
11390
11391 SDValue
11392 X86TargetLowering::LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const {
11393
11394   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
11395   const GlobalValue *GV = GA->getGlobal();
11396
11397   if (Subtarget->isTargetELF()) {
11398     TLSModel::Model model = DAG.getTarget().getTLSModel(GV);
11399     switch (model) {
11400       case TLSModel::GeneralDynamic:
11401         if (Subtarget->is64Bit())
11402           return LowerToTLSGeneralDynamicModel64(GA, DAG, getPointerTy());
11403         return LowerToTLSGeneralDynamicModel32(GA, DAG, getPointerTy());
11404       case TLSModel::LocalDynamic:
11405         return LowerToTLSLocalDynamicModel(GA, DAG, getPointerTy(),
11406                                            Subtarget->is64Bit());
11407       case TLSModel::InitialExec:
11408       case TLSModel::LocalExec:
11409         return LowerToTLSExecModel(
11410             GA, DAG, getPointerTy(), model, Subtarget->is64Bit(),
11411             DAG.getTarget().getRelocationModel() == Reloc::PIC_);
11412     }
11413     llvm_unreachable("Unknown TLS model.");
11414   }
11415
11416   if (Subtarget->isTargetDarwin()) {
11417     // Darwin only has one model of TLS.  Lower to that.
11418     unsigned char OpFlag = 0;
11419     unsigned WrapperKind = Subtarget->isPICStyleRIPRel() ?
11420                            X86ISD::WrapperRIP : X86ISD::Wrapper;
11421
11422     // In PIC mode (unless we're in RIPRel PIC mode) we add an offset to the
11423     // global base reg.
11424     bool PIC32 = (DAG.getTarget().getRelocationModel() == Reloc::PIC_) &&
11425                  !Subtarget->is64Bit();
11426     if (PIC32)
11427       OpFlag = X86II::MO_TLVP_PIC_BASE;
11428     else
11429       OpFlag = X86II::MO_TLVP;
11430     SDLoc DL(Op);
11431     SDValue Result = DAG.getTargetGlobalAddress(GA->getGlobal(), DL,
11432                                                 GA->getValueType(0),
11433                                                 GA->getOffset(), OpFlag);
11434     SDValue Offset = DAG.getNode(WrapperKind, DL, getPointerTy(), Result);
11435
11436     // With PIC32, the address is actually $g + Offset.
11437     if (PIC32)
11438       Offset = DAG.getNode(ISD::ADD, DL, getPointerTy(),
11439                            DAG.getNode(X86ISD::GlobalBaseReg,
11440                                        SDLoc(), getPointerTy()),
11441                            Offset);
11442
11443     // Lowering the machine isd will make sure everything is in the right
11444     // location.
11445     SDValue Chain = DAG.getEntryNode();
11446     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
11447     SDValue Args[] = { Chain, Offset };
11448     Chain = DAG.getNode(X86ISD::TLSCALL, DL, NodeTys, Args);
11449
11450     // TLSCALL will be codegen'ed as call. Inform MFI that function has calls.
11451     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11452     MFI->setAdjustsStack(true);
11453
11454     // And our return value (tls address) is in the standard call return value
11455     // location.
11456     unsigned Reg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
11457     return DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(),
11458                               Chain.getValue(1));
11459   }
11460
11461   if (Subtarget->isTargetKnownWindowsMSVC() ||
11462       Subtarget->isTargetWindowsGNU()) {
11463     // Just use the implicit TLS architecture
11464     // Need to generate someting similar to:
11465     //   mov     rdx, qword [gs:abs 58H]; Load pointer to ThreadLocalStorage
11466     //                                  ; from TEB
11467     //   mov     ecx, dword [rel _tls_index]: Load index (from C runtime)
11468     //   mov     rcx, qword [rdx+rcx*8]
11469     //   mov     eax, .tls$:tlsvar
11470     //   [rax+rcx] contains the address
11471     // Windows 64bit: gs:0x58
11472     // Windows 32bit: fs:__tls_array
11473
11474     SDLoc dl(GA);
11475     SDValue Chain = DAG.getEntryNode();
11476
11477     // Get the Thread Pointer, which is %fs:__tls_array (32-bit) or
11478     // %gs:0x58 (64-bit). On MinGW, __tls_array is not available, so directly
11479     // use its literal value of 0x2C.
11480     Value *Ptr = Constant::getNullValue(Subtarget->is64Bit()
11481                                         ? Type::getInt8PtrTy(*DAG.getContext(),
11482                                                              256)
11483                                         : Type::getInt32PtrTy(*DAG.getContext(),
11484                                                               257));
11485
11486     SDValue TlsArray =
11487         Subtarget->is64Bit()
11488             ? DAG.getIntPtrConstant(0x58, dl)
11489             : (Subtarget->isTargetWindowsGNU()
11490                    ? DAG.getIntPtrConstant(0x2C, dl)
11491                    : DAG.getExternalSymbol("_tls_array", getPointerTy()));
11492
11493     SDValue ThreadPointer =
11494         DAG.getLoad(getPointerTy(), dl, Chain, TlsArray,
11495                     MachinePointerInfo(Ptr), false, false, false, 0);
11496
11497     SDValue res;
11498     if (GV->getThreadLocalMode() == GlobalVariable::LocalExecTLSModel) {
11499       res = ThreadPointer;
11500     } else {
11501       // Load the _tls_index variable
11502       SDValue IDX = DAG.getExternalSymbol("_tls_index", getPointerTy());
11503       if (Subtarget->is64Bit())
11504         IDX = DAG.getExtLoad(ISD::ZEXTLOAD, dl, getPointerTy(), Chain, IDX,
11505                              MachinePointerInfo(), MVT::i32, false, false,
11506                              false, 0);
11507       else
11508         IDX = DAG.getLoad(getPointerTy(), dl, Chain, IDX, MachinePointerInfo(),
11509                           false, false, false, 0);
11510
11511       SDValue Scale = DAG.getConstant(Log2_64_Ceil(TD->getPointerSize()), dl,
11512                                       getPointerTy());
11513       IDX = DAG.getNode(ISD::SHL, dl, getPointerTy(), IDX, Scale);
11514
11515       res = DAG.getNode(ISD::ADD, dl, getPointerTy(), ThreadPointer, IDX);
11516     }
11517
11518     res = DAG.getLoad(getPointerTy(), dl, Chain, res, MachinePointerInfo(),
11519                       false, false, false, 0);
11520
11521     // Get the offset of start of .tls section
11522     SDValue TGA = DAG.getTargetGlobalAddress(GA->getGlobal(), dl,
11523                                              GA->getValueType(0),
11524                                              GA->getOffset(), X86II::MO_SECREL);
11525     SDValue Offset = DAG.getNode(X86ISD::Wrapper, dl, getPointerTy(), TGA);
11526
11527     // The address of the thread local variable is the add of the thread
11528     // pointer with the offset of the variable.
11529     return DAG.getNode(ISD::ADD, dl, getPointerTy(), res, Offset);
11530   }
11531
11532   llvm_unreachable("TLS not implemented for this target.");
11533 }
11534
11535 /// LowerShiftParts - Lower SRA_PARTS and friends, which return two i32 values
11536 /// and take a 2 x i32 value to shift plus a shift amount.
11537 static SDValue LowerShiftParts(SDValue Op, SelectionDAG &DAG) {
11538   assert(Op.getNumOperands() == 3 && "Not a double-shift!");
11539   MVT VT = Op.getSimpleValueType();
11540   unsigned VTBits = VT.getSizeInBits();
11541   SDLoc dl(Op);
11542   bool isSRA = Op.getOpcode() == ISD::SRA_PARTS;
11543   SDValue ShOpLo = Op.getOperand(0);
11544   SDValue ShOpHi = Op.getOperand(1);
11545   SDValue ShAmt  = Op.getOperand(2);
11546   // X86ISD::SHLD and X86ISD::SHRD have defined overflow behavior but the
11547   // generic ISD nodes haven't. Insert an AND to be safe, it's optimized away
11548   // during isel.
11549   SDValue SafeShAmt = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11550                                   DAG.getConstant(VTBits - 1, dl, MVT::i8));
11551   SDValue Tmp1 = isSRA ? DAG.getNode(ISD::SRA, dl, VT, ShOpHi,
11552                                      DAG.getConstant(VTBits - 1, dl, MVT::i8))
11553                        : DAG.getConstant(0, dl, VT);
11554
11555   SDValue Tmp2, Tmp3;
11556   if (Op.getOpcode() == ISD::SHL_PARTS) {
11557     Tmp2 = DAG.getNode(X86ISD::SHLD, dl, VT, ShOpHi, ShOpLo, ShAmt);
11558     Tmp3 = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, SafeShAmt);
11559   } else {
11560     Tmp2 = DAG.getNode(X86ISD::SHRD, dl, VT, ShOpLo, ShOpHi, ShAmt);
11561     Tmp3 = DAG.getNode(isSRA ? ISD::SRA : ISD::SRL, dl, VT, ShOpHi, SafeShAmt);
11562   }
11563
11564   // If the shift amount is larger or equal than the width of a part we can't
11565   // rely on the results of shld/shrd. Insert a test and select the appropriate
11566   // values for large shift amounts.
11567   SDValue AndNode = DAG.getNode(ISD::AND, dl, MVT::i8, ShAmt,
11568                                 DAG.getConstant(VTBits, dl, MVT::i8));
11569   SDValue Cond = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
11570                              AndNode, DAG.getConstant(0, dl, MVT::i8));
11571
11572   SDValue Hi, Lo;
11573   SDValue CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
11574   SDValue Ops0[4] = { Tmp2, Tmp3, CC, Cond };
11575   SDValue Ops1[4] = { Tmp3, Tmp1, CC, Cond };
11576
11577   if (Op.getOpcode() == ISD::SHL_PARTS) {
11578     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11579     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11580   } else {
11581     Lo = DAG.getNode(X86ISD::CMOV, dl, VT, Ops0);
11582     Hi = DAG.getNode(X86ISD::CMOV, dl, VT, Ops1);
11583   }
11584
11585   SDValue Ops[2] = { Lo, Hi };
11586   return DAG.getMergeValues(Ops, dl);
11587 }
11588
11589 SDValue X86TargetLowering::LowerSINT_TO_FP(SDValue Op,
11590                                            SelectionDAG &DAG) const {
11591   SDValue Src = Op.getOperand(0);
11592   MVT SrcVT = Src.getSimpleValueType();
11593   MVT VT = Op.getSimpleValueType();
11594   SDLoc dl(Op);
11595
11596   if (SrcVT.isVector()) {
11597     if (SrcVT == MVT::v2i32 && VT == MVT::v2f64) {
11598       return DAG.getNode(X86ISD::CVTDQ2PD, dl, VT,
11599                          DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4i32, Src,
11600                          DAG.getUNDEF(SrcVT)));
11601     }
11602     if (SrcVT.getVectorElementType() == MVT::i1) {
11603       MVT IntegerVT = MVT::getVectorVT(MVT::i32, SrcVT.getVectorNumElements());
11604       return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11605                          DAG.getNode(ISD::SIGN_EXTEND, dl, IntegerVT, Src));
11606     }
11607     return SDValue();
11608   }
11609
11610   assert(SrcVT <= MVT::i64 && SrcVT >= MVT::i16 &&
11611          "Unknown SINT_TO_FP to lower!");
11612
11613   // These are really Legal; return the operand so the caller accepts it as
11614   // Legal.
11615   if (SrcVT == MVT::i32 && isScalarFPTypeInSSEReg(Op.getValueType()))
11616     return Op;
11617   if (SrcVT == MVT::i64 && isScalarFPTypeInSSEReg(Op.getValueType()) &&
11618       Subtarget->is64Bit()) {
11619     return Op;
11620   }
11621
11622   unsigned Size = SrcVT.getSizeInBits()/8;
11623   MachineFunction &MF = DAG.getMachineFunction();
11624   int SSFI = MF.getFrameInfo()->CreateStackObject(Size, Size, false);
11625   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11626   SDValue Chain = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11627                                StackSlot,
11628                                MachinePointerInfo::getFixedStack(SSFI),
11629                                false, false, 0);
11630   return BuildFILD(Op, SrcVT, Chain, StackSlot, DAG);
11631 }
11632
11633 SDValue X86TargetLowering::BuildFILD(SDValue Op, EVT SrcVT, SDValue Chain,
11634                                      SDValue StackSlot,
11635                                      SelectionDAG &DAG) const {
11636   // Build the FILD
11637   SDLoc DL(Op);
11638   SDVTList Tys;
11639   bool useSSE = isScalarFPTypeInSSEReg(Op.getValueType());
11640   if (useSSE)
11641     Tys = DAG.getVTList(MVT::f64, MVT::Other, MVT::Glue);
11642   else
11643     Tys = DAG.getVTList(Op.getValueType(), MVT::Other);
11644
11645   unsigned ByteSize = SrcVT.getSizeInBits()/8;
11646
11647   FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(StackSlot);
11648   MachineMemOperand *MMO;
11649   if (FI) {
11650     int SSFI = FI->getIndex();
11651     MMO =
11652       DAG.getMachineFunction()
11653       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11654                             MachineMemOperand::MOLoad, ByteSize, ByteSize);
11655   } else {
11656     MMO = cast<LoadSDNode>(StackSlot)->getMemOperand();
11657     StackSlot = StackSlot.getOperand(1);
11658   }
11659   SDValue Ops[] = { Chain, StackSlot, DAG.getValueType(SrcVT) };
11660   SDValue Result = DAG.getMemIntrinsicNode(useSSE ? X86ISD::FILD_FLAG :
11661                                            X86ISD::FILD, DL,
11662                                            Tys, Ops, SrcVT, MMO);
11663
11664   if (useSSE) {
11665     Chain = Result.getValue(1);
11666     SDValue InFlag = Result.getValue(2);
11667
11668     // FIXME: Currently the FST is flagged to the FILD_FLAG. This
11669     // shouldn't be necessary except that RFP cannot be live across
11670     // multiple blocks. When stackifier is fixed, they can be uncoupled.
11671     MachineFunction &MF = DAG.getMachineFunction();
11672     unsigned SSFISize = Op.getValueType().getSizeInBits()/8;
11673     int SSFI = MF.getFrameInfo()->CreateStackObject(SSFISize, SSFISize, false);
11674     SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
11675     Tys = DAG.getVTList(MVT::Other);
11676     SDValue Ops[] = {
11677       Chain, Result, StackSlot, DAG.getValueType(Op.getValueType()), InFlag
11678     };
11679     MachineMemOperand *MMO =
11680       DAG.getMachineFunction()
11681       .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11682                             MachineMemOperand::MOStore, SSFISize, SSFISize);
11683
11684     Chain = DAG.getMemIntrinsicNode(X86ISD::FST, DL, Tys,
11685                                     Ops, Op.getValueType(), MMO);
11686     Result = DAG.getLoad(Op.getValueType(), DL, Chain, StackSlot,
11687                          MachinePointerInfo::getFixedStack(SSFI),
11688                          false, false, false, 0);
11689   }
11690
11691   return Result;
11692 }
11693
11694 // LowerUINT_TO_FP_i64 - 64-bit unsigned integer to double expansion.
11695 SDValue X86TargetLowering::LowerUINT_TO_FP_i64(SDValue Op,
11696                                                SelectionDAG &DAG) const {
11697   // This algorithm is not obvious. Here it is what we're trying to output:
11698   /*
11699      movq       %rax,  %xmm0
11700      punpckldq  (c0),  %xmm0  // c0: (uint4){ 0x43300000U, 0x45300000U, 0U, 0U }
11701      subpd      (c1),  %xmm0  // c1: (double2){ 0x1.0p52, 0x1.0p52 * 0x1.0p32 }
11702      #ifdef __SSE3__
11703        haddpd   %xmm0, %xmm0
11704      #else
11705        pshufd   $0x4e, %xmm0, %xmm1
11706        addpd    %xmm1, %xmm0
11707      #endif
11708   */
11709
11710   SDLoc dl(Op);
11711   LLVMContext *Context = DAG.getContext();
11712
11713   // Build some magic constants.
11714   static const uint32_t CV0[] = { 0x43300000, 0x45300000, 0, 0 };
11715   Constant *C0 = ConstantDataVector::get(*Context, CV0);
11716   SDValue CPIdx0 = DAG.getConstantPool(C0, getPointerTy(), 16);
11717
11718   SmallVector<Constant*,2> CV1;
11719   CV1.push_back(
11720     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11721                                       APInt(64, 0x4330000000000000ULL))));
11722   CV1.push_back(
11723     ConstantFP::get(*Context, APFloat(APFloat::IEEEdouble,
11724                                       APInt(64, 0x4530000000000000ULL))));
11725   Constant *C1 = ConstantVector::get(CV1);
11726   SDValue CPIdx1 = DAG.getConstantPool(C1, getPointerTy(), 16);
11727
11728   // Load the 64-bit value into an XMM register.
11729   SDValue XR1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2i64,
11730                             Op.getOperand(0));
11731   SDValue CLod0 = DAG.getLoad(MVT::v4i32, dl, DAG.getEntryNode(), CPIdx0,
11732                               MachinePointerInfo::getConstantPool(),
11733                               false, false, false, 16);
11734   SDValue Unpck1 =
11735       getUnpackl(DAG, dl, MVT::v4i32, DAG.getBitcast(MVT::v4i32, XR1), CLod0);
11736
11737   SDValue CLod1 = DAG.getLoad(MVT::v2f64, dl, CLod0.getValue(1), CPIdx1,
11738                               MachinePointerInfo::getConstantPool(),
11739                               false, false, false, 16);
11740   SDValue XR2F = DAG.getBitcast(MVT::v2f64, Unpck1);
11741   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, XR2F, CLod1);
11742   SDValue Result;
11743
11744   if (Subtarget->hasSSE3()) {
11745     // FIXME: The 'haddpd' instruction may be slower than 'movhlps + addsd'.
11746     Result = DAG.getNode(X86ISD::FHADD, dl, MVT::v2f64, Sub, Sub);
11747   } else {
11748     SDValue S2F = DAG.getBitcast(MVT::v4i32, Sub);
11749     SDValue Shuffle = getTargetShuffleNode(X86ISD::PSHUFD, dl, MVT::v4i32,
11750                                            S2F, 0x4E, DAG);
11751     Result = DAG.getNode(ISD::FADD, dl, MVT::v2f64,
11752                          DAG.getBitcast(MVT::v2f64, Shuffle), Sub);
11753   }
11754
11755   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, Result,
11756                      DAG.getIntPtrConstant(0, dl));
11757 }
11758
11759 // LowerUINT_TO_FP_i32 - 32-bit unsigned integer to float expansion.
11760 SDValue X86TargetLowering::LowerUINT_TO_FP_i32(SDValue Op,
11761                                                SelectionDAG &DAG) const {
11762   SDLoc dl(Op);
11763   // FP constant to bias correct the final result.
11764   SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
11765                                    MVT::f64);
11766
11767   // Load the 32-bit value into an XMM register.
11768   SDValue Load = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v4i32,
11769                              Op.getOperand(0));
11770
11771   // Zero out the upper parts of the register.
11772   Load = getShuffleVectorZeroOrUndef(Load, 0, true, Subtarget, DAG);
11773
11774   Load = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11775                      DAG.getBitcast(MVT::v2f64, Load),
11776                      DAG.getIntPtrConstant(0, dl));
11777
11778   // Or the load with the bias.
11779   SDValue Or = DAG.getNode(
11780       ISD::OR, dl, MVT::v2i64,
11781       DAG.getBitcast(MVT::v2i64,
11782                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Load)),
11783       DAG.getBitcast(MVT::v2i64,
11784                      DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, MVT::v2f64, Bias)));
11785   Or =
11786       DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
11787                   DAG.getBitcast(MVT::v2f64, Or), DAG.getIntPtrConstant(0, dl));
11788
11789   // Subtract the bias.
11790   SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::f64, Or, Bias);
11791
11792   // Handle final rounding.
11793   EVT DestVT = Op.getValueType();
11794
11795   if (DestVT.bitsLT(MVT::f64))
11796     return DAG.getNode(ISD::FP_ROUND, dl, DestVT, Sub,
11797                        DAG.getIntPtrConstant(0, dl));
11798   if (DestVT.bitsGT(MVT::f64))
11799     return DAG.getNode(ISD::FP_EXTEND, dl, DestVT, Sub);
11800
11801   // Handle final rounding.
11802   return Sub;
11803 }
11804
11805 static SDValue lowerUINT_TO_FP_vXi32(SDValue Op, SelectionDAG &DAG,
11806                                      const X86Subtarget &Subtarget) {
11807   // The algorithm is the following:
11808   // #ifdef __SSE4_1__
11809   //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11810   //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11811   //                                 (uint4) 0x53000000, 0xaa);
11812   // #else
11813   //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11814   //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11815   // #endif
11816   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11817   //     return (float4) lo + fhi;
11818
11819   SDLoc DL(Op);
11820   SDValue V = Op->getOperand(0);
11821   EVT VecIntVT = V.getValueType();
11822   bool Is128 = VecIntVT == MVT::v4i32;
11823   EVT VecFloatVT = Is128 ? MVT::v4f32 : MVT::v8f32;
11824   // If we convert to something else than the supported type, e.g., to v4f64,
11825   // abort early.
11826   if (VecFloatVT != Op->getValueType(0))
11827     return SDValue();
11828
11829   unsigned NumElts = VecIntVT.getVectorNumElements();
11830   assert((VecIntVT == MVT::v4i32 || VecIntVT == MVT::v8i32) &&
11831          "Unsupported custom type");
11832   assert(NumElts <= 8 && "The size of the constant array must be fixed");
11833
11834   // In the #idef/#else code, we have in common:
11835   // - The vector of constants:
11836   // -- 0x4b000000
11837   // -- 0x53000000
11838   // - A shift:
11839   // -- v >> 16
11840
11841   // Create the splat vector for 0x4b000000.
11842   SDValue CstLow = DAG.getConstant(0x4b000000, DL, MVT::i32);
11843   SDValue CstLowArray[] = {CstLow, CstLow, CstLow, CstLow,
11844                            CstLow, CstLow, CstLow, CstLow};
11845   SDValue VecCstLow = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11846                                   makeArrayRef(&CstLowArray[0], NumElts));
11847   // Create the splat vector for 0x53000000.
11848   SDValue CstHigh = DAG.getConstant(0x53000000, DL, MVT::i32);
11849   SDValue CstHighArray[] = {CstHigh, CstHigh, CstHigh, CstHigh,
11850                             CstHigh, CstHigh, CstHigh, CstHigh};
11851   SDValue VecCstHigh = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11852                                    makeArrayRef(&CstHighArray[0], NumElts));
11853
11854   // Create the right shift.
11855   SDValue CstShift = DAG.getConstant(16, DL, MVT::i32);
11856   SDValue CstShiftArray[] = {CstShift, CstShift, CstShift, CstShift,
11857                              CstShift, CstShift, CstShift, CstShift};
11858   SDValue VecCstShift = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT,
11859                                     makeArrayRef(&CstShiftArray[0], NumElts));
11860   SDValue HighShift = DAG.getNode(ISD::SRL, DL, VecIntVT, V, VecCstShift);
11861
11862   SDValue Low, High;
11863   if (Subtarget.hasSSE41()) {
11864     EVT VecI16VT = Is128 ? MVT::v8i16 : MVT::v16i16;
11865     //     uint4 lo = _mm_blend_epi16( v, (uint4) 0x4b000000, 0xaa);
11866     SDValue VecCstLowBitcast = DAG.getBitcast(VecI16VT, VecCstLow);
11867     SDValue VecBitcast = DAG.getBitcast(VecI16VT, V);
11868     // Low will be bitcasted right away, so do not bother bitcasting back to its
11869     // original type.
11870     Low = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecBitcast,
11871                       VecCstLowBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11872     //     uint4 hi = _mm_blend_epi16( _mm_srli_epi32(v,16),
11873     //                                 (uint4) 0x53000000, 0xaa);
11874     SDValue VecCstHighBitcast = DAG.getBitcast(VecI16VT, VecCstHigh);
11875     SDValue VecShiftBitcast = DAG.getBitcast(VecI16VT, HighShift);
11876     // High will be bitcasted right away, so do not bother bitcasting back to
11877     // its original type.
11878     High = DAG.getNode(X86ISD::BLENDI, DL, VecI16VT, VecShiftBitcast,
11879                        VecCstHighBitcast, DAG.getConstant(0xaa, DL, MVT::i32));
11880   } else {
11881     SDValue CstMask = DAG.getConstant(0xffff, DL, MVT::i32);
11882     SDValue VecCstMask = DAG.getNode(ISD::BUILD_VECTOR, DL, VecIntVT, CstMask,
11883                                      CstMask, CstMask, CstMask);
11884     //     uint4 lo = (v & (uint4) 0xffff) | (uint4) 0x4b000000;
11885     SDValue LowAnd = DAG.getNode(ISD::AND, DL, VecIntVT, V, VecCstMask);
11886     Low = DAG.getNode(ISD::OR, DL, VecIntVT, LowAnd, VecCstLow);
11887
11888     //     uint4 hi = (v >> 16) | (uint4) 0x53000000;
11889     High = DAG.getNode(ISD::OR, DL, VecIntVT, HighShift, VecCstHigh);
11890   }
11891
11892   // Create the vector constant for -(0x1.0p39f + 0x1.0p23f).
11893   SDValue CstFAdd = DAG.getConstantFP(
11894       APFloat(APFloat::IEEEsingle, APInt(32, 0xD3000080)), DL, MVT::f32);
11895   SDValue CstFAddArray[] = {CstFAdd, CstFAdd, CstFAdd, CstFAdd,
11896                             CstFAdd, CstFAdd, CstFAdd, CstFAdd};
11897   SDValue VecCstFAdd = DAG.getNode(ISD::BUILD_VECTOR, DL, VecFloatVT,
11898                                    makeArrayRef(&CstFAddArray[0], NumElts));
11899
11900   //     float4 fhi = (float4) hi - (0x1.0p39f + 0x1.0p23f);
11901   SDValue HighBitcast = DAG.getBitcast(VecFloatVT, High);
11902   SDValue FHigh =
11903       DAG.getNode(ISD::FADD, DL, VecFloatVT, HighBitcast, VecCstFAdd);
11904   //     return (float4) lo + fhi;
11905   SDValue LowBitcast = DAG.getBitcast(VecFloatVT, Low);
11906   return DAG.getNode(ISD::FADD, DL, VecFloatVT, LowBitcast, FHigh);
11907 }
11908
11909 SDValue X86TargetLowering::lowerUINT_TO_FP_vec(SDValue Op,
11910                                                SelectionDAG &DAG) const {
11911   SDValue N0 = Op.getOperand(0);
11912   MVT SVT = N0.getSimpleValueType();
11913   SDLoc dl(Op);
11914
11915   switch (SVT.SimpleTy) {
11916   default:
11917     llvm_unreachable("Custom UINT_TO_FP is not supported!");
11918   case MVT::v4i8:
11919   case MVT::v4i16:
11920   case MVT::v8i8:
11921   case MVT::v8i16: {
11922     MVT NVT = MVT::getVectorVT(MVT::i32, SVT.getVectorNumElements());
11923     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(),
11924                        DAG.getNode(ISD::ZERO_EXTEND, dl, NVT, N0));
11925   }
11926   case MVT::v4i32:
11927   case MVT::v8i32:
11928     return lowerUINT_TO_FP_vXi32(Op, DAG, *Subtarget);
11929   case MVT::v16i8:
11930   case MVT::v16i16:
11931     if (Subtarget->hasAVX512())
11932       return DAG.getNode(ISD::UINT_TO_FP, dl, Op.getValueType(),
11933                          DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v16i32, N0));
11934   }
11935   llvm_unreachable(nullptr);
11936 }
11937
11938 SDValue X86TargetLowering::LowerUINT_TO_FP(SDValue Op,
11939                                            SelectionDAG &DAG) const {
11940   SDValue N0 = Op.getOperand(0);
11941   SDLoc dl(Op);
11942
11943   if (Op.getValueType().isVector())
11944     return lowerUINT_TO_FP_vec(Op, DAG);
11945
11946   // Since UINT_TO_FP is legal (it's marked custom), dag combiner won't
11947   // optimize it to a SINT_TO_FP when the sign bit is known zero. Perform
11948   // the optimization here.
11949   if (DAG.SignBitIsZero(N0))
11950     return DAG.getNode(ISD::SINT_TO_FP, dl, Op.getValueType(), N0);
11951
11952   MVT SrcVT = N0.getSimpleValueType();
11953   MVT DstVT = Op.getSimpleValueType();
11954   if (SrcVT == MVT::i64 && DstVT == MVT::f64 && X86ScalarSSEf64)
11955     return LowerUINT_TO_FP_i64(Op, DAG);
11956   if (SrcVT == MVT::i32 && X86ScalarSSEf64)
11957     return LowerUINT_TO_FP_i32(Op, DAG);
11958   if (Subtarget->is64Bit() && SrcVT == MVT::i64 && DstVT == MVT::f32)
11959     return SDValue();
11960
11961   // Make a 64-bit buffer, and use it to build an FILD.
11962   SDValue StackSlot = DAG.CreateStackTemporary(MVT::i64);
11963   if (SrcVT == MVT::i32) {
11964     SDValue WordOff = DAG.getConstant(4, dl, getPointerTy());
11965     SDValue OffsetSlot = DAG.getNode(ISD::ADD, dl,
11966                                      getPointerTy(), StackSlot, WordOff);
11967     SDValue Store1 = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11968                                   StackSlot, MachinePointerInfo(),
11969                                   false, false, 0);
11970     SDValue Store2 = DAG.getStore(Store1, dl, DAG.getConstant(0, dl, MVT::i32),
11971                                   OffsetSlot, MachinePointerInfo(),
11972                                   false, false, 0);
11973     SDValue Fild = BuildFILD(Op, MVT::i64, Store2, StackSlot, DAG);
11974     return Fild;
11975   }
11976
11977   assert(SrcVT == MVT::i64 && "Unexpected type in UINT_TO_FP");
11978   SDValue Store = DAG.getStore(DAG.getEntryNode(), dl, Op.getOperand(0),
11979                                StackSlot, MachinePointerInfo(),
11980                                false, false, 0);
11981   // For i64 source, we need to add the appropriate power of 2 if the input
11982   // was negative.  This is the same as the optimization in
11983   // DAGTypeLegalizer::ExpandIntOp_UNIT_TO_FP, and for it to be safe here,
11984   // we must be careful to do the computation in x87 extended precision, not
11985   // in SSE. (The generic code can't know it's OK to do this, or how to.)
11986   int SSFI = cast<FrameIndexSDNode>(StackSlot)->getIndex();
11987   MachineMemOperand *MMO =
11988     DAG.getMachineFunction()
11989     .getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
11990                           MachineMemOperand::MOLoad, 8, 8);
11991
11992   SDVTList Tys = DAG.getVTList(MVT::f80, MVT::Other);
11993   SDValue Ops[] = { Store, StackSlot, DAG.getValueType(MVT::i64) };
11994   SDValue Fild = DAG.getMemIntrinsicNode(X86ISD::FILD, dl, Tys, Ops,
11995                                          MVT::i64, MMO);
11996
11997   APInt FF(32, 0x5F800000ULL);
11998
11999   // Check whether the sign bit is set.
12000   SDValue SignSet = DAG.getSetCC(dl,
12001                                  getSetCCResultType(*DAG.getContext(), MVT::i64),
12002                                  Op.getOperand(0),
12003                                  DAG.getConstant(0, dl, MVT::i64), ISD::SETLT);
12004
12005   // Build a 64 bit pair (0, FF) in the constant pool, with FF in the lo bits.
12006   SDValue FudgePtr = DAG.getConstantPool(
12007                              ConstantInt::get(*DAG.getContext(), FF.zext(64)),
12008                                          getPointerTy());
12009
12010   // Get a pointer to FF if the sign bit was set, or to 0 otherwise.
12011   SDValue Zero = DAG.getIntPtrConstant(0, dl);
12012   SDValue Four = DAG.getIntPtrConstant(4, dl);
12013   SDValue Offset = DAG.getNode(ISD::SELECT, dl, Zero.getValueType(), SignSet,
12014                                Zero, Four);
12015   FudgePtr = DAG.getNode(ISD::ADD, dl, getPointerTy(), FudgePtr, Offset);
12016
12017   // Load the value out, extending it from f32 to f80.
12018   // FIXME: Avoid the extend by constructing the right constant pool?
12019   SDValue Fudge = DAG.getExtLoad(ISD::EXTLOAD, dl, MVT::f80, DAG.getEntryNode(),
12020                                  FudgePtr, MachinePointerInfo::getConstantPool(),
12021                                  MVT::f32, false, false, false, 4);
12022   // Extend everything to 80 bits to force it to be done on x87.
12023   SDValue Add = DAG.getNode(ISD::FADD, dl, MVT::f80, Fild, Fudge);
12024   return DAG.getNode(ISD::FP_ROUND, dl, DstVT, Add,
12025                      DAG.getIntPtrConstant(0, dl));
12026 }
12027
12028 std::pair<SDValue,SDValue>
12029 X86TargetLowering:: FP_TO_INTHelper(SDValue Op, SelectionDAG &DAG,
12030                                     bool IsSigned, bool IsReplace) const {
12031   SDLoc DL(Op);
12032
12033   EVT DstTy = Op.getValueType();
12034
12035   if (!IsSigned && !isIntegerTypeFTOL(DstTy)) {
12036     assert(DstTy == MVT::i32 && "Unexpected FP_TO_UINT");
12037     DstTy = MVT::i64;
12038   }
12039
12040   assert(DstTy.getSimpleVT() <= MVT::i64 &&
12041          DstTy.getSimpleVT() >= MVT::i16 &&
12042          "Unknown FP_TO_INT to lower!");
12043
12044   // These are really Legal.
12045   if (DstTy == MVT::i32 &&
12046       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12047     return std::make_pair(SDValue(), SDValue());
12048   if (Subtarget->is64Bit() &&
12049       DstTy == MVT::i64 &&
12050       isScalarFPTypeInSSEReg(Op.getOperand(0).getValueType()))
12051     return std::make_pair(SDValue(), SDValue());
12052
12053   // We lower FP->int64 either into FISTP64 followed by a load from a temporary
12054   // stack slot, or into the FTOL runtime function.
12055   MachineFunction &MF = DAG.getMachineFunction();
12056   unsigned MemSize = DstTy.getSizeInBits()/8;
12057   int SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12058   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12059
12060   unsigned Opc;
12061   if (!IsSigned && isIntegerTypeFTOL(DstTy))
12062     Opc = X86ISD::WIN_FTOL;
12063   else
12064     switch (DstTy.getSimpleVT().SimpleTy) {
12065     default: llvm_unreachable("Invalid FP_TO_SINT to lower!");
12066     case MVT::i16: Opc = X86ISD::FP_TO_INT16_IN_MEM; break;
12067     case MVT::i32: Opc = X86ISD::FP_TO_INT32_IN_MEM; break;
12068     case MVT::i64: Opc = X86ISD::FP_TO_INT64_IN_MEM; break;
12069     }
12070
12071   SDValue Chain = DAG.getEntryNode();
12072   SDValue Value = Op.getOperand(0);
12073   EVT TheVT = Op.getOperand(0).getValueType();
12074   // FIXME This causes a redundant load/store if the SSE-class value is already
12075   // in memory, such as if it is on the callstack.
12076   if (isScalarFPTypeInSSEReg(TheVT)) {
12077     assert(DstTy == MVT::i64 && "Invalid FP_TO_SINT to lower!");
12078     Chain = DAG.getStore(Chain, DL, Value, StackSlot,
12079                          MachinePointerInfo::getFixedStack(SSFI),
12080                          false, false, 0);
12081     SDVTList Tys = DAG.getVTList(Op.getOperand(0).getValueType(), MVT::Other);
12082     SDValue Ops[] = {
12083       Chain, StackSlot, DAG.getValueType(TheVT)
12084     };
12085
12086     MachineMemOperand *MMO =
12087       MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12088                               MachineMemOperand::MOLoad, MemSize, MemSize);
12089     Value = DAG.getMemIntrinsicNode(X86ISD::FLD, DL, Tys, Ops, DstTy, MMO);
12090     Chain = Value.getValue(1);
12091     SSFI = MF.getFrameInfo()->CreateStackObject(MemSize, MemSize, false);
12092     StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
12093   }
12094
12095   MachineMemOperand *MMO =
12096     MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
12097                             MachineMemOperand::MOStore, MemSize, MemSize);
12098
12099   if (Opc != X86ISD::WIN_FTOL) {
12100     // Build the FP_TO_INT*_IN_MEM
12101     SDValue Ops[] = { Chain, Value, StackSlot };
12102     SDValue FIST = DAG.getMemIntrinsicNode(Opc, DL, DAG.getVTList(MVT::Other),
12103                                            Ops, DstTy, MMO);
12104     return std::make_pair(FIST, StackSlot);
12105   } else {
12106     SDValue ftol = DAG.getNode(X86ISD::WIN_FTOL, DL,
12107       DAG.getVTList(MVT::Other, MVT::Glue),
12108       Chain, Value);
12109     SDValue eax = DAG.getCopyFromReg(ftol, DL, X86::EAX,
12110       MVT::i32, ftol.getValue(1));
12111     SDValue edx = DAG.getCopyFromReg(eax.getValue(1), DL, X86::EDX,
12112       MVT::i32, eax.getValue(2));
12113     SDValue Ops[] = { eax, edx };
12114     SDValue pair = IsReplace
12115       ? DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops)
12116       : DAG.getMergeValues(Ops, DL);
12117     return std::make_pair(pair, SDValue());
12118   }
12119 }
12120
12121 static SDValue LowerAVXExtend(SDValue Op, SelectionDAG &DAG,
12122                               const X86Subtarget *Subtarget) {
12123   MVT VT = Op->getSimpleValueType(0);
12124   SDValue In = Op->getOperand(0);
12125   MVT InVT = In.getSimpleValueType();
12126   SDLoc dl(Op);
12127
12128   if (VT.is512BitVector() || InVT.getScalarType() == MVT::i1)
12129     return DAG.getNode(ISD::ZERO_EXTEND, dl, VT, In);
12130
12131   // Optimize vectors in AVX mode:
12132   //
12133   //   v8i16 -> v8i32
12134   //   Use vpunpcklwd for 4 lower elements  v8i16 -> v4i32.
12135   //   Use vpunpckhwd for 4 upper elements  v8i16 -> v4i32.
12136   //   Concat upper and lower parts.
12137   //
12138   //   v4i32 -> v4i64
12139   //   Use vpunpckldq for 4 lower elements  v4i32 -> v2i64.
12140   //   Use vpunpckhdq for 4 upper elements  v4i32 -> v2i64.
12141   //   Concat upper and lower parts.
12142   //
12143
12144   if (((VT != MVT::v16i16) || (InVT != MVT::v16i8)) &&
12145       ((VT != MVT::v8i32) || (InVT != MVT::v8i16)) &&
12146       ((VT != MVT::v4i64) || (InVT != MVT::v4i32)))
12147     return SDValue();
12148
12149   if (Subtarget->hasInt256())
12150     return DAG.getNode(X86ISD::VZEXT, dl, VT, In);
12151
12152   SDValue ZeroVec = getZeroVector(InVT, Subtarget, DAG, dl);
12153   SDValue Undef = DAG.getUNDEF(InVT);
12154   bool NeedZero = Op.getOpcode() == ISD::ZERO_EXTEND;
12155   SDValue OpLo = getUnpackl(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12156   SDValue OpHi = getUnpackh(DAG, dl, InVT, In, NeedZero ? ZeroVec : Undef);
12157
12158   MVT HVT = MVT::getVectorVT(VT.getVectorElementType(),
12159                              VT.getVectorNumElements()/2);
12160
12161   OpLo = DAG.getBitcast(HVT, OpLo);
12162   OpHi = DAG.getBitcast(HVT, OpHi);
12163
12164   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
12165 }
12166
12167 static  SDValue LowerZERO_EXTEND_AVX512(SDValue Op,
12168                   const X86Subtarget *Subtarget, SelectionDAG &DAG) {
12169   MVT VT = Op->getSimpleValueType(0);
12170   SDValue In = Op->getOperand(0);
12171   MVT InVT = In.getSimpleValueType();
12172   SDLoc DL(Op);
12173   unsigned int NumElts = VT.getVectorNumElements();
12174   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
12175     return SDValue();
12176
12177   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1)
12178     return DAG.getNode(X86ISD::VZEXT, DL, VT, In);
12179
12180   assert(InVT.getVectorElementType() == MVT::i1);
12181   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
12182   SDValue One =
12183    DAG.getConstant(APInt(ExtVT.getScalarSizeInBits(), 1), DL, ExtVT);
12184   SDValue Zero =
12185    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), DL, ExtVT);
12186
12187   SDValue V = DAG.getNode(ISD::VSELECT, DL, ExtVT, In, One, Zero);
12188   if (VT.is512BitVector())
12189     return V;
12190   return DAG.getNode(X86ISD::VTRUNC, DL, VT, V);
12191 }
12192
12193 static SDValue LowerANY_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12194                                SelectionDAG &DAG) {
12195   if (Subtarget->hasFp256())
12196     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12197       return Res;
12198
12199   return SDValue();
12200 }
12201
12202 static SDValue LowerZERO_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
12203                                 SelectionDAG &DAG) {
12204   SDLoc DL(Op);
12205   MVT VT = Op.getSimpleValueType();
12206   SDValue In = Op.getOperand(0);
12207   MVT SVT = In.getSimpleValueType();
12208
12209   if (VT.is512BitVector() || SVT.getVectorElementType() == MVT::i1)
12210     return LowerZERO_EXTEND_AVX512(Op, Subtarget, DAG);
12211
12212   if (Subtarget->hasFp256())
12213     if (SDValue Res = LowerAVXExtend(Op, DAG, Subtarget))
12214       return Res;
12215
12216   assert(!VT.is256BitVector() || !SVT.is128BitVector() ||
12217          VT.getVectorNumElements() != SVT.getVectorNumElements());
12218   return SDValue();
12219 }
12220
12221 SDValue X86TargetLowering::LowerTRUNCATE(SDValue Op, SelectionDAG &DAG) const {
12222   SDLoc DL(Op);
12223   MVT VT = Op.getSimpleValueType();
12224   SDValue In = Op.getOperand(0);
12225   MVT InVT = In.getSimpleValueType();
12226
12227   if (VT == MVT::i1) {
12228     assert((InVT.isInteger() && (InVT.getSizeInBits() <= 64)) &&
12229            "Invalid scalar TRUNCATE operation");
12230     if (InVT.getSizeInBits() >= 32)
12231       return SDValue();
12232     In = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, In);
12233     return DAG.getNode(ISD::TRUNCATE, DL, VT, In);
12234   }
12235   assert(VT.getVectorNumElements() == InVT.getVectorNumElements() &&
12236          "Invalid TRUNCATE operation");
12237
12238   // move vector to mask - truncate solution for SKX
12239   if (VT.getVectorElementType() == MVT::i1) {
12240     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() <= 16 &&
12241         Subtarget->hasBWI())
12242       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12243     if ((InVT.is256BitVector() || InVT.is128BitVector())
12244         && InVT.getScalarSizeInBits() <= 16 &&
12245         Subtarget->hasBWI() && Subtarget->hasVLX())
12246       return Op; // legal, will go to VPMOVB2M, VPMOVW2M
12247     if (InVT.is512BitVector() && InVT.getScalarSizeInBits() >= 32 &&
12248         Subtarget->hasDQI())
12249       return Op; // legal, will go to VPMOVD2M, VPMOVQ2M
12250     if ((InVT.is256BitVector() || InVT.is128BitVector())
12251         && InVT.getScalarSizeInBits() >= 32 &&
12252         Subtarget->hasDQI() && Subtarget->hasVLX())
12253       return Op; // legal, will go to VPMOVB2M, VPMOVQ2M
12254   }
12255   if (InVT.is512BitVector() || VT.getVectorElementType() == MVT::i1) {
12256     if (VT.getVectorElementType().getSizeInBits() >=8)
12257       return DAG.getNode(X86ISD::VTRUNC, DL, VT, In);
12258
12259     assert(VT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
12260     unsigned NumElts = InVT.getVectorNumElements();
12261     assert ((NumElts == 8 || NumElts == 16) && "Unexpected vector type");
12262     if (InVT.getSizeInBits() < 512) {
12263       MVT ExtVT = (NumElts == 16)? MVT::v16i32 : MVT::v8i64;
12264       In = DAG.getNode(ISD::SIGN_EXTEND, DL, ExtVT, In);
12265       InVT = ExtVT;
12266     }
12267
12268     SDValue OneV =
12269      DAG.getConstant(APInt::getSignBit(InVT.getScalarSizeInBits()), DL, InVT);
12270     SDValue And = DAG.getNode(ISD::AND, DL, InVT, OneV, In);
12271     return DAG.getNode(X86ISD::TESTM, DL, VT, And, And);
12272   }
12273
12274   if ((VT == MVT::v4i32) && (InVT == MVT::v4i64)) {
12275     // On AVX2, v4i64 -> v4i32 becomes VPERMD.
12276     if (Subtarget->hasInt256()) {
12277       static const int ShufMask[] = {0, 2, 4, 6, -1, -1, -1, -1};
12278       In = DAG.getBitcast(MVT::v8i32, In);
12279       In = DAG.getVectorShuffle(MVT::v8i32, DL, In, DAG.getUNDEF(MVT::v8i32),
12280                                 ShufMask);
12281       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, In,
12282                          DAG.getIntPtrConstant(0, DL));
12283     }
12284
12285     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12286                                DAG.getIntPtrConstant(0, DL));
12287     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12288                                DAG.getIntPtrConstant(2, DL));
12289     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12290     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12291     static const int ShufMask[] = {0, 2, 4, 6};
12292     return DAG.getVectorShuffle(VT, DL, OpLo, OpHi, ShufMask);
12293   }
12294
12295   if ((VT == MVT::v8i16) && (InVT == MVT::v8i32)) {
12296     // On AVX2, v8i32 -> v8i16 becomed PSHUFB.
12297     if (Subtarget->hasInt256()) {
12298       In = DAG.getBitcast(MVT::v32i8, In);
12299
12300       SmallVector<SDValue,32> pshufbMask;
12301       for (unsigned i = 0; i < 2; ++i) {
12302         pshufbMask.push_back(DAG.getConstant(0x0, DL, MVT::i8));
12303         pshufbMask.push_back(DAG.getConstant(0x1, DL, MVT::i8));
12304         pshufbMask.push_back(DAG.getConstant(0x4, DL, MVT::i8));
12305         pshufbMask.push_back(DAG.getConstant(0x5, DL, MVT::i8));
12306         pshufbMask.push_back(DAG.getConstant(0x8, DL, MVT::i8));
12307         pshufbMask.push_back(DAG.getConstant(0x9, DL, MVT::i8));
12308         pshufbMask.push_back(DAG.getConstant(0xc, DL, MVT::i8));
12309         pshufbMask.push_back(DAG.getConstant(0xd, DL, MVT::i8));
12310         for (unsigned j = 0; j < 8; ++j)
12311           pshufbMask.push_back(DAG.getConstant(0x80, DL, MVT::i8));
12312       }
12313       SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, DL, MVT::v32i8, pshufbMask);
12314       In = DAG.getNode(X86ISD::PSHUFB, DL, MVT::v32i8, In, BV);
12315       In = DAG.getBitcast(MVT::v4i64, In);
12316
12317       static const int ShufMask[] = {0,  2,  -1,  -1};
12318       In = DAG.getVectorShuffle(MVT::v4i64, DL,  In, DAG.getUNDEF(MVT::v4i64),
12319                                 &ShufMask[0]);
12320       In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v2i64, In,
12321                        DAG.getIntPtrConstant(0, DL));
12322       return DAG.getBitcast(VT, In);
12323     }
12324
12325     SDValue OpLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12326                                DAG.getIntPtrConstant(0, DL));
12327
12328     SDValue OpHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i32, In,
12329                                DAG.getIntPtrConstant(4, DL));
12330
12331     OpLo = DAG.getBitcast(MVT::v16i8, OpLo);
12332     OpHi = DAG.getBitcast(MVT::v16i8, OpHi);
12333
12334     // The PSHUFB mask:
12335     static const int ShufMask1[] = {0,  1,  4,  5,  8,  9, 12, 13,
12336                                    -1, -1, -1, -1, -1, -1, -1, -1};
12337
12338     SDValue Undef = DAG.getUNDEF(MVT::v16i8);
12339     OpLo = DAG.getVectorShuffle(MVT::v16i8, DL, OpLo, Undef, ShufMask1);
12340     OpHi = DAG.getVectorShuffle(MVT::v16i8, DL, OpHi, Undef, ShufMask1);
12341
12342     OpLo = DAG.getBitcast(MVT::v4i32, OpLo);
12343     OpHi = DAG.getBitcast(MVT::v4i32, OpHi);
12344
12345     // The MOVLHPS Mask:
12346     static const int ShufMask2[] = {0, 1, 4, 5};
12347     SDValue res = DAG.getVectorShuffle(MVT::v4i32, DL, OpLo, OpHi, ShufMask2);
12348     return DAG.getBitcast(MVT::v8i16, res);
12349   }
12350
12351   // Handle truncation of V256 to V128 using shuffles.
12352   if (!VT.is128BitVector() || !InVT.is256BitVector())
12353     return SDValue();
12354
12355   assert(Subtarget->hasFp256() && "256-bit vector without AVX!");
12356
12357   unsigned NumElems = VT.getVectorNumElements();
12358   MVT NVT = MVT::getVectorVT(VT.getVectorElementType(), NumElems * 2);
12359
12360   SmallVector<int, 16> MaskVec(NumElems * 2, -1);
12361   // Prepare truncation shuffle mask
12362   for (unsigned i = 0; i != NumElems; ++i)
12363     MaskVec[i] = i * 2;
12364   SDValue V = DAG.getVectorShuffle(NVT, DL, DAG.getBitcast(NVT, In),
12365                                    DAG.getUNDEF(NVT), &MaskVec[0]);
12366   return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V,
12367                      DAG.getIntPtrConstant(0, DL));
12368 }
12369
12370 SDValue X86TargetLowering::LowerFP_TO_SINT(SDValue Op,
12371                                            SelectionDAG &DAG) const {
12372   assert(!Op.getSimpleValueType().isVector());
12373
12374   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12375     /*IsSigned=*/ true, /*IsReplace=*/ false);
12376   SDValue FIST = Vals.first, StackSlot = Vals.second;
12377   // If FP_TO_INTHelper failed, the node is actually supposed to be Legal.
12378   if (!FIST.getNode()) return Op;
12379
12380   if (StackSlot.getNode())
12381     // Load the result.
12382     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12383                        FIST, StackSlot, MachinePointerInfo(),
12384                        false, false, false, 0);
12385
12386   // The node is the result.
12387   return FIST;
12388 }
12389
12390 SDValue X86TargetLowering::LowerFP_TO_UINT(SDValue Op,
12391                                            SelectionDAG &DAG) const {
12392   std::pair<SDValue,SDValue> Vals = FP_TO_INTHelper(Op, DAG,
12393     /*IsSigned=*/ false, /*IsReplace=*/ false);
12394   SDValue FIST = Vals.first, StackSlot = Vals.second;
12395   assert(FIST.getNode() && "Unexpected failure");
12396
12397   if (StackSlot.getNode())
12398     // Load the result.
12399     return DAG.getLoad(Op.getValueType(), SDLoc(Op),
12400                        FIST, StackSlot, MachinePointerInfo(),
12401                        false, false, false, 0);
12402
12403   // The node is the result.
12404   return FIST;
12405 }
12406
12407 static SDValue LowerFP_EXTEND(SDValue Op, SelectionDAG &DAG) {
12408   SDLoc DL(Op);
12409   MVT VT = Op.getSimpleValueType();
12410   SDValue In = Op.getOperand(0);
12411   MVT SVT = In.getSimpleValueType();
12412
12413   assert(SVT == MVT::v2f32 && "Only customize MVT::v2f32 type legalization!");
12414
12415   return DAG.getNode(X86ISD::VFPEXT, DL, VT,
12416                      DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v4f32,
12417                                  In, DAG.getUNDEF(SVT)));
12418 }
12419
12420 /// The only differences between FABS and FNEG are the mask and the logic op.
12421 /// FNEG also has a folding opportunity for FNEG(FABS(x)).
12422 static SDValue LowerFABSorFNEG(SDValue Op, SelectionDAG &DAG) {
12423   assert((Op.getOpcode() == ISD::FABS || Op.getOpcode() == ISD::FNEG) &&
12424          "Wrong opcode for lowering FABS or FNEG.");
12425
12426   bool IsFABS = (Op.getOpcode() == ISD::FABS);
12427
12428   // If this is a FABS and it has an FNEG user, bail out to fold the combination
12429   // into an FNABS. We'll lower the FABS after that if it is still in use.
12430   if (IsFABS)
12431     for (SDNode *User : Op->uses())
12432       if (User->getOpcode() == ISD::FNEG)
12433         return Op;
12434
12435   SDValue Op0 = Op.getOperand(0);
12436   bool IsFNABS = !IsFABS && (Op0.getOpcode() == ISD::FABS);
12437
12438   SDLoc dl(Op);
12439   MVT VT = Op.getSimpleValueType();
12440   // Assume scalar op for initialization; update for vector if needed.
12441   // Note that there are no scalar bitwise logical SSE/AVX instructions, so we
12442   // generate a 16-byte vector constant and logic op even for the scalar case.
12443   // Using a 16-byte mask allows folding the load of the mask with
12444   // the logic op, so it can save (~4 bytes) on code size.
12445   MVT EltVT = VT;
12446   unsigned NumElts = VT == MVT::f64 ? 2 : 4;
12447   // FIXME: Use function attribute "OptimizeForSize" and/or CodeGenOpt::Level to
12448   // decide if we should generate a 16-byte constant mask when we only need 4 or
12449   // 8 bytes for the scalar case.
12450   if (VT.isVector()) {
12451     EltVT = VT.getVectorElementType();
12452     NumElts = VT.getVectorNumElements();
12453   }
12454
12455   unsigned EltBits = EltVT.getSizeInBits();
12456   LLVMContext *Context = DAG.getContext();
12457   // For FABS, mask is 0x7f...; for FNEG, mask is 0x80...
12458   APInt MaskElt =
12459     IsFABS ? APInt::getSignedMaxValue(EltBits) : APInt::getSignBit(EltBits);
12460   Constant *C = ConstantInt::get(*Context, MaskElt);
12461   C = ConstantVector::getSplat(NumElts, C);
12462   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12463   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy());
12464   unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12465   SDValue Mask = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12466                              MachinePointerInfo::getConstantPool(),
12467                              false, false, false, Alignment);
12468
12469   if (VT.isVector()) {
12470     // For a vector, cast operands to a vector type, perform the logic op,
12471     // and cast the result back to the original value type.
12472     MVT VecVT = MVT::getVectorVT(MVT::i64, VT.getSizeInBits() / 64);
12473     SDValue MaskCasted = DAG.getBitcast(VecVT, Mask);
12474     SDValue Operand = IsFNABS ? DAG.getBitcast(VecVT, Op0.getOperand(0))
12475                               : DAG.getBitcast(VecVT, Op0);
12476     unsigned BitOp = IsFABS ? ISD::AND : IsFNABS ? ISD::OR : ISD::XOR;
12477     return DAG.getBitcast(VT,
12478                           DAG.getNode(BitOp, dl, VecVT, Operand, MaskCasted));
12479   }
12480
12481   // If not vector, then scalar.
12482   unsigned BitOp = IsFABS ? X86ISD::FAND : IsFNABS ? X86ISD::FOR : X86ISD::FXOR;
12483   SDValue Operand = IsFNABS ? Op0.getOperand(0) : Op0;
12484   return DAG.getNode(BitOp, dl, VT, Operand, Mask);
12485 }
12486
12487 static SDValue LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) {
12488   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12489   LLVMContext *Context = DAG.getContext();
12490   SDValue Op0 = Op.getOperand(0);
12491   SDValue Op1 = Op.getOperand(1);
12492   SDLoc dl(Op);
12493   MVT VT = Op.getSimpleValueType();
12494   MVT SrcVT = Op1.getSimpleValueType();
12495
12496   // If second operand is smaller, extend it first.
12497   if (SrcVT.bitsLT(VT)) {
12498     Op1 = DAG.getNode(ISD::FP_EXTEND, dl, VT, Op1);
12499     SrcVT = VT;
12500   }
12501   // And if it is bigger, shrink it first.
12502   if (SrcVT.bitsGT(VT)) {
12503     Op1 = DAG.getNode(ISD::FP_ROUND, dl, VT, Op1, DAG.getIntPtrConstant(1, dl));
12504     SrcVT = VT;
12505   }
12506
12507   // At this point the operands and the result should have the same
12508   // type, and that won't be f80 since that is not custom lowered.
12509
12510   const fltSemantics &Sem =
12511       VT == MVT::f64 ? APFloat::IEEEdouble : APFloat::IEEEsingle;
12512   const unsigned SizeInBits = VT.getSizeInBits();
12513
12514   SmallVector<Constant *, 4> CV(
12515       VT == MVT::f64 ? 2 : 4,
12516       ConstantFP::get(*Context, APFloat(Sem, APInt(SizeInBits, 0))));
12517
12518   // First, clear all bits but the sign bit from the second operand (sign).
12519   CV[0] = ConstantFP::get(*Context,
12520                           APFloat(Sem, APInt::getHighBitsSet(SizeInBits, 1)));
12521   Constant *C = ConstantVector::get(CV);
12522   SDValue CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12523   SDValue Mask1 = DAG.getLoad(SrcVT, dl, DAG.getEntryNode(), CPIdx,
12524                               MachinePointerInfo::getConstantPool(),
12525                               false, false, false, 16);
12526   SDValue SignBit = DAG.getNode(X86ISD::FAND, dl, SrcVT, Op1, Mask1);
12527
12528   // Next, clear the sign bit from the first operand (magnitude).
12529   // If it's a constant, we can clear it here.
12530   if (ConstantFPSDNode *Op0CN = dyn_cast<ConstantFPSDNode>(Op0)) {
12531     APFloat APF = Op0CN->getValueAPF();
12532     // If the magnitude is a positive zero, the sign bit alone is enough.
12533     if (APF.isPosZero())
12534       return SignBit;
12535     APF.clearSign();
12536     CV[0] = ConstantFP::get(*Context, APF);
12537   } else {
12538     CV[0] = ConstantFP::get(
12539         *Context,
12540         APFloat(Sem, APInt::getLowBitsSet(SizeInBits, SizeInBits - 1)));
12541   }
12542   C = ConstantVector::get(CV);
12543   CPIdx = DAG.getConstantPool(C, TLI.getPointerTy(), 16);
12544   SDValue Val = DAG.getLoad(VT, dl, DAG.getEntryNode(), CPIdx,
12545                             MachinePointerInfo::getConstantPool(),
12546                             false, false, false, 16);
12547   // If the magnitude operand wasn't a constant, we need to AND out the sign.
12548   if (!isa<ConstantFPSDNode>(Op0))
12549     Val = DAG.getNode(X86ISD::FAND, dl, VT, Op0, Val);
12550
12551   // OR the magnitude value with the sign bit.
12552   return DAG.getNode(X86ISD::FOR, dl, VT, Val, SignBit);
12553 }
12554
12555 static SDValue LowerFGETSIGN(SDValue Op, SelectionDAG &DAG) {
12556   SDValue N0 = Op.getOperand(0);
12557   SDLoc dl(Op);
12558   MVT VT = Op.getSimpleValueType();
12559
12560   // Lower ISD::FGETSIGN to (AND (X86ISD::FGETSIGNx86 ...) 1).
12561   SDValue xFGETSIGN = DAG.getNode(X86ISD::FGETSIGNx86, dl, VT, N0,
12562                                   DAG.getConstant(1, dl, VT));
12563   return DAG.getNode(ISD::AND, dl, VT, xFGETSIGN, DAG.getConstant(1, dl, VT));
12564 }
12565
12566 // Check whether an OR'd tree is PTEST-able.
12567 static SDValue LowerVectorAllZeroTest(SDValue Op, const X86Subtarget *Subtarget,
12568                                       SelectionDAG &DAG) {
12569   assert(Op.getOpcode() == ISD::OR && "Only check OR'd tree.");
12570
12571   if (!Subtarget->hasSSE41())
12572     return SDValue();
12573
12574   if (!Op->hasOneUse())
12575     return SDValue();
12576
12577   SDNode *N = Op.getNode();
12578   SDLoc DL(N);
12579
12580   SmallVector<SDValue, 8> Opnds;
12581   DenseMap<SDValue, unsigned> VecInMap;
12582   SmallVector<SDValue, 8> VecIns;
12583   EVT VT = MVT::Other;
12584
12585   // Recognize a special case where a vector is casted into wide integer to
12586   // test all 0s.
12587   Opnds.push_back(N->getOperand(0));
12588   Opnds.push_back(N->getOperand(1));
12589
12590   for (unsigned Slot = 0, e = Opnds.size(); Slot < e; ++Slot) {
12591     SmallVectorImpl<SDValue>::const_iterator I = Opnds.begin() + Slot;
12592     // BFS traverse all OR'd operands.
12593     if (I->getOpcode() == ISD::OR) {
12594       Opnds.push_back(I->getOperand(0));
12595       Opnds.push_back(I->getOperand(1));
12596       // Re-evaluate the number of nodes to be traversed.
12597       e += 2; // 2 more nodes (LHS and RHS) are pushed.
12598       continue;
12599     }
12600
12601     // Quit if a non-EXTRACT_VECTOR_ELT
12602     if (I->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
12603       return SDValue();
12604
12605     // Quit if without a constant index.
12606     SDValue Idx = I->getOperand(1);
12607     if (!isa<ConstantSDNode>(Idx))
12608       return SDValue();
12609
12610     SDValue ExtractedFromVec = I->getOperand(0);
12611     DenseMap<SDValue, unsigned>::iterator M = VecInMap.find(ExtractedFromVec);
12612     if (M == VecInMap.end()) {
12613       VT = ExtractedFromVec.getValueType();
12614       // Quit if not 128/256-bit vector.
12615       if (!VT.is128BitVector() && !VT.is256BitVector())
12616         return SDValue();
12617       // Quit if not the same type.
12618       if (VecInMap.begin() != VecInMap.end() &&
12619           VT != VecInMap.begin()->first.getValueType())
12620         return SDValue();
12621       M = VecInMap.insert(std::make_pair(ExtractedFromVec, 0)).first;
12622       VecIns.push_back(ExtractedFromVec);
12623     }
12624     M->second |= 1U << cast<ConstantSDNode>(Idx)->getZExtValue();
12625   }
12626
12627   assert((VT.is128BitVector() || VT.is256BitVector()) &&
12628          "Not extracted from 128-/256-bit vector.");
12629
12630   unsigned FullMask = (1U << VT.getVectorNumElements()) - 1U;
12631
12632   for (DenseMap<SDValue, unsigned>::const_iterator
12633         I = VecInMap.begin(), E = VecInMap.end(); I != E; ++I) {
12634     // Quit if not all elements are used.
12635     if (I->second != FullMask)
12636       return SDValue();
12637   }
12638
12639   EVT TestVT = VT.is128BitVector() ? MVT::v2i64 : MVT::v4i64;
12640
12641   // Cast all vectors into TestVT for PTEST.
12642   for (unsigned i = 0, e = VecIns.size(); i < e; ++i)
12643     VecIns[i] = DAG.getBitcast(TestVT, VecIns[i]);
12644
12645   // If more than one full vectors are evaluated, OR them first before PTEST.
12646   for (unsigned Slot = 0, e = VecIns.size(); e - Slot > 1; Slot += 2, e += 1) {
12647     // Each iteration will OR 2 nodes and append the result until there is only
12648     // 1 node left, i.e. the final OR'd value of all vectors.
12649     SDValue LHS = VecIns[Slot];
12650     SDValue RHS = VecIns[Slot + 1];
12651     VecIns.push_back(DAG.getNode(ISD::OR, DL, TestVT, LHS, RHS));
12652   }
12653
12654   return DAG.getNode(X86ISD::PTEST, DL, MVT::i32,
12655                      VecIns.back(), VecIns.back());
12656 }
12657
12658 /// \brief return true if \c Op has a use that doesn't just read flags.
12659 static bool hasNonFlagsUse(SDValue Op) {
12660   for (SDNode::use_iterator UI = Op->use_begin(), UE = Op->use_end(); UI != UE;
12661        ++UI) {
12662     SDNode *User = *UI;
12663     unsigned UOpNo = UI.getOperandNo();
12664     if (User->getOpcode() == ISD::TRUNCATE && User->hasOneUse()) {
12665       // Look pass truncate.
12666       UOpNo = User->use_begin().getOperandNo();
12667       User = *User->use_begin();
12668     }
12669
12670     if (User->getOpcode() != ISD::BRCOND && User->getOpcode() != ISD::SETCC &&
12671         !(User->getOpcode() == ISD::SELECT && UOpNo == 0))
12672       return true;
12673   }
12674   return false;
12675 }
12676
12677 /// Emit nodes that will be selected as "test Op0,Op0", or something
12678 /// equivalent.
12679 SDValue X86TargetLowering::EmitTest(SDValue Op, unsigned X86CC, SDLoc dl,
12680                                     SelectionDAG &DAG) const {
12681   if (Op.getValueType() == MVT::i1) {
12682     SDValue ExtOp = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i8, Op);
12683     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, ExtOp,
12684                        DAG.getConstant(0, dl, MVT::i8));
12685   }
12686   // CF and OF aren't always set the way we want. Determine which
12687   // of these we need.
12688   bool NeedCF = false;
12689   bool NeedOF = false;
12690   switch (X86CC) {
12691   default: break;
12692   case X86::COND_A: case X86::COND_AE:
12693   case X86::COND_B: case X86::COND_BE:
12694     NeedCF = true;
12695     break;
12696   case X86::COND_G: case X86::COND_GE:
12697   case X86::COND_L: case X86::COND_LE:
12698   case X86::COND_O: case X86::COND_NO: {
12699     // Check if we really need to set the
12700     // Overflow flag. If NoSignedWrap is present
12701     // that is not actually needed.
12702     switch (Op->getOpcode()) {
12703     case ISD::ADD:
12704     case ISD::SUB:
12705     case ISD::MUL:
12706     case ISD::SHL: {
12707       const auto *BinNode = cast<BinaryWithFlagsSDNode>(Op.getNode());
12708       if (BinNode->Flags.hasNoSignedWrap())
12709         break;
12710     }
12711     default:
12712       NeedOF = true;
12713       break;
12714     }
12715     break;
12716   }
12717   }
12718   // See if we can use the EFLAGS value from the operand instead of
12719   // doing a separate TEST. TEST always sets OF and CF to 0, so unless
12720   // we prove that the arithmetic won't overflow, we can't use OF or CF.
12721   if (Op.getResNo() != 0 || NeedOF || NeedCF) {
12722     // Emit a CMP with 0, which is the TEST pattern.
12723     //if (Op.getValueType() == MVT::i1)
12724     //  return DAG.getNode(X86ISD::CMP, dl, MVT::i1, Op,
12725     //                     DAG.getConstant(0, MVT::i1));
12726     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12727                        DAG.getConstant(0, dl, Op.getValueType()));
12728   }
12729   unsigned Opcode = 0;
12730   unsigned NumOperands = 0;
12731
12732   // Truncate operations may prevent the merge of the SETCC instruction
12733   // and the arithmetic instruction before it. Attempt to truncate the operands
12734   // of the arithmetic instruction and use a reduced bit-width instruction.
12735   bool NeedTruncation = false;
12736   SDValue ArithOp = Op;
12737   if (Op->getOpcode() == ISD::TRUNCATE && Op->hasOneUse()) {
12738     SDValue Arith = Op->getOperand(0);
12739     // Both the trunc and the arithmetic op need to have one user each.
12740     if (Arith->hasOneUse())
12741       switch (Arith.getOpcode()) {
12742         default: break;
12743         case ISD::ADD:
12744         case ISD::SUB:
12745         case ISD::AND:
12746         case ISD::OR:
12747         case ISD::XOR: {
12748           NeedTruncation = true;
12749           ArithOp = Arith;
12750         }
12751       }
12752   }
12753
12754   // NOTICE: In the code below we use ArithOp to hold the arithmetic operation
12755   // which may be the result of a CAST.  We use the variable 'Op', which is the
12756   // non-casted variable when we check for possible users.
12757   switch (ArithOp.getOpcode()) {
12758   case ISD::ADD:
12759     // Due to an isel shortcoming, be conservative if this add is likely to be
12760     // selected as part of a load-modify-store instruction. When the root node
12761     // in a match is a store, isel doesn't know how to remap non-chain non-flag
12762     // uses of other nodes in the match, such as the ADD in this case. This
12763     // leads to the ADD being left around and reselected, with the result being
12764     // two adds in the output.  Alas, even if none our users are stores, that
12765     // doesn't prove we're O.K.  Ergo, if we have any parents that aren't
12766     // CopyToReg or SETCC, eschew INC/DEC.  A better fix seems to require
12767     // climbing the DAG back to the root, and it doesn't seem to be worth the
12768     // effort.
12769     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12770          UE = Op.getNode()->use_end(); UI != UE; ++UI)
12771       if (UI->getOpcode() != ISD::CopyToReg &&
12772           UI->getOpcode() != ISD::SETCC &&
12773           UI->getOpcode() != ISD::STORE)
12774         goto default_case;
12775
12776     if (ConstantSDNode *C =
12777         dyn_cast<ConstantSDNode>(ArithOp.getNode()->getOperand(1))) {
12778       // An add of one will be selected as an INC.
12779       if (C->getAPIntValue() == 1 && !Subtarget->slowIncDec()) {
12780         Opcode = X86ISD::INC;
12781         NumOperands = 1;
12782         break;
12783       }
12784
12785       // An add of negative one (subtract of one) will be selected as a DEC.
12786       if (C->getAPIntValue().isAllOnesValue() && !Subtarget->slowIncDec()) {
12787         Opcode = X86ISD::DEC;
12788         NumOperands = 1;
12789         break;
12790       }
12791     }
12792
12793     // Otherwise use a regular EFLAGS-setting add.
12794     Opcode = X86ISD::ADD;
12795     NumOperands = 2;
12796     break;
12797   case ISD::SHL:
12798   case ISD::SRL:
12799     // If we have a constant logical shift that's only used in a comparison
12800     // against zero turn it into an equivalent AND. This allows turning it into
12801     // a TEST instruction later.
12802     if ((X86CC == X86::COND_E || X86CC == X86::COND_NE) && Op->hasOneUse() &&
12803         isa<ConstantSDNode>(Op->getOperand(1)) && !hasNonFlagsUse(Op)) {
12804       EVT VT = Op.getValueType();
12805       unsigned BitWidth = VT.getSizeInBits();
12806       unsigned ShAmt = Op->getConstantOperandVal(1);
12807       if (ShAmt >= BitWidth) // Avoid undefined shifts.
12808         break;
12809       APInt Mask = ArithOp.getOpcode() == ISD::SRL
12810                        ? APInt::getHighBitsSet(BitWidth, BitWidth - ShAmt)
12811                        : APInt::getLowBitsSet(BitWidth, BitWidth - ShAmt);
12812       if (!Mask.isSignedIntN(32)) // Avoid large immediates.
12813         break;
12814       SDValue New = DAG.getNode(ISD::AND, dl, VT, Op->getOperand(0),
12815                                 DAG.getConstant(Mask, dl, VT));
12816       DAG.ReplaceAllUsesWith(Op, New);
12817       Op = New;
12818     }
12819     break;
12820
12821   case ISD::AND:
12822     // If the primary and result isn't used, don't bother using X86ISD::AND,
12823     // because a TEST instruction will be better.
12824     if (!hasNonFlagsUse(Op))
12825       break;
12826     // FALL THROUGH
12827   case ISD::SUB:
12828   case ISD::OR:
12829   case ISD::XOR:
12830     // Due to the ISEL shortcoming noted above, be conservative if this op is
12831     // likely to be selected as part of a load-modify-store instruction.
12832     for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
12833            UE = Op.getNode()->use_end(); UI != UE; ++UI)
12834       if (UI->getOpcode() == ISD::STORE)
12835         goto default_case;
12836
12837     // Otherwise use a regular EFLAGS-setting instruction.
12838     switch (ArithOp.getOpcode()) {
12839     default: llvm_unreachable("unexpected operator!");
12840     case ISD::SUB: Opcode = X86ISD::SUB; break;
12841     case ISD::XOR: Opcode = X86ISD::XOR; break;
12842     case ISD::AND: Opcode = X86ISD::AND; break;
12843     case ISD::OR: {
12844       if (!NeedTruncation && (X86CC == X86::COND_E || X86CC == X86::COND_NE)) {
12845         SDValue EFLAGS = LowerVectorAllZeroTest(Op, Subtarget, DAG);
12846         if (EFLAGS.getNode())
12847           return EFLAGS;
12848       }
12849       Opcode = X86ISD::OR;
12850       break;
12851     }
12852     }
12853
12854     NumOperands = 2;
12855     break;
12856   case X86ISD::ADD:
12857   case X86ISD::SUB:
12858   case X86ISD::INC:
12859   case X86ISD::DEC:
12860   case X86ISD::OR:
12861   case X86ISD::XOR:
12862   case X86ISD::AND:
12863     return SDValue(Op.getNode(), 1);
12864   default:
12865   default_case:
12866     break;
12867   }
12868
12869   // If we found that truncation is beneficial, perform the truncation and
12870   // update 'Op'.
12871   if (NeedTruncation) {
12872     EVT VT = Op.getValueType();
12873     SDValue WideVal = Op->getOperand(0);
12874     EVT WideVT = WideVal.getValueType();
12875     unsigned ConvertedOp = 0;
12876     // Use a target machine opcode to prevent further DAGCombine
12877     // optimizations that may separate the arithmetic operations
12878     // from the setcc node.
12879     switch (WideVal.getOpcode()) {
12880       default: break;
12881       case ISD::ADD: ConvertedOp = X86ISD::ADD; break;
12882       case ISD::SUB: ConvertedOp = X86ISD::SUB; break;
12883       case ISD::AND: ConvertedOp = X86ISD::AND; break;
12884       case ISD::OR:  ConvertedOp = X86ISD::OR;  break;
12885       case ISD::XOR: ConvertedOp = X86ISD::XOR; break;
12886     }
12887
12888     if (ConvertedOp) {
12889       const TargetLowering &TLI = DAG.getTargetLoweringInfo();
12890       if (TLI.isOperationLegal(WideVal.getOpcode(), WideVT)) {
12891         SDValue V0 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(0));
12892         SDValue V1 = DAG.getNode(ISD::TRUNCATE, dl, VT, WideVal.getOperand(1));
12893         Op = DAG.getNode(ConvertedOp, dl, VT, V0, V1);
12894       }
12895     }
12896   }
12897
12898   if (Opcode == 0)
12899     // Emit a CMP with 0, which is the TEST pattern.
12900     return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op,
12901                        DAG.getConstant(0, dl, Op.getValueType()));
12902
12903   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
12904   SmallVector<SDValue, 4> Ops(Op->op_begin(), Op->op_begin() + NumOperands);
12905
12906   SDValue New = DAG.getNode(Opcode, dl, VTs, Ops);
12907   DAG.ReplaceAllUsesWith(Op, New);
12908   return SDValue(New.getNode(), 1);
12909 }
12910
12911 /// Emit nodes that will be selected as "cmp Op0,Op1", or something
12912 /// equivalent.
12913 SDValue X86TargetLowering::EmitCmp(SDValue Op0, SDValue Op1, unsigned X86CC,
12914                                    SDLoc dl, SelectionDAG &DAG) const {
12915   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op1)) {
12916     if (C->getAPIntValue() == 0)
12917       return EmitTest(Op0, X86CC, dl, DAG);
12918
12919      if (Op0.getValueType() == MVT::i1)
12920        llvm_unreachable("Unexpected comparison operation for MVT::i1 operands");
12921   }
12922
12923   if ((Op0.getValueType() == MVT::i8 || Op0.getValueType() == MVT::i16 ||
12924        Op0.getValueType() == MVT::i32 || Op0.getValueType() == MVT::i64)) {
12925     // Do the comparison at i32 if it's smaller, besides the Atom case.
12926     // This avoids subregister aliasing issues. Keep the smaller reference
12927     // if we're optimizing for size, however, as that'll allow better folding
12928     // of memory operations.
12929     if (Op0.getValueType() != MVT::i32 && Op0.getValueType() != MVT::i64 &&
12930         !DAG.getMachineFunction().getFunction()->hasFnAttribute(
12931             Attribute::MinSize) &&
12932         !Subtarget->isAtom()) {
12933       unsigned ExtendOp =
12934           isX86CCUnsigned(X86CC) ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
12935       Op0 = DAG.getNode(ExtendOp, dl, MVT::i32, Op0);
12936       Op1 = DAG.getNode(ExtendOp, dl, MVT::i32, Op1);
12937     }
12938     // Use SUB instead of CMP to enable CSE between SUB and CMP.
12939     SDVTList VTs = DAG.getVTList(Op0.getValueType(), MVT::i32);
12940     SDValue Sub = DAG.getNode(X86ISD::SUB, dl, VTs,
12941                               Op0, Op1);
12942     return SDValue(Sub.getNode(), 1);
12943   }
12944   return DAG.getNode(X86ISD::CMP, dl, MVT::i32, Op0, Op1);
12945 }
12946
12947 /// Convert a comparison if required by the subtarget.
12948 SDValue X86TargetLowering::ConvertCmpIfNecessary(SDValue Cmp,
12949                                                  SelectionDAG &DAG) const {
12950   // If the subtarget does not support the FUCOMI instruction, floating-point
12951   // comparisons have to be converted.
12952   if (Subtarget->hasCMov() ||
12953       Cmp.getOpcode() != X86ISD::CMP ||
12954       !Cmp.getOperand(0).getValueType().isFloatingPoint() ||
12955       !Cmp.getOperand(1).getValueType().isFloatingPoint())
12956     return Cmp;
12957
12958   // The instruction selector will select an FUCOM instruction instead of
12959   // FUCOMI, which writes the comparison result to FPSW instead of EFLAGS. Hence
12960   // build an SDNode sequence that transfers the result from FPSW into EFLAGS:
12961   // (X86sahf (trunc (srl (X86fp_stsw (trunc (X86cmp ...)), 8))))
12962   SDLoc dl(Cmp);
12963   SDValue TruncFPSW = DAG.getNode(ISD::TRUNCATE, dl, MVT::i16, Cmp);
12964   SDValue FNStSW = DAG.getNode(X86ISD::FNSTSW16r, dl, MVT::i16, TruncFPSW);
12965   SDValue Srl = DAG.getNode(ISD::SRL, dl, MVT::i16, FNStSW,
12966                             DAG.getConstant(8, dl, MVT::i8));
12967   SDValue TruncSrl = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Srl);
12968   return DAG.getNode(X86ISD::SAHF, dl, MVT::i32, TruncSrl);
12969 }
12970
12971 /// The minimum architected relative accuracy is 2^-12. We need one
12972 /// Newton-Raphson step to have a good float result (24 bits of precision).
12973 SDValue X86TargetLowering::getRsqrtEstimate(SDValue Op,
12974                                             DAGCombinerInfo &DCI,
12975                                             unsigned &RefinementSteps,
12976                                             bool &UseOneConstNR) const {
12977   EVT VT = Op.getValueType();
12978   const char *RecipOp;
12979
12980   // SSE1 has rsqrtss and rsqrtps. AVX adds a 256-bit variant for rsqrtps.
12981   // TODO: Add support for AVX512 (v16f32).
12982   // It is likely not profitable to do this for f64 because a double-precision
12983   // rsqrt estimate with refinement on x86 prior to FMA requires at least 16
12984   // instructions: convert to single, rsqrtss, convert back to double, refine
12985   // (3 steps = at least 13 insts). If an 'rsqrtsd' variant was added to the ISA
12986   // along with FMA, this could be a throughput win.
12987   if (VT == MVT::f32 && Subtarget->hasSSE1())
12988     RecipOp = "sqrtf";
12989   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
12990            (VT == MVT::v8f32 && Subtarget->hasAVX()))
12991     RecipOp = "vec-sqrtf";
12992   else
12993     return SDValue();
12994
12995   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
12996   if (!Recips.isEnabled(RecipOp))
12997     return SDValue();
12998
12999   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13000   UseOneConstNR = false;
13001   return DCI.DAG.getNode(X86ISD::FRSQRT, SDLoc(Op), VT, Op);
13002 }
13003
13004 /// The minimum architected relative accuracy is 2^-12. We need one
13005 /// Newton-Raphson step to have a good float result (24 bits of precision).
13006 SDValue X86TargetLowering::getRecipEstimate(SDValue Op,
13007                                             DAGCombinerInfo &DCI,
13008                                             unsigned &RefinementSteps) const {
13009   EVT VT = Op.getValueType();
13010   const char *RecipOp;
13011
13012   // SSE1 has rcpss and rcpps. AVX adds a 256-bit variant for rcpps.
13013   // TODO: Add support for AVX512 (v16f32).
13014   // It is likely not profitable to do this for f64 because a double-precision
13015   // reciprocal estimate with refinement on x86 prior to FMA requires
13016   // 15 instructions: convert to single, rcpss, convert back to double, refine
13017   // (3 steps = 12 insts). If an 'rcpsd' variant was added to the ISA
13018   // along with FMA, this could be a throughput win.
13019   if (VT == MVT::f32 && Subtarget->hasSSE1())
13020     RecipOp = "divf";
13021   else if ((VT == MVT::v4f32 && Subtarget->hasSSE1()) ||
13022            (VT == MVT::v8f32 && Subtarget->hasAVX()))
13023     RecipOp = "vec-divf";
13024   else
13025     return SDValue();
13026
13027   TargetRecip Recips = DCI.DAG.getTarget().Options.Reciprocals;
13028   if (!Recips.isEnabled(RecipOp))
13029     return SDValue();
13030
13031   RefinementSteps = Recips.getRefinementSteps(RecipOp);
13032   return DCI.DAG.getNode(X86ISD::FRCP, SDLoc(Op), VT, Op);
13033 }
13034
13035 /// If we have at least two divisions that use the same divisor, convert to
13036 /// multplication by a reciprocal. This may need to be adjusted for a given
13037 /// CPU if a division's cost is not at least twice the cost of a multiplication.
13038 /// This is because we still need one division to calculate the reciprocal and
13039 /// then we need two multiplies by that reciprocal as replacements for the
13040 /// original divisions.
13041 bool X86TargetLowering::combineRepeatedFPDivisors(unsigned NumUsers) const {
13042   return NumUsers > 1;
13043 }
13044
13045 static bool isAllOnes(SDValue V) {
13046   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
13047   return C && C->isAllOnesValue();
13048 }
13049
13050 /// LowerToBT - Result of 'and' is compared against zero. Turn it into a BT node
13051 /// if it's possible.
13052 SDValue X86TargetLowering::LowerToBT(SDValue And, ISD::CondCode CC,
13053                                      SDLoc dl, SelectionDAG &DAG) const {
13054   SDValue Op0 = And.getOperand(0);
13055   SDValue Op1 = And.getOperand(1);
13056   if (Op0.getOpcode() == ISD::TRUNCATE)
13057     Op0 = Op0.getOperand(0);
13058   if (Op1.getOpcode() == ISD::TRUNCATE)
13059     Op1 = Op1.getOperand(0);
13060
13061   SDValue LHS, RHS;
13062   if (Op1.getOpcode() == ISD::SHL)
13063     std::swap(Op0, Op1);
13064   if (Op0.getOpcode() == ISD::SHL) {
13065     if (ConstantSDNode *And00C = dyn_cast<ConstantSDNode>(Op0.getOperand(0)))
13066       if (And00C->getZExtValue() == 1) {
13067         // If we looked past a truncate, check that it's only truncating away
13068         // known zeros.
13069         unsigned BitWidth = Op0.getValueSizeInBits();
13070         unsigned AndBitWidth = And.getValueSizeInBits();
13071         if (BitWidth > AndBitWidth) {
13072           APInt Zeros, Ones;
13073           DAG.computeKnownBits(Op0, Zeros, Ones);
13074           if (Zeros.countLeadingOnes() < BitWidth - AndBitWidth)
13075             return SDValue();
13076         }
13077         LHS = Op1;
13078         RHS = Op0.getOperand(1);
13079       }
13080   } else if (Op1.getOpcode() == ISD::Constant) {
13081     ConstantSDNode *AndRHS = cast<ConstantSDNode>(Op1);
13082     uint64_t AndRHSVal = AndRHS->getZExtValue();
13083     SDValue AndLHS = Op0;
13084
13085     if (AndRHSVal == 1 && AndLHS.getOpcode() == ISD::SRL) {
13086       LHS = AndLHS.getOperand(0);
13087       RHS = AndLHS.getOperand(1);
13088     }
13089
13090     // Use BT if the immediate can't be encoded in a TEST instruction.
13091     if (!isUInt<32>(AndRHSVal) && isPowerOf2_64(AndRHSVal)) {
13092       LHS = AndLHS;
13093       RHS = DAG.getConstant(Log2_64_Ceil(AndRHSVal), dl, LHS.getValueType());
13094     }
13095   }
13096
13097   if (LHS.getNode()) {
13098     // If LHS is i8, promote it to i32 with any_extend.  There is no i8 BT
13099     // instruction.  Since the shift amount is in-range-or-undefined, we know
13100     // that doing a bittest on the i32 value is ok.  We extend to i32 because
13101     // the encoding for the i16 version is larger than the i32 version.
13102     // Also promote i16 to i32 for performance / code size reason.
13103     if (LHS.getValueType() == MVT::i8 ||
13104         LHS.getValueType() == MVT::i16)
13105       LHS = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, LHS);
13106
13107     // If the operand types disagree, extend the shift amount to match.  Since
13108     // BT ignores high bits (like shifts) we can use anyextend.
13109     if (LHS.getValueType() != RHS.getValueType())
13110       RHS = DAG.getNode(ISD::ANY_EXTEND, dl, LHS.getValueType(), RHS);
13111
13112     SDValue BT = DAG.getNode(X86ISD::BT, dl, MVT::i32, LHS, RHS);
13113     X86::CondCode Cond = CC == ISD::SETEQ ? X86::COND_AE : X86::COND_B;
13114     return DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13115                        DAG.getConstant(Cond, dl, MVT::i8), BT);
13116   }
13117
13118   return SDValue();
13119 }
13120
13121 /// \brief - Turns an ISD::CondCode into a value suitable for SSE floating point
13122 /// mask CMPs.
13123 static int translateX86FSETCC(ISD::CondCode SetCCOpcode, SDValue &Op0,
13124                               SDValue &Op1) {
13125   unsigned SSECC;
13126   bool Swap = false;
13127
13128   // SSE Condition code mapping:
13129   //  0 - EQ
13130   //  1 - LT
13131   //  2 - LE
13132   //  3 - UNORD
13133   //  4 - NEQ
13134   //  5 - NLT
13135   //  6 - NLE
13136   //  7 - ORD
13137   switch (SetCCOpcode) {
13138   default: llvm_unreachable("Unexpected SETCC condition");
13139   case ISD::SETOEQ:
13140   case ISD::SETEQ:  SSECC = 0; break;
13141   case ISD::SETOGT:
13142   case ISD::SETGT:  Swap = true; // Fallthrough
13143   case ISD::SETLT:
13144   case ISD::SETOLT: SSECC = 1; break;
13145   case ISD::SETOGE:
13146   case ISD::SETGE:  Swap = true; // Fallthrough
13147   case ISD::SETLE:
13148   case ISD::SETOLE: SSECC = 2; break;
13149   case ISD::SETUO:  SSECC = 3; break;
13150   case ISD::SETUNE:
13151   case ISD::SETNE:  SSECC = 4; break;
13152   case ISD::SETULE: Swap = true; // Fallthrough
13153   case ISD::SETUGE: SSECC = 5; break;
13154   case ISD::SETULT: Swap = true; // Fallthrough
13155   case ISD::SETUGT: SSECC = 6; break;
13156   case ISD::SETO:   SSECC = 7; break;
13157   case ISD::SETUEQ:
13158   case ISD::SETONE: SSECC = 8; break;
13159   }
13160   if (Swap)
13161     std::swap(Op0, Op1);
13162
13163   return SSECC;
13164 }
13165
13166 // Lower256IntVSETCC - Break a VSETCC 256-bit integer VSETCC into two new 128
13167 // ones, and then concatenate the result back.
13168 static SDValue Lower256IntVSETCC(SDValue Op, SelectionDAG &DAG) {
13169   MVT VT = Op.getSimpleValueType();
13170
13171   assert(VT.is256BitVector() && Op.getOpcode() == ISD::SETCC &&
13172          "Unsupported value type for operation");
13173
13174   unsigned NumElems = VT.getVectorNumElements();
13175   SDLoc dl(Op);
13176   SDValue CC = Op.getOperand(2);
13177
13178   // Extract the LHS vectors
13179   SDValue LHS = Op.getOperand(0);
13180   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
13181   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
13182
13183   // Extract the RHS vectors
13184   SDValue RHS = Op.getOperand(1);
13185   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
13186   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
13187
13188   // Issue the operation on the smaller types and concatenate the result back
13189   MVT EltVT = VT.getVectorElementType();
13190   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
13191   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
13192                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1, CC),
13193                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2, CC));
13194 }
13195
13196 static SDValue LowerBoolVSETCC_AVX512(SDValue Op, SelectionDAG &DAG) {
13197   SDValue Op0 = Op.getOperand(0);
13198   SDValue Op1 = Op.getOperand(1);
13199   SDValue CC = Op.getOperand(2);
13200   MVT VT = Op.getSimpleValueType();
13201   SDLoc dl(Op);
13202
13203   assert(Op0.getValueType().getVectorElementType() == MVT::i1 &&
13204          "Unexpected type for boolean compare operation");
13205   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13206   SDValue NotOp0 = DAG.getNode(ISD::XOR, dl, VT, Op0,
13207                                DAG.getConstant(-1, dl, VT));
13208   SDValue NotOp1 = DAG.getNode(ISD::XOR, dl, VT, Op1,
13209                                DAG.getConstant(-1, dl, VT));
13210   switch (SetCCOpcode) {
13211   default: llvm_unreachable("Unexpected SETCC condition");
13212   case ISD::SETEQ:
13213     // (x == y) -> ~(x ^ y)
13214     return DAG.getNode(ISD::XOR, dl, VT,
13215                        DAG.getNode(ISD::XOR, dl, VT, Op0, Op1),
13216                        DAG.getConstant(-1, dl, VT));
13217   case ISD::SETNE:
13218     // (x != y) -> (x ^ y)
13219     return DAG.getNode(ISD::XOR, dl, VT, Op0, Op1);
13220   case ISD::SETUGT:
13221   case ISD::SETGT:
13222     // (x > y) -> (x & ~y)
13223     return DAG.getNode(ISD::AND, dl, VT, Op0, NotOp1);
13224   case ISD::SETULT:
13225   case ISD::SETLT:
13226     // (x < y) -> (~x & y)
13227     return DAG.getNode(ISD::AND, dl, VT, NotOp0, Op1);
13228   case ISD::SETULE:
13229   case ISD::SETLE:
13230     // (x <= y) -> (~x | y)
13231     return DAG.getNode(ISD::OR, dl, VT, NotOp0, Op1);
13232   case ISD::SETUGE:
13233   case ISD::SETGE:
13234     // (x >=y) -> (x | ~y)
13235     return DAG.getNode(ISD::OR, dl, VT, Op0, NotOp1);
13236   }
13237 }
13238
13239 static SDValue LowerIntVSETCC_AVX512(SDValue Op, SelectionDAG &DAG,
13240                                      const X86Subtarget *Subtarget) {
13241   SDValue Op0 = Op.getOperand(0);
13242   SDValue Op1 = Op.getOperand(1);
13243   SDValue CC = Op.getOperand(2);
13244   MVT VT = Op.getSimpleValueType();
13245   SDLoc dl(Op);
13246
13247   assert(Op0.getValueType().getVectorElementType().getSizeInBits() >= 8 &&
13248          Op.getValueType().getScalarType() == MVT::i1 &&
13249          "Cannot set masked compare for this operation");
13250
13251   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13252   unsigned  Opc = 0;
13253   bool Unsigned = false;
13254   bool Swap = false;
13255   unsigned SSECC;
13256   switch (SetCCOpcode) {
13257   default: llvm_unreachable("Unexpected SETCC condition");
13258   case ISD::SETNE:  SSECC = 4; break;
13259   case ISD::SETEQ:  Opc = X86ISD::PCMPEQM; break;
13260   case ISD::SETUGT: SSECC = 6; Unsigned = true; break;
13261   case ISD::SETLT:  Swap = true; //fall-through
13262   case ISD::SETGT:  Opc = X86ISD::PCMPGTM; break;
13263   case ISD::SETULT: SSECC = 1; Unsigned = true; break;
13264   case ISD::SETUGE: SSECC = 5; Unsigned = true; break; //NLT
13265   case ISD::SETGE:  Swap = true; SSECC = 2; break; // LE + swap
13266   case ISD::SETULE: Unsigned = true; //fall-through
13267   case ISD::SETLE:  SSECC = 2; break;
13268   }
13269
13270   if (Swap)
13271     std::swap(Op0, Op1);
13272   if (Opc)
13273     return DAG.getNode(Opc, dl, VT, Op0, Op1);
13274   Opc = Unsigned ? X86ISD::CMPMU: X86ISD::CMPM;
13275   return DAG.getNode(Opc, dl, VT, Op0, Op1,
13276                      DAG.getConstant(SSECC, dl, MVT::i8));
13277 }
13278
13279 /// \brief Try to turn a VSETULT into a VSETULE by modifying its second
13280 /// operand \p Op1.  If non-trivial (for example because it's not constant)
13281 /// return an empty value.
13282 static SDValue ChangeVSETULTtoVSETULE(SDLoc dl, SDValue Op1, SelectionDAG &DAG)
13283 {
13284   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op1.getNode());
13285   if (!BV)
13286     return SDValue();
13287
13288   MVT VT = Op1.getSimpleValueType();
13289   MVT EVT = VT.getVectorElementType();
13290   unsigned n = VT.getVectorNumElements();
13291   SmallVector<SDValue, 8> ULTOp1;
13292
13293   for (unsigned i = 0; i < n; ++i) {
13294     ConstantSDNode *Elt = dyn_cast<ConstantSDNode>(BV->getOperand(i));
13295     if (!Elt || Elt->isOpaque() || Elt->getValueType(0) != EVT)
13296       return SDValue();
13297
13298     // Avoid underflow.
13299     APInt Val = Elt->getAPIntValue();
13300     if (Val == 0)
13301       return SDValue();
13302
13303     ULTOp1.push_back(DAG.getConstant(Val - 1, dl, EVT));
13304   }
13305
13306   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, ULTOp1);
13307 }
13308
13309 static SDValue LowerVSETCC(SDValue Op, const X86Subtarget *Subtarget,
13310                            SelectionDAG &DAG) {
13311   SDValue Op0 = Op.getOperand(0);
13312   SDValue Op1 = Op.getOperand(1);
13313   SDValue CC = Op.getOperand(2);
13314   MVT VT = Op.getSimpleValueType();
13315   ISD::CondCode SetCCOpcode = cast<CondCodeSDNode>(CC)->get();
13316   bool isFP = Op.getOperand(1).getSimpleValueType().isFloatingPoint();
13317   SDLoc dl(Op);
13318
13319   if (isFP) {
13320 #ifndef NDEBUG
13321     MVT EltVT = Op0.getSimpleValueType().getVectorElementType();
13322     assert(EltVT == MVT::f32 || EltVT == MVT::f64);
13323 #endif
13324
13325     unsigned SSECC = translateX86FSETCC(SetCCOpcode, Op0, Op1);
13326     unsigned Opc = X86ISD::CMPP;
13327     if (Subtarget->hasAVX512() && VT.getVectorElementType() == MVT::i1) {
13328       assert(VT.getVectorNumElements() <= 16);
13329       Opc = X86ISD::CMPM;
13330     }
13331     // In the two special cases we can't handle, emit two comparisons.
13332     if (SSECC == 8) {
13333       unsigned CC0, CC1;
13334       unsigned CombineOpc;
13335       if (SetCCOpcode == ISD::SETUEQ) {
13336         CC0 = 3; CC1 = 0; CombineOpc = ISD::OR;
13337       } else {
13338         assert(SetCCOpcode == ISD::SETONE);
13339         CC0 = 7; CC1 = 4; CombineOpc = ISD::AND;
13340       }
13341
13342       SDValue Cmp0 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13343                                  DAG.getConstant(CC0, dl, MVT::i8));
13344       SDValue Cmp1 = DAG.getNode(Opc, dl, VT, Op0, Op1,
13345                                  DAG.getConstant(CC1, dl, MVT::i8));
13346       return DAG.getNode(CombineOpc, dl, VT, Cmp0, Cmp1);
13347     }
13348     // Handle all other FP comparisons here.
13349     return DAG.getNode(Opc, dl, VT, Op0, Op1,
13350                        DAG.getConstant(SSECC, dl, MVT::i8));
13351   }
13352
13353   // Break 256-bit integer vector compare into smaller ones.
13354   if (VT.is256BitVector() && !Subtarget->hasInt256())
13355     return Lower256IntVSETCC(Op, DAG);
13356
13357   EVT OpVT = Op1.getValueType();
13358   if (OpVT.getVectorElementType() == MVT::i1)
13359     return LowerBoolVSETCC_AVX512(Op, DAG);
13360
13361   bool MaskResult = (VT.getVectorElementType() == MVT::i1);
13362   if (Subtarget->hasAVX512()) {
13363     if (Op1.getValueType().is512BitVector() ||
13364         (Subtarget->hasBWI() && Subtarget->hasVLX()) ||
13365         (MaskResult && OpVT.getVectorElementType().getSizeInBits() >= 32))
13366       return LowerIntVSETCC_AVX512(Op, DAG, Subtarget);
13367
13368     // In AVX-512 architecture setcc returns mask with i1 elements,
13369     // But there is no compare instruction for i8 and i16 elements in KNL.
13370     // We are not talking about 512-bit operands in this case, these
13371     // types are illegal.
13372     if (MaskResult &&
13373         (OpVT.getVectorElementType().getSizeInBits() < 32 &&
13374          OpVT.getVectorElementType().getSizeInBits() >= 8))
13375       return DAG.getNode(ISD::TRUNCATE, dl, VT,
13376                          DAG.getNode(ISD::SETCC, dl, OpVT, Op0, Op1, CC));
13377   }
13378
13379   // We are handling one of the integer comparisons here.  Since SSE only has
13380   // GT and EQ comparisons for integer, swapping operands and multiple
13381   // operations may be required for some comparisons.
13382   unsigned Opc;
13383   bool Swap = false, Invert = false, FlipSigns = false, MinMax = false;
13384   bool Subus = false;
13385
13386   switch (SetCCOpcode) {
13387   default: llvm_unreachable("Unexpected SETCC condition");
13388   case ISD::SETNE:  Invert = true;
13389   case ISD::SETEQ:  Opc = X86ISD::PCMPEQ; break;
13390   case ISD::SETLT:  Swap = true;
13391   case ISD::SETGT:  Opc = X86ISD::PCMPGT; break;
13392   case ISD::SETGE:  Swap = true;
13393   case ISD::SETLE:  Opc = X86ISD::PCMPGT;
13394                     Invert = true; break;
13395   case ISD::SETULT: Swap = true;
13396   case ISD::SETUGT: Opc = X86ISD::PCMPGT;
13397                     FlipSigns = true; break;
13398   case ISD::SETUGE: Swap = true;
13399   case ISD::SETULE: Opc = X86ISD::PCMPGT;
13400                     FlipSigns = true; Invert = true; break;
13401   }
13402
13403   // Special case: Use min/max operations for SETULE/SETUGE
13404   MVT VET = VT.getVectorElementType();
13405   bool hasMinMax =
13406        (Subtarget->hasSSE41() && (VET >= MVT::i8 && VET <= MVT::i32))
13407     || (Subtarget->hasSSE2()  && (VET == MVT::i8));
13408
13409   if (hasMinMax) {
13410     switch (SetCCOpcode) {
13411     default: break;
13412     case ISD::SETULE: Opc = ISD::UMIN; MinMax = true; break;
13413     case ISD::SETUGE: Opc = ISD::UMAX; MinMax = true; break;
13414     }
13415
13416     if (MinMax) { Swap = false; Invert = false; FlipSigns = false; }
13417   }
13418
13419   bool hasSubus = Subtarget->hasSSE2() && (VET == MVT::i8 || VET == MVT::i16);
13420   if (!MinMax && hasSubus) {
13421     // As another special case, use PSUBUS[BW] when it's profitable. E.g. for
13422     // Op0 u<= Op1:
13423     //   t = psubus Op0, Op1
13424     //   pcmpeq t, <0..0>
13425     switch (SetCCOpcode) {
13426     default: break;
13427     case ISD::SETULT: {
13428       // If the comparison is against a constant we can turn this into a
13429       // setule.  With psubus, setule does not require a swap.  This is
13430       // beneficial because the constant in the register is no longer
13431       // destructed as the destination so it can be hoisted out of a loop.
13432       // Only do this pre-AVX since vpcmp* is no longer destructive.
13433       if (Subtarget->hasAVX())
13434         break;
13435       SDValue ULEOp1 = ChangeVSETULTtoVSETULE(dl, Op1, DAG);
13436       if (ULEOp1.getNode()) {
13437         Op1 = ULEOp1;
13438         Subus = true; Invert = false; Swap = false;
13439       }
13440       break;
13441     }
13442     // Psubus is better than flip-sign because it requires no inversion.
13443     case ISD::SETUGE: Subus = true; Invert = false; Swap = true;  break;
13444     case ISD::SETULE: Subus = true; Invert = false; Swap = false; break;
13445     }
13446
13447     if (Subus) {
13448       Opc = X86ISD::SUBUS;
13449       FlipSigns = false;
13450     }
13451   }
13452
13453   if (Swap)
13454     std::swap(Op0, Op1);
13455
13456   // Check that the operation in question is available (most are plain SSE2,
13457   // but PCMPGTQ and PCMPEQQ have different requirements).
13458   if (VT == MVT::v2i64) {
13459     if (Opc == X86ISD::PCMPGT && !Subtarget->hasSSE42()) {
13460       assert(Subtarget->hasSSE2() && "Don't know how to lower!");
13461
13462       // First cast everything to the right type.
13463       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13464       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13465
13466       // Since SSE has no unsigned integer comparisons, we need to flip the sign
13467       // bits of the inputs before performing those operations. The lower
13468       // compare is always unsigned.
13469       SDValue SB;
13470       if (FlipSigns) {
13471         SB = DAG.getConstant(0x80000000U, dl, MVT::v4i32);
13472       } else {
13473         SDValue Sign = DAG.getConstant(0x80000000U, dl, MVT::i32);
13474         SDValue Zero = DAG.getConstant(0x00000000U, dl, MVT::i32);
13475         SB = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v4i32,
13476                          Sign, Zero, Sign, Zero);
13477       }
13478       Op0 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op0, SB);
13479       Op1 = DAG.getNode(ISD::XOR, dl, MVT::v4i32, Op1, SB);
13480
13481       // Emulate PCMPGTQ with (hi1 > hi2) | ((hi1 == hi2) & (lo1 > lo2))
13482       SDValue GT = DAG.getNode(X86ISD::PCMPGT, dl, MVT::v4i32, Op0, Op1);
13483       SDValue EQ = DAG.getNode(X86ISD::PCMPEQ, dl, MVT::v4i32, Op0, Op1);
13484
13485       // Create masks for only the low parts/high parts of the 64 bit integers.
13486       static const int MaskHi[] = { 1, 1, 3, 3 };
13487       static const int MaskLo[] = { 0, 0, 2, 2 };
13488       SDValue EQHi = DAG.getVectorShuffle(MVT::v4i32, dl, EQ, EQ, MaskHi);
13489       SDValue GTLo = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskLo);
13490       SDValue GTHi = DAG.getVectorShuffle(MVT::v4i32, dl, GT, GT, MaskHi);
13491
13492       SDValue Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, EQHi, GTLo);
13493       Result = DAG.getNode(ISD::OR, dl, MVT::v4i32, Result, GTHi);
13494
13495       if (Invert)
13496         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13497
13498       return DAG.getBitcast(VT, Result);
13499     }
13500
13501     if (Opc == X86ISD::PCMPEQ && !Subtarget->hasSSE41()) {
13502       // If pcmpeqq is missing but pcmpeqd is available synthesize pcmpeqq with
13503       // pcmpeqd + pshufd + pand.
13504       assert(Subtarget->hasSSE2() && !FlipSigns && "Don't know how to lower!");
13505
13506       // First cast everything to the right type.
13507       Op0 = DAG.getBitcast(MVT::v4i32, Op0);
13508       Op1 = DAG.getBitcast(MVT::v4i32, Op1);
13509
13510       // Do the compare.
13511       SDValue Result = DAG.getNode(Opc, dl, MVT::v4i32, Op0, Op1);
13512
13513       // Make sure the lower and upper halves are both all-ones.
13514       static const int Mask[] = { 1, 0, 3, 2 };
13515       SDValue Shuf = DAG.getVectorShuffle(MVT::v4i32, dl, Result, Result, Mask);
13516       Result = DAG.getNode(ISD::AND, dl, MVT::v4i32, Result, Shuf);
13517
13518       if (Invert)
13519         Result = DAG.getNOT(dl, Result, MVT::v4i32);
13520
13521       return DAG.getBitcast(VT, Result);
13522     }
13523   }
13524
13525   // Since SSE has no unsigned integer comparisons, we need to flip the sign
13526   // bits of the inputs before performing those operations.
13527   if (FlipSigns) {
13528     EVT EltVT = VT.getVectorElementType();
13529     SDValue SB = DAG.getConstant(APInt::getSignBit(EltVT.getSizeInBits()), dl,
13530                                  VT);
13531     Op0 = DAG.getNode(ISD::XOR, dl, VT, Op0, SB);
13532     Op1 = DAG.getNode(ISD::XOR, dl, VT, Op1, SB);
13533   }
13534
13535   SDValue Result = DAG.getNode(Opc, dl, VT, Op0, Op1);
13536
13537   // If the logical-not of the result is required, perform that now.
13538   if (Invert)
13539     Result = DAG.getNOT(dl, Result, VT);
13540
13541   if (MinMax)
13542     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Op0, Result);
13543
13544   if (Subus)
13545     Result = DAG.getNode(X86ISD::PCMPEQ, dl, VT, Result,
13546                          getZeroVector(VT, Subtarget, DAG, dl));
13547
13548   return Result;
13549 }
13550
13551 SDValue X86TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
13552
13553   MVT VT = Op.getSimpleValueType();
13554
13555   if (VT.isVector()) return LowerVSETCC(Op, Subtarget, DAG);
13556
13557   assert(((!Subtarget->hasAVX512() && VT == MVT::i8) || (VT == MVT::i1))
13558          && "SetCC type must be 8-bit or 1-bit integer");
13559   SDValue Op0 = Op.getOperand(0);
13560   SDValue Op1 = Op.getOperand(1);
13561   SDLoc dl(Op);
13562   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
13563
13564   // Optimize to BT if possible.
13565   // Lower (X & (1 << N)) == 0 to BT(X, N).
13566   // Lower ((X >>u N) & 1) != 0 to BT(X, N).
13567   // Lower ((X >>s N) & 1) != 0 to BT(X, N).
13568   if (Op0.getOpcode() == ISD::AND && Op0.hasOneUse() &&
13569       Op1.getOpcode() == ISD::Constant &&
13570       cast<ConstantSDNode>(Op1)->isNullValue() &&
13571       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13572     SDValue NewSetCC = LowerToBT(Op0, CC, dl, DAG);
13573     if (NewSetCC.getNode()) {
13574       if (VT == MVT::i1)
13575         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, NewSetCC);
13576       return NewSetCC;
13577     }
13578   }
13579
13580   // Look for X == 0, X == 1, X != 0, or X != 1.  We can simplify some forms of
13581   // these.
13582   if (Op1.getOpcode() == ISD::Constant &&
13583       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1 ||
13584        cast<ConstantSDNode>(Op1)->isNullValue()) &&
13585       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13586
13587     // If the input is a setcc, then reuse the input setcc or use a new one with
13588     // the inverted condition.
13589     if (Op0.getOpcode() == X86ISD::SETCC) {
13590       X86::CondCode CCode = (X86::CondCode)Op0.getConstantOperandVal(0);
13591       bool Invert = (CC == ISD::SETNE) ^
13592         cast<ConstantSDNode>(Op1)->isNullValue();
13593       if (!Invert)
13594         return Op0;
13595
13596       CCode = X86::GetOppositeBranchCondition(CCode);
13597       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13598                                   DAG.getConstant(CCode, dl, MVT::i8),
13599                                   Op0.getOperand(1));
13600       if (VT == MVT::i1)
13601         return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13602       return SetCC;
13603     }
13604   }
13605   if ((Op0.getValueType() == MVT::i1) && (Op1.getOpcode() == ISD::Constant) &&
13606       (cast<ConstantSDNode>(Op1)->getZExtValue() == 1) &&
13607       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
13608
13609     ISD::CondCode NewCC = ISD::getSetCCInverse(CC, true);
13610     return DAG.getSetCC(dl, VT, Op0, DAG.getConstant(0, dl, MVT::i1), NewCC);
13611   }
13612
13613   bool isFP = Op1.getSimpleValueType().isFloatingPoint();
13614   unsigned X86CC = TranslateX86CC(CC, dl, isFP, Op0, Op1, DAG);
13615   if (X86CC == X86::COND_INVALID)
13616     return SDValue();
13617
13618   SDValue EFLAGS = EmitCmp(Op0, Op1, X86CC, dl, DAG);
13619   EFLAGS = ConvertCmpIfNecessary(EFLAGS, DAG);
13620   SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
13621                               DAG.getConstant(X86CC, dl, MVT::i8), EFLAGS);
13622   if (VT == MVT::i1)
13623     return DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, SetCC);
13624   return SetCC;
13625 }
13626
13627 // isX86LogicalCmp - Return true if opcode is a X86 logical comparison.
13628 static bool isX86LogicalCmp(SDValue Op) {
13629   unsigned Opc = Op.getNode()->getOpcode();
13630   if (Opc == X86ISD::CMP || Opc == X86ISD::COMI || Opc == X86ISD::UCOMI ||
13631       Opc == X86ISD::SAHF)
13632     return true;
13633   if (Op.getResNo() == 1 &&
13634       (Opc == X86ISD::ADD ||
13635        Opc == X86ISD::SUB ||
13636        Opc == X86ISD::ADC ||
13637        Opc == X86ISD::SBB ||
13638        Opc == X86ISD::SMUL ||
13639        Opc == X86ISD::UMUL ||
13640        Opc == X86ISD::INC ||
13641        Opc == X86ISD::DEC ||
13642        Opc == X86ISD::OR ||
13643        Opc == X86ISD::XOR ||
13644        Opc == X86ISD::AND))
13645     return true;
13646
13647   if (Op.getResNo() == 2 && Opc == X86ISD::UMUL)
13648     return true;
13649
13650   return false;
13651 }
13652
13653 static bool isTruncWithZeroHighBitsInput(SDValue V, SelectionDAG &DAG) {
13654   if (V.getOpcode() != ISD::TRUNCATE)
13655     return false;
13656
13657   SDValue VOp0 = V.getOperand(0);
13658   unsigned InBits = VOp0.getValueSizeInBits();
13659   unsigned Bits = V.getValueSizeInBits();
13660   return DAG.MaskedValueIsZero(VOp0, APInt::getHighBitsSet(InBits,InBits-Bits));
13661 }
13662
13663 SDValue X86TargetLowering::LowerSELECT(SDValue Op, SelectionDAG &DAG) const {
13664   bool addTest = true;
13665   SDValue Cond  = Op.getOperand(0);
13666   SDValue Op1 = Op.getOperand(1);
13667   SDValue Op2 = Op.getOperand(2);
13668   SDLoc DL(Op);
13669   EVT VT = Op1.getValueType();
13670   SDValue CC;
13671
13672   // Lower FP selects into a CMP/AND/ANDN/OR sequence when the necessary SSE ops
13673   // are available or VBLENDV if AVX is available.
13674   // Otherwise FP cmovs get lowered into a less efficient branch sequence later.
13675   if (Cond.getOpcode() == ISD::SETCC &&
13676       ((Subtarget->hasSSE2() && (VT == MVT::f32 || VT == MVT::f64)) ||
13677        (Subtarget->hasSSE1() && VT == MVT::f32)) &&
13678       VT == Cond.getOperand(0).getValueType() && Cond->hasOneUse()) {
13679     SDValue CondOp0 = Cond.getOperand(0), CondOp1 = Cond.getOperand(1);
13680     int SSECC = translateX86FSETCC(
13681         cast<CondCodeSDNode>(Cond.getOperand(2))->get(), CondOp0, CondOp1);
13682
13683     if (SSECC != 8) {
13684       if (Subtarget->hasAVX512()) {
13685         SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CondOp0, CondOp1,
13686                                   DAG.getConstant(SSECC, DL, MVT::i8));
13687         return DAG.getNode(X86ISD::SELECT, DL, VT, Cmp, Op1, Op2);
13688       }
13689
13690       SDValue Cmp = DAG.getNode(X86ISD::FSETCC, DL, VT, CondOp0, CondOp1,
13691                                 DAG.getConstant(SSECC, DL, MVT::i8));
13692
13693       // If we have AVX, we can use a variable vector select (VBLENDV) instead
13694       // of 3 logic instructions for size savings and potentially speed.
13695       // Unfortunately, there is no scalar form of VBLENDV.
13696
13697       // If either operand is a constant, don't try this. We can expect to
13698       // optimize away at least one of the logic instructions later in that
13699       // case, so that sequence would be faster than a variable blend.
13700
13701       // BLENDV was introduced with SSE 4.1, but the 2 register form implicitly
13702       // uses XMM0 as the selection register. That may need just as many
13703       // instructions as the AND/ANDN/OR sequence due to register moves, so
13704       // don't bother.
13705
13706       if (Subtarget->hasAVX() &&
13707           !isa<ConstantFPSDNode>(Op1) && !isa<ConstantFPSDNode>(Op2)) {
13708
13709         // Convert to vectors, do a VSELECT, and convert back to scalar.
13710         // All of the conversions should be optimized away.
13711
13712         EVT VecVT = VT == MVT::f32 ? MVT::v4f32 : MVT::v2f64;
13713         SDValue VOp1 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op1);
13714         SDValue VOp2 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Op2);
13715         SDValue VCmp = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VecVT, Cmp);
13716
13717         EVT VCmpVT = VT == MVT::f32 ? MVT::v4i32 : MVT::v2i64;
13718         VCmp = DAG.getBitcast(VCmpVT, VCmp);
13719
13720         SDValue VSel = DAG.getNode(ISD::VSELECT, DL, VecVT, VCmp, VOp1, VOp2);
13721
13722         return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
13723                            VSel, DAG.getIntPtrConstant(0, DL));
13724       }
13725       SDValue AndN = DAG.getNode(X86ISD::FANDN, DL, VT, Cmp, Op2);
13726       SDValue And = DAG.getNode(X86ISD::FAND, DL, VT, Cmp, Op1);
13727       return DAG.getNode(X86ISD::FOR, DL, VT, AndN, And);
13728     }
13729   }
13730
13731     if (VT.isVector() && VT.getScalarType() == MVT::i1) {
13732       SDValue Op1Scalar;
13733       if (ISD::isBuildVectorOfConstantSDNodes(Op1.getNode()))
13734         Op1Scalar = ConvertI1VectorToInterger(Op1, DAG);
13735       else if (Op1.getOpcode() == ISD::BITCAST && Op1.getOperand(0))
13736         Op1Scalar = Op1.getOperand(0);
13737       SDValue Op2Scalar;
13738       if (ISD::isBuildVectorOfConstantSDNodes(Op2.getNode()))
13739         Op2Scalar = ConvertI1VectorToInterger(Op2, DAG);
13740       else if (Op2.getOpcode() == ISD::BITCAST && Op2.getOperand(0))
13741         Op2Scalar = Op2.getOperand(0);
13742       if (Op1Scalar.getNode() && Op2Scalar.getNode()) {
13743         SDValue newSelect = DAG.getNode(ISD::SELECT, DL,
13744                                         Op1Scalar.getValueType(),
13745                                         Cond, Op1Scalar, Op2Scalar);
13746         if (newSelect.getValueSizeInBits() == VT.getSizeInBits())
13747           return DAG.getBitcast(VT, newSelect);
13748         SDValue ExtVec = DAG.getBitcast(MVT::v8i1, newSelect);
13749         return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, ExtVec,
13750                            DAG.getIntPtrConstant(0, DL));
13751     }
13752   }
13753
13754   if (VT == MVT::v4i1 || VT == MVT::v2i1) {
13755     SDValue zeroConst = DAG.getIntPtrConstant(0, DL);
13756     Op1 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13757                       DAG.getUNDEF(MVT::v8i1), Op1, zeroConst);
13758     Op2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, MVT::v8i1,
13759                       DAG.getUNDEF(MVT::v8i1), Op2, zeroConst);
13760     SDValue newSelect = DAG.getNode(ISD::SELECT, DL, MVT::v8i1,
13761                                     Cond, Op1, Op2);
13762     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, newSelect, zeroConst);
13763   }
13764
13765   if (Cond.getOpcode() == ISD::SETCC) {
13766     SDValue NewCond = LowerSETCC(Cond, DAG);
13767     if (NewCond.getNode())
13768       Cond = NewCond;
13769   }
13770
13771   // (select (x == 0), -1, y) -> (sign_bit (x - 1)) | y
13772   // (select (x == 0), y, -1) -> ~(sign_bit (x - 1)) | y
13773   // (select (x != 0), y, -1) -> (sign_bit (x - 1)) | y
13774   // (select (x != 0), -1, y) -> ~(sign_bit (x - 1)) | y
13775   if (Cond.getOpcode() == X86ISD::SETCC &&
13776       Cond.getOperand(1).getOpcode() == X86ISD::CMP &&
13777       isZero(Cond.getOperand(1).getOperand(1))) {
13778     SDValue Cmp = Cond.getOperand(1);
13779
13780     unsigned CondCode =cast<ConstantSDNode>(Cond.getOperand(0))->getZExtValue();
13781
13782     if ((isAllOnes(Op1) || isAllOnes(Op2)) &&
13783         (CondCode == X86::COND_E || CondCode == X86::COND_NE)) {
13784       SDValue Y = isAllOnes(Op2) ? Op1 : Op2;
13785
13786       SDValue CmpOp0 = Cmp.getOperand(0);
13787       // Apply further optimizations for special cases
13788       // (select (x != 0), -1, 0) -> neg & sbb
13789       // (select (x == 0), 0, -1) -> neg & sbb
13790       if (ConstantSDNode *YC = dyn_cast<ConstantSDNode>(Y))
13791         if (YC->isNullValue() &&
13792             (isAllOnes(Op1) == (CondCode == X86::COND_NE))) {
13793           SDVTList VTs = DAG.getVTList(CmpOp0.getValueType(), MVT::i32);
13794           SDValue Neg = DAG.getNode(X86ISD::SUB, DL, VTs,
13795                                     DAG.getConstant(0, DL,
13796                                                     CmpOp0.getValueType()),
13797                                     CmpOp0);
13798           SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13799                                     DAG.getConstant(X86::COND_B, DL, MVT::i8),
13800                                     SDValue(Neg.getNode(), 1));
13801           return Res;
13802         }
13803
13804       Cmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32,
13805                         CmpOp0, DAG.getConstant(1, DL, CmpOp0.getValueType()));
13806       Cmp = ConvertCmpIfNecessary(Cmp, DAG);
13807
13808       SDValue Res =   // Res = 0 or -1.
13809         DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13810                     DAG.getConstant(X86::COND_B, DL, MVT::i8), Cmp);
13811
13812       if (isAllOnes(Op1) != (CondCode == X86::COND_E))
13813         Res = DAG.getNOT(DL, Res, Res.getValueType());
13814
13815       ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(Op2);
13816       if (!N2C || !N2C->isNullValue())
13817         Res = DAG.getNode(ISD::OR, DL, Res.getValueType(), Res, Y);
13818       return Res;
13819     }
13820   }
13821
13822   // Look past (and (setcc_carry (cmp ...)), 1).
13823   if (Cond.getOpcode() == ISD::AND &&
13824       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
13825     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
13826     if (C && C->getAPIntValue() == 1)
13827       Cond = Cond.getOperand(0);
13828   }
13829
13830   // If condition flag is set by a X86ISD::CMP, then use it as the condition
13831   // setting operand in place of the X86ISD::SETCC.
13832   unsigned CondOpcode = Cond.getOpcode();
13833   if (CondOpcode == X86ISD::SETCC ||
13834       CondOpcode == X86ISD::SETCC_CARRY) {
13835     CC = Cond.getOperand(0);
13836
13837     SDValue Cmp = Cond.getOperand(1);
13838     unsigned Opc = Cmp.getOpcode();
13839     MVT VT = Op.getSimpleValueType();
13840
13841     bool IllegalFPCMov = false;
13842     if (VT.isFloatingPoint() && !VT.isVector() &&
13843         !isScalarFPTypeInSSEReg(VT))  // FPStack?
13844       IllegalFPCMov = !hasFPCMov(cast<ConstantSDNode>(CC)->getSExtValue());
13845
13846     if ((isX86LogicalCmp(Cmp) && !IllegalFPCMov) ||
13847         Opc == X86ISD::BT) { // FIXME
13848       Cond = Cmp;
13849       addTest = false;
13850     }
13851   } else if (CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
13852              CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
13853              ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
13854               Cond.getOperand(0).getValueType() != MVT::i8)) {
13855     SDValue LHS = Cond.getOperand(0);
13856     SDValue RHS = Cond.getOperand(1);
13857     unsigned X86Opcode;
13858     unsigned X86Cond;
13859     SDVTList VTs;
13860     switch (CondOpcode) {
13861     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
13862     case ISD::SADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
13863     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
13864     case ISD::SSUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
13865     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
13866     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
13867     default: llvm_unreachable("unexpected overflowing operator");
13868     }
13869     if (CondOpcode == ISD::UMULO)
13870       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
13871                           MVT::i32);
13872     else
13873       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
13874
13875     SDValue X86Op = DAG.getNode(X86Opcode, DL, VTs, LHS, RHS);
13876
13877     if (CondOpcode == ISD::UMULO)
13878       Cond = X86Op.getValue(2);
13879     else
13880       Cond = X86Op.getValue(1);
13881
13882     CC = DAG.getConstant(X86Cond, DL, MVT::i8);
13883     addTest = false;
13884   }
13885
13886   if (addTest) {
13887     // Look pass the truncate if the high bits are known zero.
13888     if (isTruncWithZeroHighBitsInput(Cond, DAG))
13889         Cond = Cond.getOperand(0);
13890
13891     // We know the result of AND is compared against zero. Try to match
13892     // it to BT.
13893     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
13894       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, DL, DAG);
13895       if (NewSetCC.getNode()) {
13896         CC = NewSetCC.getOperand(0);
13897         Cond = NewSetCC.getOperand(1);
13898         addTest = false;
13899       }
13900     }
13901   }
13902
13903   if (addTest) {
13904     CC = DAG.getConstant(X86::COND_NE, DL, MVT::i8);
13905     Cond = EmitTest(Cond, X86::COND_NE, DL, DAG);
13906   }
13907
13908   // a <  b ? -1 :  0 -> RES = ~setcc_carry
13909   // a <  b ?  0 : -1 -> RES = setcc_carry
13910   // a >= b ? -1 :  0 -> RES = setcc_carry
13911   // a >= b ?  0 : -1 -> RES = ~setcc_carry
13912   if (Cond.getOpcode() == X86ISD::SUB) {
13913     Cond = ConvertCmpIfNecessary(Cond, DAG);
13914     unsigned CondCode = cast<ConstantSDNode>(CC)->getZExtValue();
13915
13916     if ((CondCode == X86::COND_AE || CondCode == X86::COND_B) &&
13917         (isAllOnes(Op1) || isAllOnes(Op2)) && (isZero(Op1) || isZero(Op2))) {
13918       SDValue Res = DAG.getNode(X86ISD::SETCC_CARRY, DL, Op.getValueType(),
13919                                 DAG.getConstant(X86::COND_B, DL, MVT::i8),
13920                                 Cond);
13921       if (isAllOnes(Op1) != (CondCode == X86::COND_B))
13922         return DAG.getNOT(DL, Res, Res.getValueType());
13923       return Res;
13924     }
13925   }
13926
13927   // X86 doesn't have an i8 cmov. If both operands are the result of a truncate
13928   // widen the cmov and push the truncate through. This avoids introducing a new
13929   // branch during isel and doesn't add any extensions.
13930   if (Op.getValueType() == MVT::i8 &&
13931       Op1.getOpcode() == ISD::TRUNCATE && Op2.getOpcode() == ISD::TRUNCATE) {
13932     SDValue T1 = Op1.getOperand(0), T2 = Op2.getOperand(0);
13933     if (T1.getValueType() == T2.getValueType() &&
13934         // Blacklist CopyFromReg to avoid partial register stalls.
13935         T1.getOpcode() != ISD::CopyFromReg && T2.getOpcode()!=ISD::CopyFromReg){
13936       SDVTList VTs = DAG.getVTList(T1.getValueType(), MVT::Glue);
13937       SDValue Cmov = DAG.getNode(X86ISD::CMOV, DL, VTs, T2, T1, CC, Cond);
13938       return DAG.getNode(ISD::TRUNCATE, DL, Op.getValueType(), Cmov);
13939     }
13940   }
13941
13942   // X86ISD::CMOV means set the result (which is operand 1) to the RHS if
13943   // condition is true.
13944   SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::Glue);
13945   SDValue Ops[] = { Op2, Op1, CC, Cond };
13946   return DAG.getNode(X86ISD::CMOV, DL, VTs, Ops);
13947 }
13948
13949 static SDValue LowerSIGN_EXTEND_AVX512(SDValue Op,
13950                                        const X86Subtarget *Subtarget,
13951                                        SelectionDAG &DAG) {
13952   MVT VT = Op->getSimpleValueType(0);
13953   SDValue In = Op->getOperand(0);
13954   MVT InVT = In.getSimpleValueType();
13955   MVT VTElt = VT.getVectorElementType();
13956   MVT InVTElt = InVT.getVectorElementType();
13957   SDLoc dl(Op);
13958
13959   // SKX processor
13960   if ((InVTElt == MVT::i1) &&
13961       (((Subtarget->hasBWI() && Subtarget->hasVLX() &&
13962         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() <= 16)) ||
13963
13964        ((Subtarget->hasBWI() && VT.is512BitVector() &&
13965         VTElt.getSizeInBits() <= 16)) ||
13966
13967        ((Subtarget->hasDQI() && Subtarget->hasVLX() &&
13968         VT.getSizeInBits() <= 256 && VTElt.getSizeInBits() >= 32)) ||
13969
13970        ((Subtarget->hasDQI() && VT.is512BitVector() &&
13971         VTElt.getSizeInBits() >= 32))))
13972     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13973
13974   unsigned int NumElts = VT.getVectorNumElements();
13975
13976   if (NumElts != 8 && NumElts != 16 && !Subtarget->hasBWI())
13977     return SDValue();
13978
13979   if (VT.is512BitVector() && InVT.getVectorElementType() != MVT::i1) {
13980     if (In.getOpcode() == X86ISD::VSEXT || In.getOpcode() == X86ISD::VZEXT)
13981       return DAG.getNode(In.getOpcode(), dl, VT, In.getOperand(0));
13982     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
13983   }
13984
13985   assert (InVT.getVectorElementType() == MVT::i1 && "Unexpected vector type");
13986   MVT ExtVT = NumElts == 8 ? MVT::v8i64 : MVT::v16i32;
13987   SDValue NegOne =
13988    DAG.getConstant(APInt::getAllOnesValue(ExtVT.getScalarSizeInBits()), dl,
13989                    ExtVT);
13990   SDValue Zero =
13991    DAG.getConstant(APInt::getNullValue(ExtVT.getScalarSizeInBits()), dl, ExtVT);
13992
13993   SDValue V = DAG.getNode(ISD::VSELECT, dl, ExtVT, In, NegOne, Zero);
13994   if (VT.is512BitVector())
13995     return V;
13996   return DAG.getNode(X86ISD::VTRUNC, dl, VT, V);
13997 }
13998
13999 static SDValue LowerSIGN_EXTEND_VECTOR_INREG(SDValue Op,
14000                                              const X86Subtarget *Subtarget,
14001                                              SelectionDAG &DAG) {
14002   SDValue In = Op->getOperand(0);
14003   MVT VT = Op->getSimpleValueType(0);
14004   MVT InVT = In.getSimpleValueType();
14005   assert(VT.getSizeInBits() == InVT.getSizeInBits());
14006
14007   MVT InSVT = InVT.getScalarType();
14008   assert(VT.getScalarType().getScalarSizeInBits() > InSVT.getScalarSizeInBits());
14009
14010   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16)
14011     return SDValue();
14012   if (InSVT != MVT::i32 && InSVT != MVT::i16 && InSVT != MVT::i8)
14013     return SDValue();
14014
14015   SDLoc dl(Op);
14016
14017   // SSE41 targets can use the pmovsx* instructions directly.
14018   if (Subtarget->hasSSE41())
14019     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14020
14021   // pre-SSE41 targets unpack lower lanes and then sign-extend using SRAI.
14022   SDValue Curr = In;
14023   MVT CurrVT = InVT;
14024
14025   // As SRAI is only available on i16/i32 types, we expand only up to i32
14026   // and handle i64 separately.
14027   while (CurrVT != VT && CurrVT.getScalarType() != MVT::i32) {
14028     Curr = DAG.getNode(X86ISD::UNPCKL, dl, CurrVT, DAG.getUNDEF(CurrVT), Curr);
14029     MVT CurrSVT = MVT::getIntegerVT(CurrVT.getScalarSizeInBits() * 2);
14030     CurrVT = MVT::getVectorVT(CurrSVT, CurrVT.getVectorNumElements() / 2);
14031     Curr = DAG.getBitcast(CurrVT, Curr);
14032   }
14033
14034   SDValue SignExt = Curr;
14035   if (CurrVT != InVT) {
14036     unsigned SignExtShift =
14037         CurrVT.getScalarSizeInBits() - InSVT.getScalarSizeInBits();
14038     SignExt = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14039                           DAG.getConstant(SignExtShift, dl, MVT::i8));
14040   }
14041
14042   if (CurrVT == VT)
14043     return SignExt;
14044
14045   if (VT == MVT::v2i64 && CurrVT == MVT::v4i32) {
14046     SDValue Sign = DAG.getNode(X86ISD::VSRAI, dl, CurrVT, Curr,
14047                                DAG.getConstant(31, dl, MVT::i8));
14048     SDValue Ext = DAG.getVectorShuffle(CurrVT, dl, SignExt, Sign, {0, 4, 1, 5});
14049     return DAG.getBitcast(VT, Ext);
14050   }
14051
14052   return SDValue();
14053 }
14054
14055 static SDValue LowerSIGN_EXTEND(SDValue Op, const X86Subtarget *Subtarget,
14056                                 SelectionDAG &DAG) {
14057   MVT VT = Op->getSimpleValueType(0);
14058   SDValue In = Op->getOperand(0);
14059   MVT InVT = In.getSimpleValueType();
14060   SDLoc dl(Op);
14061
14062   if (VT.is512BitVector() || InVT.getVectorElementType() == MVT::i1)
14063     return LowerSIGN_EXTEND_AVX512(Op, Subtarget, DAG);
14064
14065   if ((VT != MVT::v4i64 || InVT != MVT::v4i32) &&
14066       (VT != MVT::v8i32 || InVT != MVT::v8i16) &&
14067       (VT != MVT::v16i16 || InVT != MVT::v16i8))
14068     return SDValue();
14069
14070   if (Subtarget->hasInt256())
14071     return DAG.getNode(X86ISD::VSEXT, dl, VT, In);
14072
14073   // Optimize vectors in AVX mode
14074   // Sign extend  v8i16 to v8i32 and
14075   //              v4i32 to v4i64
14076   //
14077   // Divide input vector into two parts
14078   // for v4i32 the shuffle mask will be { 0, 1, -1, -1} {2, 3, -1, -1}
14079   // use vpmovsx instruction to extend v4i32 -> v2i64; v8i16 -> v4i32
14080   // concat the vectors to original VT
14081
14082   unsigned NumElems = InVT.getVectorNumElements();
14083   SDValue Undef = DAG.getUNDEF(InVT);
14084
14085   SmallVector<int,8> ShufMask1(NumElems, -1);
14086   for (unsigned i = 0; i != NumElems/2; ++i)
14087     ShufMask1[i] = i;
14088
14089   SDValue OpLo = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask1[0]);
14090
14091   SmallVector<int,8> ShufMask2(NumElems, -1);
14092   for (unsigned i = 0; i != NumElems/2; ++i)
14093     ShufMask2[i] = i + NumElems/2;
14094
14095   SDValue OpHi = DAG.getVectorShuffle(InVT, dl, In, Undef, &ShufMask2[0]);
14096
14097   MVT HalfVT = MVT::getVectorVT(VT.getScalarType(),
14098                                 VT.getVectorNumElements()/2);
14099
14100   OpLo = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpLo);
14101   OpHi = DAG.getNode(X86ISD::VSEXT, dl, HalfVT, OpHi);
14102
14103   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, OpLo, OpHi);
14104 }
14105
14106 // Lower vector extended loads using a shuffle. If SSSE3 is not available we
14107 // may emit an illegal shuffle but the expansion is still better than scalar
14108 // code. We generate X86ISD::VSEXT for SEXTLOADs if it's available, otherwise
14109 // we'll emit a shuffle and a arithmetic shift.
14110 // FIXME: Is the expansion actually better than scalar code? It doesn't seem so.
14111 // TODO: It is possible to support ZExt by zeroing the undef values during
14112 // the shuffle phase or after the shuffle.
14113 static SDValue LowerExtendedLoad(SDValue Op, const X86Subtarget *Subtarget,
14114                                  SelectionDAG &DAG) {
14115   MVT RegVT = Op.getSimpleValueType();
14116   assert(RegVT.isVector() && "We only custom lower vector sext loads.");
14117   assert(RegVT.isInteger() &&
14118          "We only custom lower integer vector sext loads.");
14119
14120   // Nothing useful we can do without SSE2 shuffles.
14121   assert(Subtarget->hasSSE2() && "We only custom lower sext loads with SSE2.");
14122
14123   LoadSDNode *Ld = cast<LoadSDNode>(Op.getNode());
14124   SDLoc dl(Ld);
14125   EVT MemVT = Ld->getMemoryVT();
14126   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14127   unsigned RegSz = RegVT.getSizeInBits();
14128
14129   ISD::LoadExtType Ext = Ld->getExtensionType();
14130
14131   assert((Ext == ISD::EXTLOAD || Ext == ISD::SEXTLOAD)
14132          && "Only anyext and sext are currently implemented.");
14133   assert(MemVT != RegVT && "Cannot extend to the same type");
14134   assert(MemVT.isVector() && "Must load a vector from memory");
14135
14136   unsigned NumElems = RegVT.getVectorNumElements();
14137   unsigned MemSz = MemVT.getSizeInBits();
14138   assert(RegSz > MemSz && "Register size must be greater than the mem size");
14139
14140   if (Ext == ISD::SEXTLOAD && RegSz == 256 && !Subtarget->hasInt256()) {
14141     // The only way in which we have a legal 256-bit vector result but not the
14142     // integer 256-bit operations needed to directly lower a sextload is if we
14143     // have AVX1 but not AVX2. In that case, we can always emit a sextload to
14144     // a 128-bit vector and a normal sign_extend to 256-bits that should get
14145     // correctly legalized. We do this late to allow the canonical form of
14146     // sextload to persist throughout the rest of the DAG combiner -- it wants
14147     // to fold together any extensions it can, and so will fuse a sign_extend
14148     // of an sextload into a sextload targeting a wider value.
14149     SDValue Load;
14150     if (MemSz == 128) {
14151       // Just switch this to a normal load.
14152       assert(TLI.isTypeLegal(MemVT) && "If the memory type is a 128-bit type, "
14153                                        "it must be a legal 128-bit vector "
14154                                        "type!");
14155       Load = DAG.getLoad(MemVT, dl, Ld->getChain(), Ld->getBasePtr(),
14156                   Ld->getPointerInfo(), Ld->isVolatile(), Ld->isNonTemporal(),
14157                   Ld->isInvariant(), Ld->getAlignment());
14158     } else {
14159       assert(MemSz < 128 &&
14160              "Can't extend a type wider than 128 bits to a 256 bit vector!");
14161       // Do an sext load to a 128-bit vector type. We want to use the same
14162       // number of elements, but elements half as wide. This will end up being
14163       // recursively lowered by this routine, but will succeed as we definitely
14164       // have all the necessary features if we're using AVX1.
14165       EVT HalfEltVT =
14166           EVT::getIntegerVT(*DAG.getContext(), RegVT.getScalarSizeInBits() / 2);
14167       EVT HalfVecVT = EVT::getVectorVT(*DAG.getContext(), HalfEltVT, NumElems);
14168       Load =
14169           DAG.getExtLoad(Ext, dl, HalfVecVT, Ld->getChain(), Ld->getBasePtr(),
14170                          Ld->getPointerInfo(), MemVT, Ld->isVolatile(),
14171                          Ld->isNonTemporal(), Ld->isInvariant(),
14172                          Ld->getAlignment());
14173     }
14174
14175     // Replace chain users with the new chain.
14176     assert(Load->getNumValues() == 2 && "Loads must carry a chain!");
14177     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Load.getValue(1));
14178
14179     // Finally, do a normal sign-extend to the desired register.
14180     return DAG.getSExtOrTrunc(Load, dl, RegVT);
14181   }
14182
14183   // All sizes must be a power of two.
14184   assert(isPowerOf2_32(RegSz * MemSz * NumElems) &&
14185          "Non-power-of-two elements are not custom lowered!");
14186
14187   // Attempt to load the original value using scalar loads.
14188   // Find the largest scalar type that divides the total loaded size.
14189   MVT SclrLoadTy = MVT::i8;
14190   for (MVT Tp : MVT::integer_valuetypes()) {
14191     if (TLI.isTypeLegal(Tp) && ((MemSz % Tp.getSizeInBits()) == 0)) {
14192       SclrLoadTy = Tp;
14193     }
14194   }
14195
14196   // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
14197   if (TLI.isTypeLegal(MVT::f64) && SclrLoadTy.getSizeInBits() < 64 &&
14198       (64 <= MemSz))
14199     SclrLoadTy = MVT::f64;
14200
14201   // Calculate the number of scalar loads that we need to perform
14202   // in order to load our vector from memory.
14203   unsigned NumLoads = MemSz / SclrLoadTy.getSizeInBits();
14204
14205   assert((Ext != ISD::SEXTLOAD || NumLoads == 1) &&
14206          "Can only lower sext loads with a single scalar load!");
14207
14208   unsigned loadRegZize = RegSz;
14209   if (Ext == ISD::SEXTLOAD && RegSz >= 256)
14210     loadRegZize = 128;
14211
14212   // Represent our vector as a sequence of elements which are the
14213   // largest scalar that we can load.
14214   EVT LoadUnitVecVT = EVT::getVectorVT(
14215       *DAG.getContext(), SclrLoadTy, loadRegZize / SclrLoadTy.getSizeInBits());
14216
14217   // Represent the data using the same element type that is stored in
14218   // memory. In practice, we ''widen'' MemVT.
14219   EVT WideVecVT =
14220       EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
14221                        loadRegZize / MemVT.getScalarType().getSizeInBits());
14222
14223   assert(WideVecVT.getSizeInBits() == LoadUnitVecVT.getSizeInBits() &&
14224          "Invalid vector type");
14225
14226   // We can't shuffle using an illegal type.
14227   assert(TLI.isTypeLegal(WideVecVT) &&
14228          "We only lower types that form legal widened vector types");
14229
14230   SmallVector<SDValue, 8> Chains;
14231   SDValue Ptr = Ld->getBasePtr();
14232   SDValue Increment =
14233       DAG.getConstant(SclrLoadTy.getSizeInBits() / 8, dl, TLI.getPointerTy());
14234   SDValue Res = DAG.getUNDEF(LoadUnitVecVT);
14235
14236   for (unsigned i = 0; i < NumLoads; ++i) {
14237     // Perform a single load.
14238     SDValue ScalarLoad =
14239         DAG.getLoad(SclrLoadTy, dl, Ld->getChain(), Ptr, Ld->getPointerInfo(),
14240                     Ld->isVolatile(), Ld->isNonTemporal(), Ld->isInvariant(),
14241                     Ld->getAlignment());
14242     Chains.push_back(ScalarLoad.getValue(1));
14243     // Create the first element type using SCALAR_TO_VECTOR in order to avoid
14244     // another round of DAGCombining.
14245     if (i == 0)
14246       Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, LoadUnitVecVT, ScalarLoad);
14247     else
14248       Res = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, LoadUnitVecVT, Res,
14249                         ScalarLoad, DAG.getIntPtrConstant(i, dl));
14250
14251     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
14252   }
14253
14254   SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
14255
14256   // Bitcast the loaded value to a vector of the original element type, in
14257   // the size of the target vector type.
14258   SDValue SlicedVec = DAG.getBitcast(WideVecVT, Res);
14259   unsigned SizeRatio = RegSz / MemSz;
14260
14261   if (Ext == ISD::SEXTLOAD) {
14262     // If we have SSE4.1, we can directly emit a VSEXT node.
14263     if (Subtarget->hasSSE41()) {
14264       SDValue Sext = DAG.getNode(X86ISD::VSEXT, dl, RegVT, SlicedVec);
14265       DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14266       return Sext;
14267     }
14268
14269     // Otherwise we'll shuffle the small elements in the high bits of the
14270     // larger type and perform an arithmetic shift. If the shift is not legal
14271     // it's better to scalarize.
14272     assert(TLI.isOperationLegalOrCustom(ISD::SRA, RegVT) &&
14273            "We can't implement a sext load without an arithmetic right shift!");
14274
14275     // Redistribute the loaded elements into the different locations.
14276     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14277     for (unsigned i = 0; i != NumElems; ++i)
14278       ShuffleVec[i * SizeRatio + SizeRatio - 1] = i;
14279
14280     SDValue Shuff = DAG.getVectorShuffle(
14281         WideVecVT, dl, SlicedVec, DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14282
14283     Shuff = DAG.getBitcast(RegVT, Shuff);
14284
14285     // Build the arithmetic shift.
14286     unsigned Amt = RegVT.getVectorElementType().getSizeInBits() -
14287                    MemVT.getVectorElementType().getSizeInBits();
14288     Shuff =
14289         DAG.getNode(ISD::SRA, dl, RegVT, Shuff,
14290                     DAG.getConstant(Amt, dl, RegVT));
14291
14292     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14293     return Shuff;
14294   }
14295
14296   // Redistribute the loaded elements into the different locations.
14297   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
14298   for (unsigned i = 0; i != NumElems; ++i)
14299     ShuffleVec[i * SizeRatio] = i;
14300
14301   SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, SlicedVec,
14302                                        DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
14303
14304   // Bitcast to the requested type.
14305   Shuff = DAG.getBitcast(RegVT, Shuff);
14306   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), TF);
14307   return Shuff;
14308 }
14309
14310 // isAndOrOfSingleUseSetCCs - Return true if node is an ISD::AND or
14311 // ISD::OR of two X86ISD::SETCC nodes each of which has no other use apart
14312 // from the AND / OR.
14313 static bool isAndOrOfSetCCs(SDValue Op, unsigned &Opc) {
14314   Opc = Op.getOpcode();
14315   if (Opc != ISD::OR && Opc != ISD::AND)
14316     return false;
14317   return (Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14318           Op.getOperand(0).hasOneUse() &&
14319           Op.getOperand(1).getOpcode() == X86ISD::SETCC &&
14320           Op.getOperand(1).hasOneUse());
14321 }
14322
14323 // isXor1OfSetCC - Return true if node is an ISD::XOR of a X86ISD::SETCC and
14324 // 1 and that the SETCC node has a single use.
14325 static bool isXor1OfSetCC(SDValue Op) {
14326   if (Op.getOpcode() != ISD::XOR)
14327     return false;
14328   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
14329   if (N1C && N1C->getAPIntValue() == 1) {
14330     return Op.getOperand(0).getOpcode() == X86ISD::SETCC &&
14331       Op.getOperand(0).hasOneUse();
14332   }
14333   return false;
14334 }
14335
14336 SDValue X86TargetLowering::LowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
14337   bool addTest = true;
14338   SDValue Chain = Op.getOperand(0);
14339   SDValue Cond  = Op.getOperand(1);
14340   SDValue Dest  = Op.getOperand(2);
14341   SDLoc dl(Op);
14342   SDValue CC;
14343   bool Inverted = false;
14344
14345   if (Cond.getOpcode() == ISD::SETCC) {
14346     // Check for setcc([su]{add,sub,mul}o == 0).
14347     if (cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETEQ &&
14348         isa<ConstantSDNode>(Cond.getOperand(1)) &&
14349         cast<ConstantSDNode>(Cond.getOperand(1))->isNullValue() &&
14350         Cond.getOperand(0).getResNo() == 1 &&
14351         (Cond.getOperand(0).getOpcode() == ISD::SADDO ||
14352          Cond.getOperand(0).getOpcode() == ISD::UADDO ||
14353          Cond.getOperand(0).getOpcode() == ISD::SSUBO ||
14354          Cond.getOperand(0).getOpcode() == ISD::USUBO ||
14355          Cond.getOperand(0).getOpcode() == ISD::SMULO ||
14356          Cond.getOperand(0).getOpcode() == ISD::UMULO)) {
14357       Inverted = true;
14358       Cond = Cond.getOperand(0);
14359     } else {
14360       SDValue NewCond = LowerSETCC(Cond, DAG);
14361       if (NewCond.getNode())
14362         Cond = NewCond;
14363     }
14364   }
14365 #if 0
14366   // FIXME: LowerXALUO doesn't handle these!!
14367   else if (Cond.getOpcode() == X86ISD::ADD  ||
14368            Cond.getOpcode() == X86ISD::SUB  ||
14369            Cond.getOpcode() == X86ISD::SMUL ||
14370            Cond.getOpcode() == X86ISD::UMUL)
14371     Cond = LowerXALUO(Cond, DAG);
14372 #endif
14373
14374   // Look pass (and (setcc_carry (cmp ...)), 1).
14375   if (Cond.getOpcode() == ISD::AND &&
14376       Cond.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY) {
14377     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Cond.getOperand(1));
14378     if (C && C->getAPIntValue() == 1)
14379       Cond = Cond.getOperand(0);
14380   }
14381
14382   // If condition flag is set by a X86ISD::CMP, then use it as the condition
14383   // setting operand in place of the X86ISD::SETCC.
14384   unsigned CondOpcode = Cond.getOpcode();
14385   if (CondOpcode == X86ISD::SETCC ||
14386       CondOpcode == X86ISD::SETCC_CARRY) {
14387     CC = Cond.getOperand(0);
14388
14389     SDValue Cmp = Cond.getOperand(1);
14390     unsigned Opc = Cmp.getOpcode();
14391     // FIXME: WHY THE SPECIAL CASING OF LogicalCmp??
14392     if (isX86LogicalCmp(Cmp) || Opc == X86ISD::BT) {
14393       Cond = Cmp;
14394       addTest = false;
14395     } else {
14396       switch (cast<ConstantSDNode>(CC)->getZExtValue()) {
14397       default: break;
14398       case X86::COND_O:
14399       case X86::COND_B:
14400         // These can only come from an arithmetic instruction with overflow,
14401         // e.g. SADDO, UADDO.
14402         Cond = Cond.getNode()->getOperand(1);
14403         addTest = false;
14404         break;
14405       }
14406     }
14407   }
14408   CondOpcode = Cond.getOpcode();
14409   if (CondOpcode == ISD::UADDO || CondOpcode == ISD::SADDO ||
14410       CondOpcode == ISD::USUBO || CondOpcode == ISD::SSUBO ||
14411       ((CondOpcode == ISD::UMULO || CondOpcode == ISD::SMULO) &&
14412        Cond.getOperand(0).getValueType() != MVT::i8)) {
14413     SDValue LHS = Cond.getOperand(0);
14414     SDValue RHS = Cond.getOperand(1);
14415     unsigned X86Opcode;
14416     unsigned X86Cond;
14417     SDVTList VTs;
14418     // Keep this in sync with LowerXALUO, otherwise we might create redundant
14419     // instructions that can't be removed afterwards (i.e. X86ISD::ADD and
14420     // X86ISD::INC).
14421     switch (CondOpcode) {
14422     case ISD::UADDO: X86Opcode = X86ISD::ADD; X86Cond = X86::COND_B; break;
14423     case ISD::SADDO:
14424       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14425         if (C->isOne()) {
14426           X86Opcode = X86ISD::INC; X86Cond = X86::COND_O;
14427           break;
14428         }
14429       X86Opcode = X86ISD::ADD; X86Cond = X86::COND_O; break;
14430     case ISD::USUBO: X86Opcode = X86ISD::SUB; X86Cond = X86::COND_B; break;
14431     case ISD::SSUBO:
14432       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
14433         if (C->isOne()) {
14434           X86Opcode = X86ISD::DEC; X86Cond = X86::COND_O;
14435           break;
14436         }
14437       X86Opcode = X86ISD::SUB; X86Cond = X86::COND_O; break;
14438     case ISD::UMULO: X86Opcode = X86ISD::UMUL; X86Cond = X86::COND_O; break;
14439     case ISD::SMULO: X86Opcode = X86ISD::SMUL; X86Cond = X86::COND_O; break;
14440     default: llvm_unreachable("unexpected overflowing operator");
14441     }
14442     if (Inverted)
14443       X86Cond = X86::GetOppositeBranchCondition((X86::CondCode)X86Cond);
14444     if (CondOpcode == ISD::UMULO)
14445       VTs = DAG.getVTList(LHS.getValueType(), LHS.getValueType(),
14446                           MVT::i32);
14447     else
14448       VTs = DAG.getVTList(LHS.getValueType(), MVT::i32);
14449
14450     SDValue X86Op = DAG.getNode(X86Opcode, dl, VTs, LHS, RHS);
14451
14452     if (CondOpcode == ISD::UMULO)
14453       Cond = X86Op.getValue(2);
14454     else
14455       Cond = X86Op.getValue(1);
14456
14457     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14458     addTest = false;
14459   } else {
14460     unsigned CondOpc;
14461     if (Cond.hasOneUse() && isAndOrOfSetCCs(Cond, CondOpc)) {
14462       SDValue Cmp = Cond.getOperand(0).getOperand(1);
14463       if (CondOpc == ISD::OR) {
14464         // Also, recognize the pattern generated by an FCMP_UNE. We can emit
14465         // two branches instead of an explicit OR instruction with a
14466         // separate test.
14467         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14468             isX86LogicalCmp(Cmp)) {
14469           CC = Cond.getOperand(0).getOperand(0);
14470           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14471                               Chain, Dest, CC, Cmp);
14472           CC = Cond.getOperand(1).getOperand(0);
14473           Cond = Cmp;
14474           addTest = false;
14475         }
14476       } else { // ISD::AND
14477         // Also, recognize the pattern generated by an FCMP_OEQ. We can emit
14478         // two branches instead of an explicit AND instruction with a
14479         // separate test. However, we only do this if this block doesn't
14480         // have a fall-through edge, because this requires an explicit
14481         // jmp when the condition is false.
14482         if (Cmp == Cond.getOperand(1).getOperand(1) &&
14483             isX86LogicalCmp(Cmp) &&
14484             Op.getNode()->hasOneUse()) {
14485           X86::CondCode CCode =
14486             (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14487           CCode = X86::GetOppositeBranchCondition(CCode);
14488           CC = DAG.getConstant(CCode, dl, MVT::i8);
14489           SDNode *User = *Op.getNode()->use_begin();
14490           // Look for an unconditional branch following this conditional branch.
14491           // We need this because we need to reverse the successors in order
14492           // to implement FCMP_OEQ.
14493           if (User->getOpcode() == ISD::BR) {
14494             SDValue FalseBB = User->getOperand(1);
14495             SDNode *NewBR =
14496               DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14497             assert(NewBR == User);
14498             (void)NewBR;
14499             Dest = FalseBB;
14500
14501             Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14502                                 Chain, Dest, CC, Cmp);
14503             X86::CondCode CCode =
14504               (X86::CondCode)Cond.getOperand(1).getConstantOperandVal(0);
14505             CCode = X86::GetOppositeBranchCondition(CCode);
14506             CC = DAG.getConstant(CCode, dl, MVT::i8);
14507             Cond = Cmp;
14508             addTest = false;
14509           }
14510         }
14511       }
14512     } else if (Cond.hasOneUse() && isXor1OfSetCC(Cond)) {
14513       // Recognize for xorb (setcc), 1 patterns. The xor inverts the condition.
14514       // It should be transformed during dag combiner except when the condition
14515       // is set by a arithmetics with overflow node.
14516       X86::CondCode CCode =
14517         (X86::CondCode)Cond.getOperand(0).getConstantOperandVal(0);
14518       CCode = X86::GetOppositeBranchCondition(CCode);
14519       CC = DAG.getConstant(CCode, dl, MVT::i8);
14520       Cond = Cond.getOperand(0).getOperand(1);
14521       addTest = false;
14522     } else if (Cond.getOpcode() == ISD::SETCC &&
14523                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETOEQ) {
14524       // For FCMP_OEQ, we can emit
14525       // two branches instead of an explicit AND instruction with a
14526       // separate test. However, we only do this if this block doesn't
14527       // have a fall-through edge, because this requires an explicit
14528       // jmp when the condition is false.
14529       if (Op.getNode()->hasOneUse()) {
14530         SDNode *User = *Op.getNode()->use_begin();
14531         // Look for an unconditional branch following this conditional branch.
14532         // We need this because we need to reverse the successors in order
14533         // to implement FCMP_OEQ.
14534         if (User->getOpcode() == ISD::BR) {
14535           SDValue FalseBB = User->getOperand(1);
14536           SDNode *NewBR =
14537             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14538           assert(NewBR == User);
14539           (void)NewBR;
14540           Dest = FalseBB;
14541
14542           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14543                                     Cond.getOperand(0), Cond.getOperand(1));
14544           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14545           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14546           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14547                               Chain, Dest, CC, Cmp);
14548           CC = DAG.getConstant(X86::COND_P, dl, MVT::i8);
14549           Cond = Cmp;
14550           addTest = false;
14551         }
14552       }
14553     } else if (Cond.getOpcode() == ISD::SETCC &&
14554                cast<CondCodeSDNode>(Cond.getOperand(2))->get() == ISD::SETUNE) {
14555       // For FCMP_UNE, we can emit
14556       // two branches instead of an explicit AND instruction with a
14557       // separate test. However, we only do this if this block doesn't
14558       // have a fall-through edge, because this requires an explicit
14559       // jmp when the condition is false.
14560       if (Op.getNode()->hasOneUse()) {
14561         SDNode *User = *Op.getNode()->use_begin();
14562         // Look for an unconditional branch following this conditional branch.
14563         // We need this because we need to reverse the successors in order
14564         // to implement FCMP_UNE.
14565         if (User->getOpcode() == ISD::BR) {
14566           SDValue FalseBB = User->getOperand(1);
14567           SDNode *NewBR =
14568             DAG.UpdateNodeOperands(User, User->getOperand(0), Dest);
14569           assert(NewBR == User);
14570           (void)NewBR;
14571
14572           SDValue Cmp = DAG.getNode(X86ISD::CMP, dl, MVT::i32,
14573                                     Cond.getOperand(0), Cond.getOperand(1));
14574           Cmp = ConvertCmpIfNecessary(Cmp, DAG);
14575           CC = DAG.getConstant(X86::COND_NE, dl, MVT::i8);
14576           Chain = DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14577                               Chain, Dest, CC, Cmp);
14578           CC = DAG.getConstant(X86::COND_NP, dl, MVT::i8);
14579           Cond = Cmp;
14580           addTest = false;
14581           Dest = FalseBB;
14582         }
14583       }
14584     }
14585   }
14586
14587   if (addTest) {
14588     // Look pass the truncate if the high bits are known zero.
14589     if (isTruncWithZeroHighBitsInput(Cond, DAG))
14590         Cond = Cond.getOperand(0);
14591
14592     // We know the result of AND is compared against zero. Try to match
14593     // it to BT.
14594     if (Cond.getOpcode() == ISD::AND && Cond.hasOneUse()) {
14595       SDValue NewSetCC = LowerToBT(Cond, ISD::SETNE, dl, DAG);
14596       if (NewSetCC.getNode()) {
14597         CC = NewSetCC.getOperand(0);
14598         Cond = NewSetCC.getOperand(1);
14599         addTest = false;
14600       }
14601     }
14602   }
14603
14604   if (addTest) {
14605     X86::CondCode X86Cond = Inverted ? X86::COND_E : X86::COND_NE;
14606     CC = DAG.getConstant(X86Cond, dl, MVT::i8);
14607     Cond = EmitTest(Cond, X86Cond, dl, DAG);
14608   }
14609   Cond = ConvertCmpIfNecessary(Cond, DAG);
14610   return DAG.getNode(X86ISD::BRCOND, dl, Op.getValueType(),
14611                      Chain, Dest, CC, Cond);
14612 }
14613
14614 // Lower dynamic stack allocation to _alloca call for Cygwin/Mingw targets.
14615 // Calls to _alloca are needed to probe the stack when allocating more than 4k
14616 // bytes in one go. Touching the stack at 4K increments is necessary to ensure
14617 // that the guard pages used by the OS virtual memory manager are allocated in
14618 // correct sequence.
14619 SDValue
14620 X86TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
14621                                            SelectionDAG &DAG) const {
14622   MachineFunction &MF = DAG.getMachineFunction();
14623   bool SplitStack = MF.shouldSplitStack();
14624   bool Lower = (Subtarget->isOSWindows() && !Subtarget->isTargetMachO()) ||
14625                SplitStack;
14626   SDLoc dl(Op);
14627
14628   if (!Lower) {
14629     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
14630     SDNode* Node = Op.getNode();
14631
14632     unsigned SPReg = TLI.getStackPointerRegisterToSaveRestore();
14633     assert(SPReg && "Target cannot require DYNAMIC_STACKALLOC expansion and"
14634         " not tell us which reg is the stack pointer!");
14635     EVT VT = Node->getValueType(0);
14636     SDValue Tmp1 = SDValue(Node, 0);
14637     SDValue Tmp2 = SDValue(Node, 1);
14638     SDValue Tmp3 = Node->getOperand(2);
14639     SDValue Chain = Tmp1.getOperand(0);
14640
14641     // Chain the dynamic stack allocation so that it doesn't modify the stack
14642     // pointer when other instructions are using the stack.
14643     Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(0, dl, true),
14644         SDLoc(Node));
14645
14646     SDValue Size = Tmp2.getOperand(1);
14647     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, VT);
14648     Chain = SP.getValue(1);
14649     unsigned Align = cast<ConstantSDNode>(Tmp3)->getZExtValue();
14650     const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
14651     unsigned StackAlign = TFI.getStackAlignment();
14652     Tmp1 = DAG.getNode(ISD::SUB, dl, VT, SP, Size); // Value
14653     if (Align > StackAlign)
14654       Tmp1 = DAG.getNode(ISD::AND, dl, VT, Tmp1,
14655           DAG.getConstant(-(uint64_t)Align, dl, VT));
14656     Chain = DAG.getCopyToReg(Chain, dl, SPReg, Tmp1); // Output chain
14657
14658     Tmp2 = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
14659         DAG.getIntPtrConstant(0, dl, true), SDValue(),
14660         SDLoc(Node));
14661
14662     SDValue Ops[2] = { Tmp1, Tmp2 };
14663     return DAG.getMergeValues(Ops, dl);
14664   }
14665
14666   // Get the inputs.
14667   SDValue Chain = Op.getOperand(0);
14668   SDValue Size  = Op.getOperand(1);
14669   unsigned Align = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
14670   EVT VT = Op.getNode()->getValueType(0);
14671
14672   bool Is64Bit = Subtarget->is64Bit();
14673   EVT SPTy = getPointerTy();
14674
14675   if (SplitStack) {
14676     MachineRegisterInfo &MRI = MF.getRegInfo();
14677
14678     if (Is64Bit) {
14679       // The 64 bit implementation of segmented stacks needs to clobber both r10
14680       // r11. This makes it impossible to use it along with nested parameters.
14681       const Function *F = MF.getFunction();
14682
14683       for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
14684            I != E; ++I)
14685         if (I->hasNestAttr())
14686           report_fatal_error("Cannot use segmented stacks with functions that "
14687                              "have nested arguments.");
14688     }
14689
14690     const TargetRegisterClass *AddrRegClass =
14691       getRegClassFor(getPointerTy());
14692     unsigned Vreg = MRI.createVirtualRegister(AddrRegClass);
14693     Chain = DAG.getCopyToReg(Chain, dl, Vreg, Size);
14694     SDValue Value = DAG.getNode(X86ISD::SEG_ALLOCA, dl, SPTy, Chain,
14695                                 DAG.getRegister(Vreg, SPTy));
14696     SDValue Ops1[2] = { Value, Chain };
14697     return DAG.getMergeValues(Ops1, dl);
14698   } else {
14699     SDValue Flag;
14700     const unsigned Reg = (Subtarget->isTarget64BitLP64() ? X86::RAX : X86::EAX);
14701
14702     Chain = DAG.getCopyToReg(Chain, dl, Reg, Size, Flag);
14703     Flag = Chain.getValue(1);
14704     SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
14705
14706     Chain = DAG.getNode(X86ISD::WIN_ALLOCA, dl, NodeTys, Chain, Flag);
14707
14708     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
14709     unsigned SPReg = RegInfo->getStackRegister();
14710     SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, SPTy);
14711     Chain = SP.getValue(1);
14712
14713     if (Align) {
14714       SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
14715                        DAG.getConstant(-(uint64_t)Align, dl, VT));
14716       Chain = DAG.getCopyToReg(Chain, dl, SPReg, SP);
14717     }
14718
14719     SDValue Ops1[2] = { SP, Chain };
14720     return DAG.getMergeValues(Ops1, dl);
14721   }
14722 }
14723
14724 SDValue X86TargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
14725   MachineFunction &MF = DAG.getMachineFunction();
14726   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
14727
14728   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14729   SDLoc DL(Op);
14730
14731   if (!Subtarget->is64Bit() || Subtarget->isTargetWin64()) {
14732     // vastart just stores the address of the VarArgsFrameIndex slot into the
14733     // memory location argument.
14734     SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14735                                    getPointerTy());
14736     return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
14737                         MachinePointerInfo(SV), false, false, 0);
14738   }
14739
14740   // __va_list_tag:
14741   //   gp_offset         (0 - 6 * 8)
14742   //   fp_offset         (48 - 48 + 8 * 16)
14743   //   overflow_arg_area (point to parameters coming in memory).
14744   //   reg_save_area
14745   SmallVector<SDValue, 8> MemOps;
14746   SDValue FIN = Op.getOperand(1);
14747   // Store gp_offset
14748   SDValue Store = DAG.getStore(Op.getOperand(0), DL,
14749                                DAG.getConstant(FuncInfo->getVarArgsGPOffset(),
14750                                                DL, MVT::i32),
14751                                FIN, MachinePointerInfo(SV), false, false, 0);
14752   MemOps.push_back(Store);
14753
14754   // Store fp_offset
14755   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14756                     FIN, DAG.getIntPtrConstant(4, DL));
14757   Store = DAG.getStore(Op.getOperand(0), DL,
14758                        DAG.getConstant(FuncInfo->getVarArgsFPOffset(), DL,
14759                                        MVT::i32),
14760                        FIN, MachinePointerInfo(SV, 4), false, false, 0);
14761   MemOps.push_back(Store);
14762
14763   // Store ptr to overflow_arg_area
14764   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14765                     FIN, DAG.getIntPtrConstant(4, DL));
14766   SDValue OVFIN = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
14767                                     getPointerTy());
14768   Store = DAG.getStore(Op.getOperand(0), DL, OVFIN, FIN,
14769                        MachinePointerInfo(SV, 8),
14770                        false, false, 0);
14771   MemOps.push_back(Store);
14772
14773   // Store ptr to reg_save_area.
14774   FIN = DAG.getNode(ISD::ADD, DL, getPointerTy(),
14775                     FIN, DAG.getIntPtrConstant(8, DL));
14776   SDValue RSFIN = DAG.getFrameIndex(FuncInfo->getRegSaveFrameIndex(),
14777                                     getPointerTy());
14778   Store = DAG.getStore(Op.getOperand(0), DL, RSFIN, FIN,
14779                        MachinePointerInfo(SV, 16), false, false, 0);
14780   MemOps.push_back(Store);
14781   return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
14782 }
14783
14784 SDValue X86TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
14785   assert(Subtarget->is64Bit() &&
14786          "LowerVAARG only handles 64-bit va_arg!");
14787   assert((Subtarget->isTargetLinux() ||
14788           Subtarget->isTargetDarwin()) &&
14789           "Unhandled target in LowerVAARG");
14790   assert(Op.getNode()->getNumOperands() == 4);
14791   SDValue Chain = Op.getOperand(0);
14792   SDValue SrcPtr = Op.getOperand(1);
14793   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
14794   unsigned Align = Op.getConstantOperandVal(3);
14795   SDLoc dl(Op);
14796
14797   EVT ArgVT = Op.getNode()->getValueType(0);
14798   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
14799   uint32_t ArgSize = getDataLayout()->getTypeAllocSize(ArgTy);
14800   uint8_t ArgMode;
14801
14802   // Decide which area this value should be read from.
14803   // TODO: Implement the AMD64 ABI in its entirety. This simple
14804   // selection mechanism works only for the basic types.
14805   if (ArgVT == MVT::f80) {
14806     llvm_unreachable("va_arg for f80 not yet implemented");
14807   } else if (ArgVT.isFloatingPoint() && ArgSize <= 16 /*bytes*/) {
14808     ArgMode = 2;  // Argument passed in XMM register. Use fp_offset.
14809   } else if (ArgVT.isInteger() && ArgSize <= 32 /*bytes*/) {
14810     ArgMode = 1;  // Argument passed in GPR64 register(s). Use gp_offset.
14811   } else {
14812     llvm_unreachable("Unhandled argument type in LowerVAARG");
14813   }
14814
14815   if (ArgMode == 2) {
14816     // Sanity Check: Make sure using fp_offset makes sense.
14817     assert(!Subtarget->useSoftFloat() &&
14818            !(DAG.getMachineFunction().getFunction()->hasFnAttribute(
14819                Attribute::NoImplicitFloat)) &&
14820            Subtarget->hasSSE1());
14821   }
14822
14823   // Insert VAARG_64 node into the DAG
14824   // VAARG_64 returns two values: Variable Argument Address, Chain
14825   SDValue InstOps[] = {Chain, SrcPtr, DAG.getConstant(ArgSize, dl, MVT::i32),
14826                        DAG.getConstant(ArgMode, dl, MVT::i8),
14827                        DAG.getConstant(Align, dl, MVT::i32)};
14828   SDVTList VTs = DAG.getVTList(getPointerTy(), MVT::Other);
14829   SDValue VAARG = DAG.getMemIntrinsicNode(X86ISD::VAARG_64, dl,
14830                                           VTs, InstOps, MVT::i64,
14831                                           MachinePointerInfo(SV),
14832                                           /*Align=*/0,
14833                                           /*Volatile=*/false,
14834                                           /*ReadMem=*/true,
14835                                           /*WriteMem=*/true);
14836   Chain = VAARG.getValue(1);
14837
14838   // Load the next argument and return it
14839   return DAG.getLoad(ArgVT, dl,
14840                      Chain,
14841                      VAARG,
14842                      MachinePointerInfo(),
14843                      false, false, false, 0);
14844 }
14845
14846 static SDValue LowerVACOPY(SDValue Op, const X86Subtarget *Subtarget,
14847                            SelectionDAG &DAG) {
14848   // X86-64 va_list is a struct { i32, i32, i8*, i8* }.
14849   assert(Subtarget->is64Bit() && "This code only handles 64-bit va_copy!");
14850   SDValue Chain = Op.getOperand(0);
14851   SDValue DstPtr = Op.getOperand(1);
14852   SDValue SrcPtr = Op.getOperand(2);
14853   const Value *DstSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
14854   const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
14855   SDLoc DL(Op);
14856
14857   return DAG.getMemcpy(Chain, DL, DstPtr, SrcPtr,
14858                        DAG.getIntPtrConstant(24, DL), 8, /*isVolatile*/false,
14859                        false, false,
14860                        MachinePointerInfo(DstSV), MachinePointerInfo(SrcSV));
14861 }
14862
14863 // getTargetVShiftByConstNode - Handle vector element shifts where the shift
14864 // amount is a constant. Takes immediate version of shift as input.
14865 static SDValue getTargetVShiftByConstNode(unsigned Opc, SDLoc dl, MVT VT,
14866                                           SDValue SrcOp, uint64_t ShiftAmt,
14867                                           SelectionDAG &DAG) {
14868   MVT ElementType = VT.getVectorElementType();
14869
14870   // Fold this packed shift into its first operand if ShiftAmt is 0.
14871   if (ShiftAmt == 0)
14872     return SrcOp;
14873
14874   // Check for ShiftAmt >= element width
14875   if (ShiftAmt >= ElementType.getSizeInBits()) {
14876     if (Opc == X86ISD::VSRAI)
14877       ShiftAmt = ElementType.getSizeInBits() - 1;
14878     else
14879       return DAG.getConstant(0, dl, VT);
14880   }
14881
14882   assert((Opc == X86ISD::VSHLI || Opc == X86ISD::VSRLI || Opc == X86ISD::VSRAI)
14883          && "Unknown target vector shift-by-constant node");
14884
14885   // Fold this packed vector shift into a build vector if SrcOp is a
14886   // vector of Constants or UNDEFs, and SrcOp valuetype is the same as VT.
14887   if (VT == SrcOp.getSimpleValueType() &&
14888       ISD::isBuildVectorOfConstantSDNodes(SrcOp.getNode())) {
14889     SmallVector<SDValue, 8> Elts;
14890     unsigned NumElts = SrcOp->getNumOperands();
14891     ConstantSDNode *ND;
14892
14893     switch(Opc) {
14894     default: llvm_unreachable(nullptr);
14895     case X86ISD::VSHLI:
14896       for (unsigned i=0; i!=NumElts; ++i) {
14897         SDValue CurrentOp = SrcOp->getOperand(i);
14898         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14899           Elts.push_back(CurrentOp);
14900           continue;
14901         }
14902         ND = cast<ConstantSDNode>(CurrentOp);
14903         const APInt &C = ND->getAPIntValue();
14904         Elts.push_back(DAG.getConstant(C.shl(ShiftAmt), dl, ElementType));
14905       }
14906       break;
14907     case X86ISD::VSRLI:
14908       for (unsigned i=0; i!=NumElts; ++i) {
14909         SDValue CurrentOp = SrcOp->getOperand(i);
14910         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14911           Elts.push_back(CurrentOp);
14912           continue;
14913         }
14914         ND = cast<ConstantSDNode>(CurrentOp);
14915         const APInt &C = ND->getAPIntValue();
14916         Elts.push_back(DAG.getConstant(C.lshr(ShiftAmt), dl, ElementType));
14917       }
14918       break;
14919     case X86ISD::VSRAI:
14920       for (unsigned i=0; i!=NumElts; ++i) {
14921         SDValue CurrentOp = SrcOp->getOperand(i);
14922         if (CurrentOp->getOpcode() == ISD::UNDEF) {
14923           Elts.push_back(CurrentOp);
14924           continue;
14925         }
14926         ND = cast<ConstantSDNode>(CurrentOp);
14927         const APInt &C = ND->getAPIntValue();
14928         Elts.push_back(DAG.getConstant(C.ashr(ShiftAmt), dl, ElementType));
14929       }
14930       break;
14931     }
14932
14933     return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
14934   }
14935
14936   return DAG.getNode(Opc, dl, VT, SrcOp,
14937                      DAG.getConstant(ShiftAmt, dl, MVT::i8));
14938 }
14939
14940 // getTargetVShiftNode - Handle vector element shifts where the shift amount
14941 // may or may not be a constant. Takes immediate version of shift as input.
14942 static SDValue getTargetVShiftNode(unsigned Opc, SDLoc dl, MVT VT,
14943                                    SDValue SrcOp, SDValue ShAmt,
14944                                    SelectionDAG &DAG) {
14945   MVT SVT = ShAmt.getSimpleValueType();
14946   assert((SVT == MVT::i32 || SVT == MVT::i64) && "Unexpected value type!");
14947
14948   // Catch shift-by-constant.
14949   if (ConstantSDNode *CShAmt = dyn_cast<ConstantSDNode>(ShAmt))
14950     return getTargetVShiftByConstNode(Opc, dl, VT, SrcOp,
14951                                       CShAmt->getZExtValue(), DAG);
14952
14953   // Change opcode to non-immediate version
14954   switch (Opc) {
14955     default: llvm_unreachable("Unknown target vector shift node");
14956     case X86ISD::VSHLI: Opc = X86ISD::VSHL; break;
14957     case X86ISD::VSRLI: Opc = X86ISD::VSRL; break;
14958     case X86ISD::VSRAI: Opc = X86ISD::VSRA; break;
14959   }
14960
14961   const X86Subtarget &Subtarget =
14962       static_cast<const X86Subtarget &>(DAG.getSubtarget());
14963   if (Subtarget.hasSSE41() && ShAmt.getOpcode() == ISD::ZERO_EXTEND &&
14964       ShAmt.getOperand(0).getSimpleValueType() == MVT::i16) {
14965     // Let the shuffle legalizer expand this shift amount node.
14966     SDValue Op0 = ShAmt.getOperand(0);
14967     Op0 = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(Op0), MVT::v8i16, Op0);
14968     ShAmt = getShuffleVectorZeroOrUndef(Op0, 0, true, &Subtarget, DAG);
14969   } else {
14970     // Need to build a vector containing shift amount.
14971     // SSE/AVX packed shifts only use the lower 64-bit of the shift count.
14972     SmallVector<SDValue, 4> ShOps;
14973     ShOps.push_back(ShAmt);
14974     if (SVT == MVT::i32) {
14975       ShOps.push_back(DAG.getConstant(0, dl, SVT));
14976       ShOps.push_back(DAG.getUNDEF(SVT));
14977     }
14978     ShOps.push_back(DAG.getUNDEF(SVT));
14979
14980     MVT BVT = SVT == MVT::i32 ? MVT::v4i32 : MVT::v2i64;
14981     ShAmt = DAG.getNode(ISD::BUILD_VECTOR, dl, BVT, ShOps);
14982   }
14983
14984   // The return type has to be a 128-bit type with the same element
14985   // type as the input type.
14986   MVT EltVT = VT.getVectorElementType();
14987   EVT ShVT = MVT::getVectorVT(EltVT, 128/EltVT.getSizeInBits());
14988
14989   ShAmt = DAG.getBitcast(ShVT, ShAmt);
14990   return DAG.getNode(Opc, dl, VT, SrcOp, ShAmt);
14991 }
14992
14993 /// \brief Return (and \p Op, \p Mask) for compare instructions or
14994 /// (vselect \p Mask, \p Op, \p PreservedSrc) for others along with the
14995 /// necessary casting for \p Mask when lowering masking intrinsics.
14996 static SDValue getVectorMaskingNode(SDValue Op, SDValue Mask,
14997                                     SDValue PreservedSrc,
14998                                     const X86Subtarget *Subtarget,
14999                                     SelectionDAG &DAG) {
15000     EVT VT = Op.getValueType();
15001     EVT MaskVT = EVT::getVectorVT(*DAG.getContext(),
15002                                   MVT::i1, VT.getVectorNumElements());
15003     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15004                                      Mask.getValueType().getSizeInBits());
15005     SDLoc dl(Op);
15006
15007     assert(MaskVT.isSimple() && "invalid mask type");
15008
15009     if (isAllOnes(Mask))
15010       return Op;
15011
15012     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15013     // are extracted by EXTRACT_SUBVECTOR.
15014     SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15015                                 DAG.getBitcast(BitcastVT, Mask),
15016                                 DAG.getIntPtrConstant(0, dl));
15017
15018     switch (Op.getOpcode()) {
15019       default: break;
15020       case X86ISD::PCMPEQM:
15021       case X86ISD::PCMPGTM:
15022       case X86ISD::CMPM:
15023       case X86ISD::CMPMU:
15024         return DAG.getNode(ISD::AND, dl, VT, Op, VMask);
15025     }
15026     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15027       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15028     return DAG.getNode(ISD::VSELECT, dl, VT, VMask, Op, PreservedSrc);
15029 }
15030
15031 /// \brief Creates an SDNode for a predicated scalar operation.
15032 /// \returns (X86vselect \p Mask, \p Op, \p PreservedSrc).
15033 /// The mask is comming as MVT::i8 and it should be truncated
15034 /// to MVT::i1 while lowering masking intrinsics.
15035 /// The main difference between ScalarMaskingNode and VectorMaskingNode is using
15036 /// "X86select" instead of "vselect". We just can't create the "vselect" node for
15037 /// a scalar instruction.
15038 static SDValue getScalarMaskingNode(SDValue Op, SDValue Mask,
15039                                     SDValue PreservedSrc,
15040                                     const X86Subtarget *Subtarget,
15041                                     SelectionDAG &DAG) {
15042     if (isAllOnes(Mask))
15043       return Op;
15044
15045     EVT VT = Op.getValueType();
15046     SDLoc dl(Op);
15047     // The mask should be of type MVT::i1
15048     SDValue IMask = DAG.getNode(ISD::TRUNCATE, dl, MVT::i1, Mask);
15049
15050     if (PreservedSrc.getOpcode() == ISD::UNDEF)
15051       PreservedSrc = getZeroVector(VT, Subtarget, DAG, dl);
15052     return DAG.getNode(X86ISD::SELECT, dl, VT, IMask, Op, PreservedSrc);
15053 }
15054
15055 /// When the 32-bit MSVC runtime transfers control to us, either to an outlined
15056 /// function or when returning to a parent frame after catching an exception, we
15057 /// recover the parent frame pointer by doing arithmetic on the incoming EBP.
15058 /// Here's the math:
15059 ///   RegNodeBase = EntryEBP - RegNodeSize
15060 ///   ParentFP = RegNodeBase - RegNodeFrameOffset
15061 /// Subtracting RegNodeSize takes us to the offset of the registration node, and
15062 /// subtracting the offset (negative on x86) takes us back to the parent FP.
15063 static SDValue recoverFramePointer(SelectionDAG &DAG, const Function *Fn,
15064                                    SDValue EntryEBP) {
15065   MachineFunction &MF = DAG.getMachineFunction();
15066   SDLoc dl;
15067
15068   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15069   MVT PtrVT = TLI.getPointerTy();
15070
15071   // It's possible that the parent function no longer has a personality function
15072   // if the exceptional code was optimized away, in which case we just return
15073   // the incoming EBP.
15074   if (!Fn->hasPersonalityFn())
15075     return EntryEBP;
15076
15077   // The RegNodeSize is 6 32-bit words for SEH and 4 for C++ EH. See
15078   // WinEHStatePass for the full struct definition.
15079   int RegNodeSize;
15080   switch (classifyEHPersonality(Fn->getPersonalityFn())) {
15081   default:
15082     report_fatal_error("can only recover FP for MSVC EH personality functions");
15083   case EHPersonality::MSVC_X86SEH: RegNodeSize = 24; break;
15084   case EHPersonality::MSVC_CXX: RegNodeSize = 16; break;
15085   }
15086
15087   // Get an MCSymbol that will ultimately resolve to the frame offset of the EH
15088   // registration.
15089   MCSymbol *OffsetSym =
15090       MF.getMMI().getContext().getOrCreateParentFrameOffsetSymbol(
15091           GlobalValue::getRealLinkageName(Fn->getName()));
15092   SDValue OffsetSymVal = DAG.getMCSymbol(OffsetSym, PtrVT);
15093   SDValue RegNodeFrameOffset =
15094       DAG.getNode(ISD::FRAME_ALLOC_RECOVER, dl, PtrVT, OffsetSymVal);
15095
15096   // RegNodeBase = EntryEBP - RegNodeSize
15097   // ParentFP = RegNodeBase - RegNodeFrameOffset
15098   SDValue RegNodeBase = DAG.getNode(ISD::SUB, dl, PtrVT, EntryEBP,
15099                                     DAG.getConstant(RegNodeSize, dl, PtrVT));
15100   return DAG.getNode(ISD::SUB, dl, PtrVT, RegNodeBase, RegNodeFrameOffset);
15101 }
15102
15103 static SDValue LowerINTRINSIC_WO_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15104                                        SelectionDAG &DAG) {
15105   SDLoc dl(Op);
15106   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15107   EVT VT = Op.getValueType();
15108   const IntrinsicData* IntrData = getIntrinsicWithoutChain(IntNo);
15109   if (IntrData) {
15110     switch(IntrData->Type) {
15111     case INTR_TYPE_1OP:
15112       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1));
15113     case INTR_TYPE_2OP:
15114       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15115         Op.getOperand(2));
15116     case INTR_TYPE_3OP:
15117       return DAG.getNode(IntrData->Opc0, dl, Op.getValueType(), Op.getOperand(1),
15118         Op.getOperand(2), Op.getOperand(3));
15119     case INTR_TYPE_1OP_MASK_RM: {
15120       SDValue Src = Op.getOperand(1);
15121       SDValue PassThru = Op.getOperand(2);
15122       SDValue Mask = Op.getOperand(3);
15123       SDValue RoundingMode;
15124       if (Op.getNumOperands() == 4)
15125         RoundingMode = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15126       else
15127         RoundingMode = Op.getOperand(4);
15128       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15129       if (IntrWithRoundingModeOpcode != 0) {
15130         unsigned Round = cast<ConstantSDNode>(RoundingMode)->getZExtValue();
15131         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION)
15132           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15133                                       dl, Op.getValueType(), Src, RoundingMode),
15134                                       Mask, PassThru, Subtarget, DAG);
15135       }
15136       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src,
15137                                               RoundingMode),
15138                                   Mask, PassThru, Subtarget, DAG);
15139     }
15140     case INTR_TYPE_1OP_MASK: {
15141       SDValue Src = Op.getOperand(1);
15142       SDValue Passthru = Op.getOperand(2);
15143       SDValue Mask = Op.getOperand(3);
15144       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src),
15145                                   Mask, Passthru, Subtarget, DAG);
15146     }
15147     case INTR_TYPE_SCALAR_MASK_RM: {
15148       SDValue Src1 = Op.getOperand(1);
15149       SDValue Src2 = Op.getOperand(2);
15150       SDValue Src0 = Op.getOperand(3);
15151       SDValue Mask = Op.getOperand(4);
15152       // There are 2 kinds of intrinsics in this group:
15153       // (1) With supress-all-exceptions (sae) or rounding mode- 6 operands
15154       // (2) With rounding mode and sae - 7 operands.
15155       if (Op.getNumOperands() == 6) {
15156         SDValue Sae  = Op.getOperand(5);
15157         unsigned Opc = IntrData->Opc1 ? IntrData->Opc1 : IntrData->Opc0;
15158         return getScalarMaskingNode(DAG.getNode(Opc, dl, VT, Src1, Src2,
15159                                                 Sae),
15160                                     Mask, Src0, Subtarget, DAG);
15161       }
15162       assert(Op.getNumOperands() == 7 && "Unexpected intrinsic form");
15163       SDValue RoundingMode  = Op.getOperand(5);
15164       SDValue Sae  = Op.getOperand(6);
15165       return getScalarMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, Src1, Src2,
15166                                               RoundingMode, Sae),
15167                                   Mask, Src0, Subtarget, DAG);
15168     }
15169     case INTR_TYPE_2OP_MASK: {
15170       SDValue Src1 = Op.getOperand(1);
15171       SDValue Src2 = Op.getOperand(2);
15172       SDValue PassThru = Op.getOperand(3);
15173       SDValue Mask = Op.getOperand(4);
15174       // We specify 2 possible opcodes for intrinsics with rounding modes.
15175       // First, we check if the intrinsic may have non-default rounding mode,
15176       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15177       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15178       if (IntrWithRoundingModeOpcode != 0) {
15179         SDValue Rnd = Op.getOperand(5);
15180         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15181         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15182           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15183                                       dl, Op.getValueType(),
15184                                       Src1, Src2, Rnd),
15185                                       Mask, PassThru, Subtarget, DAG);
15186         }
15187       }
15188       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15189                                               Src1,Src2),
15190                                   Mask, PassThru, Subtarget, DAG);
15191     }
15192     case INTR_TYPE_2OP_MASK_RM: {
15193       SDValue Src1 = Op.getOperand(1);
15194       SDValue Src2 = Op.getOperand(2);
15195       SDValue PassThru = Op.getOperand(3);
15196       SDValue Mask = Op.getOperand(4);
15197       // We specify 2 possible modes for intrinsics, with/without rounding modes.
15198       // First, we check if the intrinsic have rounding mode (6 operands),
15199       // if not, we set rounding mode to "current".
15200       SDValue Rnd;
15201       if (Op.getNumOperands() == 6)
15202         Rnd = Op.getOperand(5);
15203       else 
15204         Rnd = DAG.getConstant(X86::STATIC_ROUNDING::CUR_DIRECTION, dl, MVT::i32);
15205       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15206                                               Src1, Src2, Rnd),
15207                                   Mask, PassThru, Subtarget, DAG);
15208     }
15209     case INTR_TYPE_3OP_MASK: {
15210       SDValue Src1 = Op.getOperand(1);
15211       SDValue Src2 = Op.getOperand(2);
15212       SDValue Src3 = Op.getOperand(3);
15213       SDValue PassThru = Op.getOperand(4);
15214       SDValue Mask = Op.getOperand(5);
15215       // We specify 2 possible opcodes for intrinsics with rounding modes.
15216       // First, we check if the intrinsic may have non-default rounding mode,
15217       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15218       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15219       if (IntrWithRoundingModeOpcode != 0) {
15220         SDValue Rnd = Op.getOperand(6);
15221         unsigned Round = cast<ConstantSDNode>(Rnd)->getZExtValue();
15222         if (Round != X86::STATIC_ROUNDING::CUR_DIRECTION) {
15223           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15224                                       dl, Op.getValueType(),
15225                                       Src1, Src2, Src3, Rnd),
15226                                       Mask, PassThru, Subtarget, DAG);
15227         }
15228       }
15229       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15230                                               Src1, Src2, Src3),
15231                                   Mask, PassThru, Subtarget, DAG);
15232     }
15233     case VPERM_3OP_MASKZ: 
15234     case VPERM_3OP_MASK:
15235     case FMA_OP_MASK3:
15236     case FMA_OP_MASKZ:
15237     case FMA_OP_MASK: {
15238       SDValue Src1 = Op.getOperand(1);
15239       SDValue Src2 = Op.getOperand(2);
15240       SDValue Src3 = Op.getOperand(3);
15241       SDValue Mask = Op.getOperand(4);
15242       EVT VT = Op.getValueType();
15243       SDValue PassThru = SDValue();
15244
15245       // set PassThru element
15246       if (IntrData->Type == VPERM_3OP_MASKZ || IntrData->Type == FMA_OP_MASKZ)
15247         PassThru = getZeroVector(VT, Subtarget, DAG, dl);
15248       else if (IntrData->Type == FMA_OP_MASK3)
15249         PassThru = Src3;
15250       else
15251         PassThru = Src1;
15252
15253       // We specify 2 possible opcodes for intrinsics with rounding modes.
15254       // First, we check if the intrinsic may have non-default rounding mode,
15255       // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15256       unsigned IntrWithRoundingModeOpcode = IntrData->Opc1;
15257       if (IntrWithRoundingModeOpcode != 0) {
15258         SDValue Rnd = Op.getOperand(5);
15259         if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15260             X86::STATIC_ROUNDING::CUR_DIRECTION)
15261           return getVectorMaskingNode(DAG.getNode(IntrWithRoundingModeOpcode,
15262                                                   dl, Op.getValueType(),
15263                                                   Src1, Src2, Src3, Rnd),
15264                                       Mask, PassThru, Subtarget, DAG);
15265       }
15266       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0,
15267                                               dl, Op.getValueType(),
15268                                               Src1, Src2, Src3),
15269                                   Mask, PassThru, Subtarget, DAG);
15270     }
15271     case CMP_MASK:
15272     case CMP_MASK_CC: {
15273       // Comparison intrinsics with masks.
15274       // Example of transformation:
15275       // (i8 (int_x86_avx512_mask_pcmpeq_q_128
15276       //             (v2i64 %a), (v2i64 %b), (i8 %mask))) ->
15277       // (i8 (bitcast
15278       //   (v8i1 (insert_subvector undef,
15279       //           (v2i1 (and (PCMPEQM %a, %b),
15280       //                      (extract_subvector
15281       //                         (v8i1 (bitcast %mask)), 0))), 0))))
15282       EVT VT = Op.getOperand(1).getValueType();
15283       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15284                                     VT.getVectorNumElements());
15285       SDValue Mask = Op.getOperand((IntrData->Type == CMP_MASK_CC) ? 4 : 3);
15286       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15287                                        Mask.getValueType().getSizeInBits());
15288       SDValue Cmp;
15289       if (IntrData->Type == CMP_MASK_CC) {
15290         SDValue CC = Op.getOperand(3);
15291         CC = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, CC);
15292         // We specify 2 possible opcodes for intrinsics with rounding modes.
15293         // First, we check if the intrinsic may have non-default rounding mode,
15294         // (IntrData->Opc1 != 0), then we check the rounding mode operand.
15295         if (IntrData->Opc1 != 0) {
15296           SDValue Rnd = Op.getOperand(5);
15297           if (cast<ConstantSDNode>(Rnd)->getZExtValue() !=
15298               X86::STATIC_ROUNDING::CUR_DIRECTION)
15299             Cmp = DAG.getNode(IntrData->Opc1, dl, MaskVT, Op.getOperand(1),
15300                               Op.getOperand(2), CC, Rnd);
15301         }
15302         //default rounding mode
15303         if(!Cmp.getNode())
15304             Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15305                               Op.getOperand(2), CC);
15306
15307       } else {
15308         assert(IntrData->Type == CMP_MASK && "Unexpected intrinsic type!");
15309         Cmp = DAG.getNode(IntrData->Opc0, dl, MaskVT, Op.getOperand(1),
15310                           Op.getOperand(2));
15311       }
15312       SDValue CmpMask = getVectorMaskingNode(Cmp, Mask,
15313                                              DAG.getTargetConstant(0, dl,
15314                                                                    MaskVT),
15315                                              Subtarget, DAG);
15316       SDValue Res = DAG.getNode(ISD::INSERT_SUBVECTOR, dl, BitcastVT,
15317                                 DAG.getUNDEF(BitcastVT), CmpMask,
15318                                 DAG.getIntPtrConstant(0, dl));
15319       return DAG.getBitcast(Op.getValueType(), Res);
15320     }
15321     case COMI: { // Comparison intrinsics
15322       ISD::CondCode CC = (ISD::CondCode)IntrData->Opc1;
15323       SDValue LHS = Op.getOperand(1);
15324       SDValue RHS = Op.getOperand(2);
15325       unsigned X86CC = TranslateX86CC(CC, dl, true, LHS, RHS, DAG);
15326       assert(X86CC != X86::COND_INVALID && "Unexpected illegal condition!");
15327       SDValue Cond = DAG.getNode(IntrData->Opc0, dl, MVT::i32, LHS, RHS);
15328       SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15329                                   DAG.getConstant(X86CC, dl, MVT::i8), Cond);
15330       return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15331     }
15332     case VSHIFT:
15333       return getTargetVShiftNode(IntrData->Opc0, dl, Op.getSimpleValueType(),
15334                                  Op.getOperand(1), Op.getOperand(2), DAG);
15335     case VSHIFT_MASK:
15336       return getVectorMaskingNode(getTargetVShiftNode(IntrData->Opc0, dl,
15337                                                       Op.getSimpleValueType(),
15338                                                       Op.getOperand(1),
15339                                                       Op.getOperand(2), DAG),
15340                                   Op.getOperand(4), Op.getOperand(3), Subtarget,
15341                                   DAG);
15342     case COMPRESS_EXPAND_IN_REG: {
15343       SDValue Mask = Op.getOperand(3);
15344       SDValue DataToCompress = Op.getOperand(1);
15345       SDValue PassThru = Op.getOperand(2);
15346       if (isAllOnes(Mask)) // return data as is
15347         return Op.getOperand(1);
15348
15349       return getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT,
15350                                               DataToCompress),
15351                                   Mask, PassThru, Subtarget, DAG);
15352     }
15353     case BLEND: {
15354       SDValue Mask = Op.getOperand(3);
15355       EVT VT = Op.getValueType();
15356       EVT MaskVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15357                                     VT.getVectorNumElements());
15358       EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15359                                        Mask.getValueType().getSizeInBits());
15360       SDLoc dl(Op);
15361       SDValue VMask = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15362                                   DAG.getBitcast(BitcastVT, Mask),
15363                                   DAG.getIntPtrConstant(0, dl));
15364       return DAG.getNode(IntrData->Opc0, dl, VT, VMask, Op.getOperand(1),
15365                          Op.getOperand(2));
15366     }
15367     default:
15368       break;
15369     }
15370   }
15371
15372   switch (IntNo) {
15373   default: return SDValue();    // Don't custom lower most intrinsics.
15374
15375   case Intrinsic::x86_avx2_permd:
15376   case Intrinsic::x86_avx2_permps:
15377     // Operands intentionally swapped. Mask is last operand to intrinsic,
15378     // but second operand for node/instruction.
15379     return DAG.getNode(X86ISD::VPERMV, dl, Op.getValueType(),
15380                        Op.getOperand(2), Op.getOperand(1));
15381
15382   // ptest and testp intrinsics. The intrinsic these come from are designed to
15383   // return an integer value, not just an instruction so lower it to the ptest
15384   // or testp pattern and a setcc for the result.
15385   case Intrinsic::x86_sse41_ptestz:
15386   case Intrinsic::x86_sse41_ptestc:
15387   case Intrinsic::x86_sse41_ptestnzc:
15388   case Intrinsic::x86_avx_ptestz_256:
15389   case Intrinsic::x86_avx_ptestc_256:
15390   case Intrinsic::x86_avx_ptestnzc_256:
15391   case Intrinsic::x86_avx_vtestz_ps:
15392   case Intrinsic::x86_avx_vtestc_ps:
15393   case Intrinsic::x86_avx_vtestnzc_ps:
15394   case Intrinsic::x86_avx_vtestz_pd:
15395   case Intrinsic::x86_avx_vtestc_pd:
15396   case Intrinsic::x86_avx_vtestnzc_pd:
15397   case Intrinsic::x86_avx_vtestz_ps_256:
15398   case Intrinsic::x86_avx_vtestc_ps_256:
15399   case Intrinsic::x86_avx_vtestnzc_ps_256:
15400   case Intrinsic::x86_avx_vtestz_pd_256:
15401   case Intrinsic::x86_avx_vtestc_pd_256:
15402   case Intrinsic::x86_avx_vtestnzc_pd_256: {
15403     bool IsTestPacked = false;
15404     unsigned X86CC;
15405     switch (IntNo) {
15406     default: llvm_unreachable("Bad fallthrough in Intrinsic lowering.");
15407     case Intrinsic::x86_avx_vtestz_ps:
15408     case Intrinsic::x86_avx_vtestz_pd:
15409     case Intrinsic::x86_avx_vtestz_ps_256:
15410     case Intrinsic::x86_avx_vtestz_pd_256:
15411       IsTestPacked = true; // Fallthrough
15412     case Intrinsic::x86_sse41_ptestz:
15413     case Intrinsic::x86_avx_ptestz_256:
15414       // ZF = 1
15415       X86CC = X86::COND_E;
15416       break;
15417     case Intrinsic::x86_avx_vtestc_ps:
15418     case Intrinsic::x86_avx_vtestc_pd:
15419     case Intrinsic::x86_avx_vtestc_ps_256:
15420     case Intrinsic::x86_avx_vtestc_pd_256:
15421       IsTestPacked = true; // Fallthrough
15422     case Intrinsic::x86_sse41_ptestc:
15423     case Intrinsic::x86_avx_ptestc_256:
15424       // CF = 1
15425       X86CC = X86::COND_B;
15426       break;
15427     case Intrinsic::x86_avx_vtestnzc_ps:
15428     case Intrinsic::x86_avx_vtestnzc_pd:
15429     case Intrinsic::x86_avx_vtestnzc_ps_256:
15430     case Intrinsic::x86_avx_vtestnzc_pd_256:
15431       IsTestPacked = true; // Fallthrough
15432     case Intrinsic::x86_sse41_ptestnzc:
15433     case Intrinsic::x86_avx_ptestnzc_256:
15434       // ZF and CF = 0
15435       X86CC = X86::COND_A;
15436       break;
15437     }
15438
15439     SDValue LHS = Op.getOperand(1);
15440     SDValue RHS = Op.getOperand(2);
15441     unsigned TestOpc = IsTestPacked ? X86ISD::TESTP : X86ISD::PTEST;
15442     SDValue Test = DAG.getNode(TestOpc, dl, MVT::i32, LHS, RHS);
15443     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15444     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8, CC, Test);
15445     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15446   }
15447   case Intrinsic::x86_avx512_kortestz_w:
15448   case Intrinsic::x86_avx512_kortestc_w: {
15449     unsigned X86CC = (IntNo == Intrinsic::x86_avx512_kortestz_w)? X86::COND_E: X86::COND_B;
15450     SDValue LHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(1));
15451     SDValue RHS = DAG.getBitcast(MVT::v16i1, Op.getOperand(2));
15452     SDValue CC = DAG.getConstant(X86CC, dl, MVT::i8);
15453     SDValue Test = DAG.getNode(X86ISD::KORTEST, dl, MVT::i32, LHS, RHS);
15454     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i1, CC, Test);
15455     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15456   }
15457
15458   case Intrinsic::x86_sse42_pcmpistria128:
15459   case Intrinsic::x86_sse42_pcmpestria128:
15460   case Intrinsic::x86_sse42_pcmpistric128:
15461   case Intrinsic::x86_sse42_pcmpestric128:
15462   case Intrinsic::x86_sse42_pcmpistrio128:
15463   case Intrinsic::x86_sse42_pcmpestrio128:
15464   case Intrinsic::x86_sse42_pcmpistris128:
15465   case Intrinsic::x86_sse42_pcmpestris128:
15466   case Intrinsic::x86_sse42_pcmpistriz128:
15467   case Intrinsic::x86_sse42_pcmpestriz128: {
15468     unsigned Opcode;
15469     unsigned X86CC;
15470     switch (IntNo) {
15471     default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
15472     case Intrinsic::x86_sse42_pcmpistria128:
15473       Opcode = X86ISD::PCMPISTRI;
15474       X86CC = X86::COND_A;
15475       break;
15476     case Intrinsic::x86_sse42_pcmpestria128:
15477       Opcode = X86ISD::PCMPESTRI;
15478       X86CC = X86::COND_A;
15479       break;
15480     case Intrinsic::x86_sse42_pcmpistric128:
15481       Opcode = X86ISD::PCMPISTRI;
15482       X86CC = X86::COND_B;
15483       break;
15484     case Intrinsic::x86_sse42_pcmpestric128:
15485       Opcode = X86ISD::PCMPESTRI;
15486       X86CC = X86::COND_B;
15487       break;
15488     case Intrinsic::x86_sse42_pcmpistrio128:
15489       Opcode = X86ISD::PCMPISTRI;
15490       X86CC = X86::COND_O;
15491       break;
15492     case Intrinsic::x86_sse42_pcmpestrio128:
15493       Opcode = X86ISD::PCMPESTRI;
15494       X86CC = X86::COND_O;
15495       break;
15496     case Intrinsic::x86_sse42_pcmpistris128:
15497       Opcode = X86ISD::PCMPISTRI;
15498       X86CC = X86::COND_S;
15499       break;
15500     case Intrinsic::x86_sse42_pcmpestris128:
15501       Opcode = X86ISD::PCMPESTRI;
15502       X86CC = X86::COND_S;
15503       break;
15504     case Intrinsic::x86_sse42_pcmpistriz128:
15505       Opcode = X86ISD::PCMPISTRI;
15506       X86CC = X86::COND_E;
15507       break;
15508     case Intrinsic::x86_sse42_pcmpestriz128:
15509       Opcode = X86ISD::PCMPESTRI;
15510       X86CC = X86::COND_E;
15511       break;
15512     }
15513     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15514     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15515     SDValue PCMP = DAG.getNode(Opcode, dl, VTs, NewOps);
15516     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15517                                 DAG.getConstant(X86CC, dl, MVT::i8),
15518                                 SDValue(PCMP.getNode(), 1));
15519     return DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, SetCC);
15520   }
15521
15522   case Intrinsic::x86_sse42_pcmpistri128:
15523   case Intrinsic::x86_sse42_pcmpestri128: {
15524     unsigned Opcode;
15525     if (IntNo == Intrinsic::x86_sse42_pcmpistri128)
15526       Opcode = X86ISD::PCMPISTRI;
15527     else
15528       Opcode = X86ISD::PCMPESTRI;
15529
15530     SmallVector<SDValue, 5> NewOps(Op->op_begin()+1, Op->op_end());
15531     SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
15532     return DAG.getNode(Opcode, dl, VTs, NewOps);
15533   }
15534
15535   case Intrinsic::x86_seh_lsda: {
15536     // Compute the symbol for the LSDA. We know it'll get emitted later.
15537     MachineFunction &MF = DAG.getMachineFunction();
15538     SDValue Op1 = Op.getOperand(1);
15539     auto *Fn = cast<Function>(cast<GlobalAddressSDNode>(Op1)->getGlobal());
15540     MCSymbol *LSDASym = MF.getMMI().getContext().getOrCreateLSDASymbol(
15541         GlobalValue::getRealLinkageName(Fn->getName()));
15542
15543     // Generate a simple absolute symbol reference. This intrinsic is only
15544     // supported on 32-bit Windows, which isn't PIC.
15545     SDValue Result = DAG.getMCSymbol(LSDASym, VT);
15546     return DAG.getNode(X86ISD::Wrapper, dl, VT, Result);
15547   }
15548
15549   case Intrinsic::x86_seh_recoverfp: {
15550     SDValue FnOp = Op.getOperand(1);
15551     SDValue IncomingFPOp = Op.getOperand(2);
15552     GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
15553     auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
15554     if (!Fn)
15555       report_fatal_error(
15556           "llvm.x86.seh.recoverfp must take a function as the first argument");
15557     return recoverFramePointer(DAG, Fn, IncomingFPOp);
15558   }
15559   }
15560 }
15561
15562 static SDValue getGatherNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15563                               SDValue Src, SDValue Mask, SDValue Base,
15564                               SDValue Index, SDValue ScaleOp, SDValue Chain,
15565                               const X86Subtarget * Subtarget) {
15566   SDLoc dl(Op);
15567   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15568   if (!C)
15569     llvm_unreachable("Invalid scale type");
15570   unsigned ScaleVal = C->getZExtValue();
15571   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15572     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15573
15574   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15575   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15576                              Index.getSimpleValueType().getVectorNumElements());
15577   SDValue MaskInReg;
15578   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15579   if (MaskC)
15580     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15581   else {
15582     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15583                                      Mask.getValueType().getSizeInBits());
15584
15585     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15586     // are extracted by EXTRACT_SUBVECTOR.
15587     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15588                             DAG.getBitcast(BitcastVT, Mask),
15589                             DAG.getIntPtrConstant(0, dl));
15590   }
15591   SDVTList VTs = DAG.getVTList(Op.getValueType(), MaskVT, MVT::Other);
15592   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15593   SDValue Segment = DAG.getRegister(0, MVT::i32);
15594   if (Src.getOpcode() == ISD::UNDEF)
15595     Src = getZeroVector(Op.getValueType(), Subtarget, DAG, dl);
15596   SDValue Ops[] = {Src, MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15597   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15598   SDValue RetOps[] = { SDValue(Res, 0), SDValue(Res, 2) };
15599   return DAG.getMergeValues(RetOps, dl);
15600 }
15601
15602 static SDValue getScatterNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15603                                SDValue Src, SDValue Mask, SDValue Base,
15604                                SDValue Index, SDValue ScaleOp, SDValue Chain) {
15605   SDLoc dl(Op);
15606   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15607   if (!C)
15608     llvm_unreachable("Invalid scale type");
15609   unsigned ScaleVal = C->getZExtValue();
15610   if (ScaleVal > 2 && ScaleVal != 4 && ScaleVal != 8)
15611     llvm_unreachable("Valid scale values are 1, 2, 4, 8");
15612
15613   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15614   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15615   SDValue Segment = DAG.getRegister(0, MVT::i32);
15616   EVT MaskVT = MVT::getVectorVT(MVT::i1,
15617                              Index.getSimpleValueType().getVectorNumElements());
15618   SDValue MaskInReg;
15619   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15620   if (MaskC)
15621     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15622   else {
15623     EVT BitcastVT = EVT::getVectorVT(*DAG.getContext(), MVT::i1,
15624                                      Mask.getValueType().getSizeInBits());
15625
15626     // In case when MaskVT equals v2i1 or v4i1, low 2 or 4 elements
15627     // are extracted by EXTRACT_SUBVECTOR.
15628     MaskInReg = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, MaskVT,
15629                             DAG.getBitcast(BitcastVT, Mask),
15630                             DAG.getIntPtrConstant(0, dl));
15631   }
15632   SDVTList VTs = DAG.getVTList(MaskVT, MVT::Other);
15633   SDValue Ops[] = {Base, Scale, Index, Disp, Segment, MaskInReg, Src, Chain};
15634   SDNode *Res = DAG.getMachineNode(Opc, dl, VTs, Ops);
15635   return SDValue(Res, 1);
15636 }
15637
15638 static SDValue getPrefetchNode(unsigned Opc, SDValue Op, SelectionDAG &DAG,
15639                                SDValue Mask, SDValue Base, SDValue Index,
15640                                SDValue ScaleOp, SDValue Chain) {
15641   SDLoc dl(Op);
15642   ConstantSDNode *C = dyn_cast<ConstantSDNode>(ScaleOp);
15643   assert(C && "Invalid scale type");
15644   SDValue Scale = DAG.getTargetConstant(C->getZExtValue(), dl, MVT::i8);
15645   SDValue Disp = DAG.getTargetConstant(0, dl, MVT::i32);
15646   SDValue Segment = DAG.getRegister(0, MVT::i32);
15647   EVT MaskVT =
15648     MVT::getVectorVT(MVT::i1, Index.getSimpleValueType().getVectorNumElements());
15649   SDValue MaskInReg;
15650   ConstantSDNode *MaskC = dyn_cast<ConstantSDNode>(Mask);
15651   if (MaskC)
15652     MaskInReg = DAG.getTargetConstant(MaskC->getSExtValue(), dl, MaskVT);
15653   else
15654     MaskInReg = DAG.getBitcast(MaskVT, Mask);
15655   //SDVTList VTs = DAG.getVTList(MVT::Other);
15656   SDValue Ops[] = {MaskInReg, Base, Scale, Index, Disp, Segment, Chain};
15657   SDNode *Res = DAG.getMachineNode(Opc, dl, MVT::Other, Ops);
15658   return SDValue(Res, 0);
15659 }
15660
15661 // getReadPerformanceCounter - Handles the lowering of builtin intrinsics that
15662 // read performance monitor counters (x86_rdpmc).
15663 static void getReadPerformanceCounter(SDNode *N, SDLoc DL,
15664                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15665                               SmallVectorImpl<SDValue> &Results) {
15666   assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15667   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15668   SDValue LO, HI;
15669
15670   // The ECX register is used to select the index of the performance counter
15671   // to read.
15672   SDValue Chain = DAG.getCopyToReg(N->getOperand(0), DL, X86::ECX,
15673                                    N->getOperand(2));
15674   SDValue rd = DAG.getNode(X86ISD::RDPMC_DAG, DL, Tys, Chain);
15675
15676   // Reads the content of a 64-bit performance counter and returns it in the
15677   // registers EDX:EAX.
15678   if (Subtarget->is64Bit()) {
15679     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15680     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15681                             LO.getValue(2));
15682   } else {
15683     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15684     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15685                             LO.getValue(2));
15686   }
15687   Chain = HI.getValue(1);
15688
15689   if (Subtarget->is64Bit()) {
15690     // The EAX register is loaded with the low-order 32 bits. The EDX register
15691     // is loaded with the supported high-order bits of the counter.
15692     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15693                               DAG.getConstant(32, DL, MVT::i8));
15694     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15695     Results.push_back(Chain);
15696     return;
15697   }
15698
15699   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15700   SDValue Ops[] = { LO, HI };
15701   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15702   Results.push_back(Pair);
15703   Results.push_back(Chain);
15704 }
15705
15706 // getReadTimeStampCounter - Handles the lowering of builtin intrinsics that
15707 // read the time stamp counter (x86_rdtsc and x86_rdtscp). This function is
15708 // also used to custom lower READCYCLECOUNTER nodes.
15709 static void getReadTimeStampCounter(SDNode *N, SDLoc DL, unsigned Opcode,
15710                               SelectionDAG &DAG, const X86Subtarget *Subtarget,
15711                               SmallVectorImpl<SDValue> &Results) {
15712   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
15713   SDValue rd = DAG.getNode(Opcode, DL, Tys, N->getOperand(0));
15714   SDValue LO, HI;
15715
15716   // The processor's time-stamp counter (a 64-bit MSR) is stored into the
15717   // EDX:EAX registers. EDX is loaded with the high-order 32 bits of the MSR
15718   // and the EAX register is loaded with the low-order 32 bits.
15719   if (Subtarget->is64Bit()) {
15720     LO = DAG.getCopyFromReg(rd, DL, X86::RAX, MVT::i64, rd.getValue(1));
15721     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::RDX, MVT::i64,
15722                             LO.getValue(2));
15723   } else {
15724     LO = DAG.getCopyFromReg(rd, DL, X86::EAX, MVT::i32, rd.getValue(1));
15725     HI = DAG.getCopyFromReg(LO.getValue(1), DL, X86::EDX, MVT::i32,
15726                             LO.getValue(2));
15727   }
15728   SDValue Chain = HI.getValue(1);
15729
15730   if (Opcode == X86ISD::RDTSCP_DAG) {
15731     assert(N->getNumOperands() == 3 && "Unexpected number of operands!");
15732
15733     // Instruction RDTSCP loads the IA32:TSC_AUX_MSR (address C000_0103H) into
15734     // the ECX register. Add 'ecx' explicitly to the chain.
15735     SDValue ecx = DAG.getCopyFromReg(Chain, DL, X86::ECX, MVT::i32,
15736                                      HI.getValue(2));
15737     // Explicitly store the content of ECX at the location passed in input
15738     // to the 'rdtscp' intrinsic.
15739     Chain = DAG.getStore(ecx.getValue(1), DL, ecx, N->getOperand(2),
15740                          MachinePointerInfo(), false, false, 0);
15741   }
15742
15743   if (Subtarget->is64Bit()) {
15744     // The EDX register is loaded with the high-order 32 bits of the MSR, and
15745     // the EAX register is loaded with the low-order 32 bits.
15746     SDValue Tmp = DAG.getNode(ISD::SHL, DL, MVT::i64, HI,
15747                               DAG.getConstant(32, DL, MVT::i8));
15748     Results.push_back(DAG.getNode(ISD::OR, DL, MVT::i64, LO, Tmp));
15749     Results.push_back(Chain);
15750     return;
15751   }
15752
15753   // Use a buildpair to merge the two 32-bit values into a 64-bit one.
15754   SDValue Ops[] = { LO, HI };
15755   SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, Ops);
15756   Results.push_back(Pair);
15757   Results.push_back(Chain);
15758 }
15759
15760 static SDValue LowerREADCYCLECOUNTER(SDValue Op, const X86Subtarget *Subtarget,
15761                                      SelectionDAG &DAG) {
15762   SmallVector<SDValue, 2> Results;
15763   SDLoc DL(Op);
15764   getReadTimeStampCounter(Op.getNode(), DL, X86ISD::RDTSC_DAG, DAG, Subtarget,
15765                           Results);
15766   return DAG.getMergeValues(Results, DL);
15767 }
15768
15769 static SDValue LowerSEHRESTOREFRAME(SDValue Op, const X86Subtarget *Subtarget,
15770                                     SelectionDAG &DAG) {
15771   MachineFunction &MF = DAG.getMachineFunction();
15772   SDLoc dl(Op);
15773   SDValue Chain = Op.getOperand(0);
15774
15775   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
15776   MVT VT = TLI.getPointerTy();
15777
15778   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15779   unsigned FrameReg =
15780       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
15781   unsigned SPReg = RegInfo->getStackRegister();
15782
15783   // Get incoming EBP.
15784   SDValue IncomingEBP =
15785       DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
15786
15787   // Load [EBP-24] into SP.
15788   SDValue SPAddr =
15789       DAG.getNode(ISD::ADD, dl, VT, IncomingEBP, DAG.getConstant(-24, dl, VT));
15790   SDValue NewSP =
15791       DAG.getLoad(VT, dl, Chain, SPAddr, MachinePointerInfo(), false, false,
15792                   false, VT.getScalarSizeInBits() / 8);
15793   Chain = DAG.getCopyToReg(Chain, dl, SPReg, NewSP);
15794
15795   // FIXME: Restore the base pointer in case of stack realignment!
15796
15797   // Adjust EBP to point back to the original frame position.
15798   SDValue NewFP = recoverFramePointer(DAG, MF.getFunction(), IncomingEBP);
15799   Chain = DAG.getCopyToReg(Chain, dl, FrameReg, NewFP);
15800   return Chain;
15801 }
15802
15803 static SDValue LowerINTRINSIC_W_CHAIN(SDValue Op, const X86Subtarget *Subtarget,
15804                                       SelectionDAG &DAG) {
15805   unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
15806
15807   const IntrinsicData* IntrData = getIntrinsicWithChain(IntNo);
15808   if (!IntrData) {
15809     if (IntNo == llvm::Intrinsic::x86_seh_restoreframe)
15810       return LowerSEHRESTOREFRAME(Op, Subtarget, DAG);
15811     return SDValue();
15812   }
15813
15814   SDLoc dl(Op);
15815   switch(IntrData->Type) {
15816   default:
15817     llvm_unreachable("Unknown Intrinsic Type");
15818     break;
15819   case RDSEED:
15820   case RDRAND: {
15821     // Emit the node with the right value type.
15822     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Glue, MVT::Other);
15823     SDValue Result = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15824
15825     // If the value returned by RDRAND/RDSEED was valid (CF=1), return 1.
15826     // Otherwise return the value from Rand, which is always 0, casted to i32.
15827     SDValue Ops[] = { DAG.getZExtOrTrunc(Result, dl, Op->getValueType(1)),
15828                       DAG.getConstant(1, dl, Op->getValueType(1)),
15829                       DAG.getConstant(X86::COND_B, dl, MVT::i32),
15830                       SDValue(Result.getNode(), 1) };
15831     SDValue isValid = DAG.getNode(X86ISD::CMOV, dl,
15832                                   DAG.getVTList(Op->getValueType(1), MVT::Glue),
15833                                   Ops);
15834
15835     // Return { result, isValid, chain }.
15836     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(), Result, isValid,
15837                        SDValue(Result.getNode(), 2));
15838   }
15839   case GATHER: {
15840   //gather(v1, mask, index, base, scale);
15841     SDValue Chain = Op.getOperand(0);
15842     SDValue Src   = Op.getOperand(2);
15843     SDValue Base  = Op.getOperand(3);
15844     SDValue Index = Op.getOperand(4);
15845     SDValue Mask  = Op.getOperand(5);
15846     SDValue Scale = Op.getOperand(6);
15847     return getGatherNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index, Scale,
15848                          Chain, Subtarget);
15849   }
15850   case SCATTER: {
15851   //scatter(base, mask, index, v1, scale);
15852     SDValue Chain = Op.getOperand(0);
15853     SDValue Base  = Op.getOperand(2);
15854     SDValue Mask  = Op.getOperand(3);
15855     SDValue Index = Op.getOperand(4);
15856     SDValue Src   = Op.getOperand(5);
15857     SDValue Scale = Op.getOperand(6);
15858     return getScatterNode(IntrData->Opc0, Op, DAG, Src, Mask, Base, Index,
15859                           Scale, Chain);
15860   }
15861   case PREFETCH: {
15862     SDValue Hint = Op.getOperand(6);
15863     unsigned HintVal = cast<ConstantSDNode>(Hint)->getZExtValue();
15864     assert(HintVal < 2 && "Wrong prefetch hint in intrinsic: should be 0 or 1");
15865     unsigned Opcode = (HintVal ? IntrData->Opc1 : IntrData->Opc0);
15866     SDValue Chain = Op.getOperand(0);
15867     SDValue Mask  = Op.getOperand(2);
15868     SDValue Index = Op.getOperand(3);
15869     SDValue Base  = Op.getOperand(4);
15870     SDValue Scale = Op.getOperand(5);
15871     return getPrefetchNode(Opcode, Op, DAG, Mask, Base, Index, Scale, Chain);
15872   }
15873   // Read Time Stamp Counter (RDTSC) and Processor ID (RDTSCP).
15874   case RDTSC: {
15875     SmallVector<SDValue, 2> Results;
15876     getReadTimeStampCounter(Op.getNode(), dl, IntrData->Opc0, DAG, Subtarget,
15877                             Results);
15878     return DAG.getMergeValues(Results, dl);
15879   }
15880   // Read Performance Monitoring Counters.
15881   case RDPMC: {
15882     SmallVector<SDValue, 2> Results;
15883     getReadPerformanceCounter(Op.getNode(), dl, DAG, Subtarget, Results);
15884     return DAG.getMergeValues(Results, dl);
15885   }
15886   // XTEST intrinsics.
15887   case XTEST: {
15888     SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15889     SDValue InTrans = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(0));
15890     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15891                                 DAG.getConstant(X86::COND_NE, dl, MVT::i8),
15892                                 InTrans);
15893     SDValue Ret = DAG.getNode(ISD::ZERO_EXTEND, dl, Op->getValueType(0), SetCC);
15894     return DAG.getNode(ISD::MERGE_VALUES, dl, Op->getVTList(),
15895                        Ret, SDValue(InTrans.getNode(), 1));
15896   }
15897   // ADC/ADCX/SBB
15898   case ADX: {
15899     SmallVector<SDValue, 2> Results;
15900     SDVTList CFVTs = DAG.getVTList(Op->getValueType(0), MVT::Other);
15901     SDVTList VTs = DAG.getVTList(Op.getOperand(3)->getValueType(0), MVT::Other);
15902     SDValue GenCF = DAG.getNode(X86ISD::ADD, dl, CFVTs, Op.getOperand(2),
15903                                 DAG.getConstant(-1, dl, MVT::i8));
15904     SDValue Res = DAG.getNode(IntrData->Opc0, dl, VTs, Op.getOperand(3),
15905                               Op.getOperand(4), GenCF.getValue(1));
15906     SDValue Store = DAG.getStore(Op.getOperand(0), dl, Res.getValue(0),
15907                                  Op.getOperand(5), MachinePointerInfo(),
15908                                  false, false, 0);
15909     SDValue SetCC = DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
15910                                 DAG.getConstant(X86::COND_B, dl, MVT::i8),
15911                                 Res.getValue(1));
15912     Results.push_back(SetCC);
15913     Results.push_back(Store);
15914     return DAG.getMergeValues(Results, dl);
15915   }
15916   case COMPRESS_TO_MEM: {
15917     SDLoc dl(Op);
15918     SDValue Mask = Op.getOperand(4);
15919     SDValue DataToCompress = Op.getOperand(3);
15920     SDValue Addr = Op.getOperand(2);
15921     SDValue Chain = Op.getOperand(0);
15922
15923     EVT VT = DataToCompress.getValueType();
15924     if (isAllOnes(Mask)) // return just a store
15925       return DAG.getStore(Chain, dl, DataToCompress, Addr,
15926                           MachinePointerInfo(), false, false,
15927                           VT.getScalarSizeInBits()/8);
15928
15929     SDValue Compressed =
15930       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToCompress),
15931                            Mask, DAG.getUNDEF(VT), Subtarget, DAG);
15932     return DAG.getStore(Chain, dl, Compressed, Addr,
15933                         MachinePointerInfo(), false, false,
15934                         VT.getScalarSizeInBits()/8);
15935   }
15936   case EXPAND_FROM_MEM: {
15937     SDLoc dl(Op);
15938     SDValue Mask = Op.getOperand(4);
15939     SDValue PassThru = Op.getOperand(3);
15940     SDValue Addr = Op.getOperand(2);
15941     SDValue Chain = Op.getOperand(0);
15942     EVT VT = Op.getValueType();
15943
15944     if (isAllOnes(Mask)) // return just a load
15945       return DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(), false, false,
15946                          false, VT.getScalarSizeInBits()/8);
15947
15948     SDValue DataToExpand = DAG.getLoad(VT, dl, Chain, Addr, MachinePointerInfo(),
15949                                        false, false, false,
15950                                        VT.getScalarSizeInBits()/8);
15951
15952     SDValue Results[] = {
15953       getVectorMaskingNode(DAG.getNode(IntrData->Opc0, dl, VT, DataToExpand),
15954                            Mask, PassThru, Subtarget, DAG), Chain};
15955     return DAG.getMergeValues(Results, dl);
15956   }
15957   }
15958 }
15959
15960 SDValue X86TargetLowering::LowerRETURNADDR(SDValue Op,
15961                                            SelectionDAG &DAG) const {
15962   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
15963   MFI->setReturnAddressIsTaken(true);
15964
15965   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
15966     return SDValue();
15967
15968   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
15969   SDLoc dl(Op);
15970   EVT PtrVT = getPointerTy();
15971
15972   if (Depth > 0) {
15973     SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
15974     const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15975     SDValue Offset = DAG.getConstant(RegInfo->getSlotSize(), dl, PtrVT);
15976     return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15977                        DAG.getNode(ISD::ADD, dl, PtrVT,
15978                                    FrameAddr, Offset),
15979                        MachinePointerInfo(), false, false, false, 0);
15980   }
15981
15982   // Just load the return address.
15983   SDValue RetAddrFI = getReturnAddressFrameIndex(DAG);
15984   return DAG.getLoad(PtrVT, dl, DAG.getEntryNode(),
15985                      RetAddrFI, MachinePointerInfo(), false, false, false, 0);
15986 }
15987
15988 SDValue X86TargetLowering::LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
15989   MachineFunction &MF = DAG.getMachineFunction();
15990   MachineFrameInfo *MFI = MF.getFrameInfo();
15991   X86MachineFunctionInfo *FuncInfo = MF.getInfo<X86MachineFunctionInfo>();
15992   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
15993   EVT VT = Op.getValueType();
15994
15995   MFI->setFrameAddressIsTaken(true);
15996
15997   if (MF.getTarget().getMCAsmInfo()->usesWindowsCFI()) {
15998     // Depth > 0 makes no sense on targets which use Windows unwind codes.  It
15999     // is not possible to crawl up the stack without looking at the unwind codes
16000     // simultaneously.
16001     int FrameAddrIndex = FuncInfo->getFAIndex();
16002     if (!FrameAddrIndex) {
16003       // Set up a frame object for the return address.
16004       unsigned SlotSize = RegInfo->getSlotSize();
16005       FrameAddrIndex = MF.getFrameInfo()->CreateFixedObject(
16006           SlotSize, /*Offset=*/0, /*IsImmutable=*/false);
16007       FuncInfo->setFAIndex(FrameAddrIndex);
16008     }
16009     return DAG.getFrameIndex(FrameAddrIndex, VT);
16010   }
16011
16012   unsigned FrameReg =
16013       RegInfo->getPtrSizedFrameRegister(DAG.getMachineFunction());
16014   SDLoc dl(Op);  // FIXME probably not meaningful
16015   unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
16016   assert(((FrameReg == X86::RBP && VT == MVT::i64) ||
16017           (FrameReg == X86::EBP && VT == MVT::i32)) &&
16018          "Invalid Frame Register!");
16019   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
16020   while (Depth--)
16021     FrameAddr = DAG.getLoad(VT, dl, DAG.getEntryNode(), FrameAddr,
16022                             MachinePointerInfo(),
16023                             false, false, false, 0);
16024   return FrameAddr;
16025 }
16026
16027 // FIXME? Maybe this could be a TableGen attribute on some registers and
16028 // this table could be generated automatically from RegInfo.
16029 unsigned X86TargetLowering::getRegisterByName(const char* RegName,
16030                                               EVT VT) const {
16031   unsigned Reg = StringSwitch<unsigned>(RegName)
16032                        .Case("esp", X86::ESP)
16033                        .Case("rsp", X86::RSP)
16034                        .Default(0);
16035   if (Reg)
16036     return Reg;
16037   report_fatal_error("Invalid register name global variable");
16038 }
16039
16040 SDValue X86TargetLowering::LowerFRAME_TO_ARGS_OFFSET(SDValue Op,
16041                                                      SelectionDAG &DAG) const {
16042   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16043   return DAG.getIntPtrConstant(2 * RegInfo->getSlotSize(), SDLoc(Op));
16044 }
16045
16046 SDValue X86TargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG) const {
16047   SDValue Chain     = Op.getOperand(0);
16048   SDValue Offset    = Op.getOperand(1);
16049   SDValue Handler   = Op.getOperand(2);
16050   SDLoc dl      (Op);
16051
16052   EVT PtrVT = getPointerTy();
16053   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
16054   unsigned FrameReg = RegInfo->getFrameRegister(DAG.getMachineFunction());
16055   assert(((FrameReg == X86::RBP && PtrVT == MVT::i64) ||
16056           (FrameReg == X86::EBP && PtrVT == MVT::i32)) &&
16057          "Invalid Frame Register!");
16058   SDValue Frame = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, PtrVT);
16059   unsigned StoreAddrReg = (PtrVT == MVT::i64) ? X86::RCX : X86::ECX;
16060
16061   SDValue StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, Frame,
16062                                  DAG.getIntPtrConstant(RegInfo->getSlotSize(),
16063                                                        dl));
16064   StoreAddr = DAG.getNode(ISD::ADD, dl, PtrVT, StoreAddr, Offset);
16065   Chain = DAG.getStore(Chain, dl, Handler, StoreAddr, MachinePointerInfo(),
16066                        false, false, 0);
16067   Chain = DAG.getCopyToReg(Chain, dl, StoreAddrReg, StoreAddr);
16068
16069   return DAG.getNode(X86ISD::EH_RETURN, dl, MVT::Other, Chain,
16070                      DAG.getRegister(StoreAddrReg, PtrVT));
16071 }
16072
16073 SDValue X86TargetLowering::lowerEH_SJLJ_SETJMP(SDValue Op,
16074                                                SelectionDAG &DAG) const {
16075   SDLoc DL(Op);
16076   return DAG.getNode(X86ISD::EH_SJLJ_SETJMP, DL,
16077                      DAG.getVTList(MVT::i32, MVT::Other),
16078                      Op.getOperand(0), Op.getOperand(1));
16079 }
16080
16081 SDValue X86TargetLowering::lowerEH_SJLJ_LONGJMP(SDValue Op,
16082                                                 SelectionDAG &DAG) const {
16083   SDLoc DL(Op);
16084   return DAG.getNode(X86ISD::EH_SJLJ_LONGJMP, DL, MVT::Other,
16085                      Op.getOperand(0), Op.getOperand(1));
16086 }
16087
16088 static SDValue LowerADJUST_TRAMPOLINE(SDValue Op, SelectionDAG &DAG) {
16089   return Op.getOperand(0);
16090 }
16091
16092 SDValue X86TargetLowering::LowerINIT_TRAMPOLINE(SDValue Op,
16093                                                 SelectionDAG &DAG) const {
16094   SDValue Root = Op.getOperand(0);
16095   SDValue Trmp = Op.getOperand(1); // trampoline
16096   SDValue FPtr = Op.getOperand(2); // nested function
16097   SDValue Nest = Op.getOperand(3); // 'nest' parameter value
16098   SDLoc dl (Op);
16099
16100   const Value *TrmpAddr = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
16101   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
16102
16103   if (Subtarget->is64Bit()) {
16104     SDValue OutChains[6];
16105
16106     // Large code-model.
16107     const unsigned char JMP64r  = 0xFF; // 64-bit jmp through register opcode.
16108     const unsigned char MOV64ri = 0xB8; // X86::MOV64ri opcode.
16109
16110     const unsigned char N86R10 = TRI->getEncodingValue(X86::R10) & 0x7;
16111     const unsigned char N86R11 = TRI->getEncodingValue(X86::R11) & 0x7;
16112
16113     const unsigned char REX_WB = 0x40 | 0x08 | 0x01; // REX prefix
16114
16115     // Load the pointer to the nested function into R11.
16116     unsigned OpCode = ((MOV64ri | N86R11) << 8) | REX_WB; // movabsq r11
16117     SDValue Addr = Trmp;
16118     OutChains[0] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16119                                 Addr, MachinePointerInfo(TrmpAddr),
16120                                 false, false, 0);
16121
16122     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16123                        DAG.getConstant(2, dl, MVT::i64));
16124     OutChains[1] = DAG.getStore(Root, dl, FPtr, Addr,
16125                                 MachinePointerInfo(TrmpAddr, 2),
16126                                 false, false, 2);
16127
16128     // Load the 'nest' parameter value into R10.
16129     // R10 is specified in X86CallingConv.td
16130     OpCode = ((MOV64ri | N86R10) << 8) | REX_WB; // movabsq r10
16131     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16132                        DAG.getConstant(10, dl, MVT::i64));
16133     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16134                                 Addr, MachinePointerInfo(TrmpAddr, 10),
16135                                 false, false, 0);
16136
16137     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16138                        DAG.getConstant(12, dl, MVT::i64));
16139     OutChains[3] = DAG.getStore(Root, dl, Nest, Addr,
16140                                 MachinePointerInfo(TrmpAddr, 12),
16141                                 false, false, 2);
16142
16143     // Jump to the nested function.
16144     OpCode = (JMP64r << 8) | REX_WB; // jmpq *...
16145     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16146                        DAG.getConstant(20, dl, MVT::i64));
16147     OutChains[4] = DAG.getStore(Root, dl, DAG.getConstant(OpCode, dl, MVT::i16),
16148                                 Addr, MachinePointerInfo(TrmpAddr, 20),
16149                                 false, false, 0);
16150
16151     unsigned char ModRM = N86R11 | (4 << 3) | (3 << 6); // ...r11
16152     Addr = DAG.getNode(ISD::ADD, dl, MVT::i64, Trmp,
16153                        DAG.getConstant(22, dl, MVT::i64));
16154     OutChains[5] = DAG.getStore(Root, dl, DAG.getConstant(ModRM, dl, MVT::i8),
16155                                 Addr, MachinePointerInfo(TrmpAddr, 22),
16156                                 false, false, 0);
16157
16158     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16159   } else {
16160     const Function *Func =
16161       cast<Function>(cast<SrcValueSDNode>(Op.getOperand(5))->getValue());
16162     CallingConv::ID CC = Func->getCallingConv();
16163     unsigned NestReg;
16164
16165     switch (CC) {
16166     default:
16167       llvm_unreachable("Unsupported calling convention");
16168     case CallingConv::C:
16169     case CallingConv::X86_StdCall: {
16170       // Pass 'nest' parameter in ECX.
16171       // Must be kept in sync with X86CallingConv.td
16172       NestReg = X86::ECX;
16173
16174       // Check that ECX wasn't needed by an 'inreg' parameter.
16175       FunctionType *FTy = Func->getFunctionType();
16176       const AttributeSet &Attrs = Func->getAttributes();
16177
16178       if (!Attrs.isEmpty() && !Func->isVarArg()) {
16179         unsigned InRegCount = 0;
16180         unsigned Idx = 1;
16181
16182         for (FunctionType::param_iterator I = FTy->param_begin(),
16183              E = FTy->param_end(); I != E; ++I, ++Idx)
16184           if (Attrs.hasAttribute(Idx, Attribute::InReg))
16185             // FIXME: should only count parameters that are lowered to integers.
16186             InRegCount += (TD->getTypeSizeInBits(*I) + 31) / 32;
16187
16188         if (InRegCount > 2) {
16189           report_fatal_error("Nest register in use - reduce number of inreg"
16190                              " parameters!");
16191         }
16192       }
16193       break;
16194     }
16195     case CallingConv::X86_FastCall:
16196     case CallingConv::X86_ThisCall:
16197     case CallingConv::Fast:
16198       // Pass 'nest' parameter in EAX.
16199       // Must be kept in sync with X86CallingConv.td
16200       NestReg = X86::EAX;
16201       break;
16202     }
16203
16204     SDValue OutChains[4];
16205     SDValue Addr, Disp;
16206
16207     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16208                        DAG.getConstant(10, dl, MVT::i32));
16209     Disp = DAG.getNode(ISD::SUB, dl, MVT::i32, FPtr, Addr);
16210
16211     // This is storing the opcode for MOV32ri.
16212     const unsigned char MOV32ri = 0xB8; // X86::MOV32ri's opcode byte.
16213     const unsigned char N86Reg = TRI->getEncodingValue(NestReg) & 0x7;
16214     OutChains[0] = DAG.getStore(Root, dl,
16215                                 DAG.getConstant(MOV32ri|N86Reg, dl, MVT::i8),
16216                                 Trmp, MachinePointerInfo(TrmpAddr),
16217                                 false, false, 0);
16218
16219     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16220                        DAG.getConstant(1, dl, MVT::i32));
16221     OutChains[1] = DAG.getStore(Root, dl, Nest, Addr,
16222                                 MachinePointerInfo(TrmpAddr, 1),
16223                                 false, false, 1);
16224
16225     const unsigned char JMP = 0xE9; // jmp <32bit dst> opcode.
16226     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16227                        DAG.getConstant(5, dl, MVT::i32));
16228     OutChains[2] = DAG.getStore(Root, dl, DAG.getConstant(JMP, dl, MVT::i8),
16229                                 Addr, MachinePointerInfo(TrmpAddr, 5),
16230                                 false, false, 1);
16231
16232     Addr = DAG.getNode(ISD::ADD, dl, MVT::i32, Trmp,
16233                        DAG.getConstant(6, dl, MVT::i32));
16234     OutChains[3] = DAG.getStore(Root, dl, Disp, Addr,
16235                                 MachinePointerInfo(TrmpAddr, 6),
16236                                 false, false, 1);
16237
16238     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
16239   }
16240 }
16241
16242 SDValue X86TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
16243                                             SelectionDAG &DAG) const {
16244   /*
16245    The rounding mode is in bits 11:10 of FPSR, and has the following
16246    settings:
16247      00 Round to nearest
16248      01 Round to -inf
16249      10 Round to +inf
16250      11 Round to 0
16251
16252   FLT_ROUNDS, on the other hand, expects the following:
16253     -1 Undefined
16254      0 Round to 0
16255      1 Round to nearest
16256      2 Round to +inf
16257      3 Round to -inf
16258
16259   To perform the conversion, we do:
16260     (((((FPSR & 0x800) >> 11) | ((FPSR & 0x400) >> 9)) + 1) & 3)
16261   */
16262
16263   MachineFunction &MF = DAG.getMachineFunction();
16264   const TargetFrameLowering &TFI = *Subtarget->getFrameLowering();
16265   unsigned StackAlignment = TFI.getStackAlignment();
16266   MVT VT = Op.getSimpleValueType();
16267   SDLoc DL(Op);
16268
16269   // Save FP Control Word to stack slot
16270   int SSFI = MF.getFrameInfo()->CreateStackObject(2, StackAlignment, false);
16271   SDValue StackSlot = DAG.getFrameIndex(SSFI, getPointerTy());
16272
16273   MachineMemOperand *MMO =
16274    MF.getMachineMemOperand(MachinePointerInfo::getFixedStack(SSFI),
16275                            MachineMemOperand::MOStore, 2, 2);
16276
16277   SDValue Ops[] = { DAG.getEntryNode(), StackSlot };
16278   SDValue Chain = DAG.getMemIntrinsicNode(X86ISD::FNSTCW16m, DL,
16279                                           DAG.getVTList(MVT::Other),
16280                                           Ops, MVT::i16, MMO);
16281
16282   // Load FP Control Word from stack slot
16283   SDValue CWD = DAG.getLoad(MVT::i16, DL, Chain, StackSlot,
16284                             MachinePointerInfo(), false, false, false, 0);
16285
16286   // Transform as necessary
16287   SDValue CWD1 =
16288     DAG.getNode(ISD::SRL, DL, MVT::i16,
16289                 DAG.getNode(ISD::AND, DL, MVT::i16,
16290                             CWD, DAG.getConstant(0x800, DL, MVT::i16)),
16291                 DAG.getConstant(11, DL, MVT::i8));
16292   SDValue CWD2 =
16293     DAG.getNode(ISD::SRL, DL, MVT::i16,
16294                 DAG.getNode(ISD::AND, DL, MVT::i16,
16295                             CWD, DAG.getConstant(0x400, DL, MVT::i16)),
16296                 DAG.getConstant(9, DL, MVT::i8));
16297
16298   SDValue RetVal =
16299     DAG.getNode(ISD::AND, DL, MVT::i16,
16300                 DAG.getNode(ISD::ADD, DL, MVT::i16,
16301                             DAG.getNode(ISD::OR, DL, MVT::i16, CWD1, CWD2),
16302                             DAG.getConstant(1, DL, MVT::i16)),
16303                 DAG.getConstant(3, DL, MVT::i16));
16304
16305   return DAG.getNode((VT.getSizeInBits() < 16 ?
16306                       ISD::TRUNCATE : ISD::ZERO_EXTEND), DL, VT, RetVal);
16307 }
16308
16309 static SDValue LowerCTLZ(SDValue Op, SelectionDAG &DAG) {
16310   MVT VT = Op.getSimpleValueType();
16311   EVT OpVT = VT;
16312   unsigned NumBits = VT.getSizeInBits();
16313   SDLoc dl(Op);
16314
16315   Op = Op.getOperand(0);
16316   if (VT == MVT::i8) {
16317     // Zero extend to i32 since there is not an i8 bsr.
16318     OpVT = MVT::i32;
16319     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16320   }
16321
16322   // Issue a bsr (scan bits in reverse) which also sets EFLAGS.
16323   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16324   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16325
16326   // If src is zero (i.e. bsr sets ZF), returns NumBits.
16327   SDValue Ops[] = {
16328     Op,
16329     DAG.getConstant(NumBits + NumBits - 1, dl, OpVT),
16330     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16331     Op.getValue(1)
16332   };
16333   Op = DAG.getNode(X86ISD::CMOV, dl, OpVT, Ops);
16334
16335   // Finally xor with NumBits-1.
16336   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16337                    DAG.getConstant(NumBits - 1, dl, OpVT));
16338
16339   if (VT == MVT::i8)
16340     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16341   return Op;
16342 }
16343
16344 static SDValue LowerCTLZ_ZERO_UNDEF(SDValue Op, SelectionDAG &DAG) {
16345   MVT VT = Op.getSimpleValueType();
16346   EVT OpVT = VT;
16347   unsigned NumBits = VT.getSizeInBits();
16348   SDLoc dl(Op);
16349
16350   Op = Op.getOperand(0);
16351   if (VT == MVT::i8) {
16352     // Zero extend to i32 since there is not an i8 bsr.
16353     OpVT = MVT::i32;
16354     Op = DAG.getNode(ISD::ZERO_EXTEND, dl, OpVT, Op);
16355   }
16356
16357   // Issue a bsr (scan bits in reverse).
16358   SDVTList VTs = DAG.getVTList(OpVT, MVT::i32);
16359   Op = DAG.getNode(X86ISD::BSR, dl, VTs, Op);
16360
16361   // And xor with NumBits-1.
16362   Op = DAG.getNode(ISD::XOR, dl, OpVT, Op,
16363                    DAG.getConstant(NumBits - 1, dl, OpVT));
16364
16365   if (VT == MVT::i8)
16366     Op = DAG.getNode(ISD::TRUNCATE, dl, MVT::i8, Op);
16367   return Op;
16368 }
16369
16370 static SDValue LowerCTTZ(SDValue Op, SelectionDAG &DAG) {
16371   MVT VT = Op.getSimpleValueType();
16372   unsigned NumBits = VT.getSizeInBits();
16373   SDLoc dl(Op);
16374   Op = Op.getOperand(0);
16375
16376   // Issue a bsf (scan bits forward) which also sets EFLAGS.
16377   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
16378   Op = DAG.getNode(X86ISD::BSF, dl, VTs, Op);
16379
16380   // If src is zero (i.e. bsf sets ZF), returns NumBits.
16381   SDValue Ops[] = {
16382     Op,
16383     DAG.getConstant(NumBits, dl, VT),
16384     DAG.getConstant(X86::COND_E, dl, MVT::i8),
16385     Op.getValue(1)
16386   };
16387   return DAG.getNode(X86ISD::CMOV, dl, VT, Ops);
16388 }
16389
16390 // Lower256IntArith - Break a 256-bit integer operation into two new 128-bit
16391 // ones, and then concatenate the result back.
16392 static SDValue Lower256IntArith(SDValue Op, SelectionDAG &DAG) {
16393   MVT VT = Op.getSimpleValueType();
16394
16395   assert(VT.is256BitVector() && VT.isInteger() &&
16396          "Unsupported value type for operation");
16397
16398   unsigned NumElems = VT.getVectorNumElements();
16399   SDLoc dl(Op);
16400
16401   // Extract the LHS vectors
16402   SDValue LHS = Op.getOperand(0);
16403   SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, dl);
16404   SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, dl);
16405
16406   // Extract the RHS vectors
16407   SDValue RHS = Op.getOperand(1);
16408   SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, dl);
16409   SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, dl);
16410
16411   MVT EltVT = VT.getVectorElementType();
16412   MVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
16413
16414   return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16415                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS1, RHS1),
16416                      DAG.getNode(Op.getOpcode(), dl, NewVT, LHS2, RHS2));
16417 }
16418
16419 static SDValue LowerADD(SDValue Op, SelectionDAG &DAG) {
16420   if (Op.getValueType() == MVT::i1)
16421     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16422                        Op.getOperand(0), Op.getOperand(1));
16423   assert(Op.getSimpleValueType().is256BitVector() &&
16424          Op.getSimpleValueType().isInteger() &&
16425          "Only handle AVX 256-bit vector integer operation");
16426   return Lower256IntArith(Op, DAG);
16427 }
16428
16429 static SDValue LowerSUB(SDValue Op, SelectionDAG &DAG) {
16430   if (Op.getValueType() == MVT::i1)
16431     return DAG.getNode(ISD::XOR, SDLoc(Op), Op.getValueType(),
16432                        Op.getOperand(0), Op.getOperand(1));
16433   assert(Op.getSimpleValueType().is256BitVector() &&
16434          Op.getSimpleValueType().isInteger() &&
16435          "Only handle AVX 256-bit vector integer operation");
16436   return Lower256IntArith(Op, DAG);
16437 }
16438
16439 static SDValue LowerMUL(SDValue Op, const X86Subtarget *Subtarget,
16440                         SelectionDAG &DAG) {
16441   SDLoc dl(Op);
16442   MVT VT = Op.getSimpleValueType();
16443
16444   if (VT == MVT::i1)
16445     return DAG.getNode(ISD::AND, dl, VT, Op.getOperand(0), Op.getOperand(1));
16446
16447   // Decompose 256-bit ops into smaller 128-bit ops.
16448   if (VT.is256BitVector() && !Subtarget->hasInt256())
16449     return Lower256IntArith(Op, DAG);
16450
16451   SDValue A = Op.getOperand(0);
16452   SDValue B = Op.getOperand(1);
16453
16454   // Lower v16i8/v32i8 mul as promotion to v8i16/v16i16 vector
16455   // pairs, multiply and truncate.
16456   if (VT == MVT::v16i8 || VT == MVT::v32i8) {
16457     if (Subtarget->hasInt256()) {
16458       if (VT == MVT::v32i8) {
16459         MVT SubVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() / 2);
16460         SDValue Lo = DAG.getIntPtrConstant(0, dl);
16461         SDValue Hi = DAG.getIntPtrConstant(VT.getVectorNumElements() / 2, dl);
16462         SDValue ALo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Lo);
16463         SDValue BLo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Lo);
16464         SDValue AHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, A, Hi);
16465         SDValue BHi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, SubVT, B, Hi);
16466         return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
16467                            DAG.getNode(ISD::MUL, dl, SubVT, ALo, BLo),
16468                            DAG.getNode(ISD::MUL, dl, SubVT, AHi, BHi));
16469       }
16470
16471       MVT ExVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements());
16472       return DAG.getNode(
16473           ISD::TRUNCATE, dl, VT,
16474           DAG.getNode(ISD::MUL, dl, ExVT,
16475                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, A),
16476                       DAG.getNode(ISD::SIGN_EXTEND, dl, ExVT, B)));
16477     }
16478
16479     assert(VT == MVT::v16i8 &&
16480            "Pre-AVX2 support only supports v16i8 multiplication");
16481     MVT ExVT = MVT::v8i16;
16482
16483     // Extract the lo parts and sign extend to i16
16484     SDValue ALo, BLo;
16485     if (Subtarget->hasSSE41()) {
16486       ALo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, A);
16487       BLo = DAG.getNode(X86ISD::VSEXT, dl, ExVT, B);
16488     } else {
16489       const int ShufMask[] = {-1, 0, -1, 1, -1, 2, -1, 3,
16490                               -1, 4, -1, 5, -1, 6, -1, 7};
16491       ALo = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16492       BLo = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16493       ALo = DAG.getBitcast(ExVT, ALo);
16494       BLo = DAG.getBitcast(ExVT, BLo);
16495       ALo = DAG.getNode(ISD::SRA, dl, ExVT, ALo, DAG.getConstant(8, dl, ExVT));
16496       BLo = DAG.getNode(ISD::SRA, dl, ExVT, BLo, DAG.getConstant(8, dl, ExVT));
16497     }
16498
16499     // Extract the hi parts and sign extend to i16
16500     SDValue AHi, BHi;
16501     if (Subtarget->hasSSE41()) {
16502       const int ShufMask[] = {8,  9,  10, 11, 12, 13, 14, 15,
16503                               -1, -1, -1, -1, -1, -1, -1, -1};
16504       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16505       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16506       AHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, AHi);
16507       BHi = DAG.getNode(X86ISD::VSEXT, dl, ExVT, BHi);
16508     } else {
16509       const int ShufMask[] = {-1, 8,  -1, 9,  -1, 10, -1, 11,
16510                               -1, 12, -1, 13, -1, 14, -1, 15};
16511       AHi = DAG.getVectorShuffle(VT, dl, A, A, ShufMask);
16512       BHi = DAG.getVectorShuffle(VT, dl, B, B, ShufMask);
16513       AHi = DAG.getBitcast(ExVT, AHi);
16514       BHi = DAG.getBitcast(ExVT, BHi);
16515       AHi = DAG.getNode(ISD::SRA, dl, ExVT, AHi, DAG.getConstant(8, dl, ExVT));
16516       BHi = DAG.getNode(ISD::SRA, dl, ExVT, BHi, DAG.getConstant(8, dl, ExVT));
16517     }
16518
16519     // Multiply, mask the lower 8bits of the lo/hi results and pack
16520     SDValue RLo = DAG.getNode(ISD::MUL, dl, ExVT, ALo, BLo);
16521     SDValue RHi = DAG.getNode(ISD::MUL, dl, ExVT, AHi, BHi);
16522     RLo = DAG.getNode(ISD::AND, dl, ExVT, RLo, DAG.getConstant(255, dl, ExVT));
16523     RHi = DAG.getNode(ISD::AND, dl, ExVT, RHi, DAG.getConstant(255, dl, ExVT));
16524     return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
16525   }
16526
16527   // Lower v4i32 mul as 2x shuffle, 2x pmuludq, 2x shuffle.
16528   if (VT == MVT::v4i32) {
16529     assert(Subtarget->hasSSE2() && !Subtarget->hasSSE41() &&
16530            "Should not custom lower when pmuldq is available!");
16531
16532     // Extract the odd parts.
16533     static const int UnpackMask[] = { 1, -1, 3, -1 };
16534     SDValue Aodds = DAG.getVectorShuffle(VT, dl, A, A, UnpackMask);
16535     SDValue Bodds = DAG.getVectorShuffle(VT, dl, B, B, UnpackMask);
16536
16537     // Multiply the even parts.
16538     SDValue Evens = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, A, B);
16539     // Now multiply odd parts.
16540     SDValue Odds = DAG.getNode(X86ISD::PMULUDQ, dl, MVT::v2i64, Aodds, Bodds);
16541
16542     Evens = DAG.getBitcast(VT, Evens);
16543     Odds = DAG.getBitcast(VT, Odds);
16544
16545     // Merge the two vectors back together with a shuffle. This expands into 2
16546     // shuffles.
16547     static const int ShufMask[] = { 0, 4, 2, 6 };
16548     return DAG.getVectorShuffle(VT, dl, Evens, Odds, ShufMask);
16549   }
16550
16551   assert((VT == MVT::v2i64 || VT == MVT::v4i64 || VT == MVT::v8i64) &&
16552          "Only know how to lower V2I64/V4I64/V8I64 multiply");
16553
16554   //  Ahi = psrlqi(a, 32);
16555   //  Bhi = psrlqi(b, 32);
16556   //
16557   //  AloBlo = pmuludq(a, b);
16558   //  AloBhi = pmuludq(a, Bhi);
16559   //  AhiBlo = pmuludq(Ahi, b);
16560
16561   //  AloBhi = psllqi(AloBhi, 32);
16562   //  AhiBlo = psllqi(AhiBlo, 32);
16563   //  return AloBlo + AloBhi + AhiBlo;
16564
16565   SDValue Ahi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, A, 32, DAG);
16566   SDValue Bhi = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, VT, B, 32, DAG);
16567
16568   SDValue AhiBlo = Ahi;
16569   SDValue AloBhi = Bhi;
16570   // Bit cast to 32-bit vectors for MULUDQ
16571   EVT MulVT = (VT == MVT::v2i64) ? MVT::v4i32 :
16572                                   (VT == MVT::v4i64) ? MVT::v8i32 : MVT::v16i32;
16573   A = DAG.getBitcast(MulVT, A);
16574   B = DAG.getBitcast(MulVT, B);
16575   Ahi = DAG.getBitcast(MulVT, Ahi);
16576   Bhi = DAG.getBitcast(MulVT, Bhi);
16577
16578   SDValue AloBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, B);
16579   // After shifting right const values the result may be all-zero.
16580   if (!ISD::isBuildVectorAllZeros(Ahi.getNode())) {
16581     AhiBlo = DAG.getNode(X86ISD::PMULUDQ, dl, VT, Ahi, B);
16582     AhiBlo = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AhiBlo, 32, DAG);
16583   }
16584   if (!ISD::isBuildVectorAllZeros(Bhi.getNode())) {
16585     AloBhi = DAG.getNode(X86ISD::PMULUDQ, dl, VT, A, Bhi);
16586     AloBhi = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, VT, AloBhi, 32, DAG);
16587   }
16588
16589   SDValue Res = DAG.getNode(ISD::ADD, dl, VT, AloBlo, AloBhi);
16590   return DAG.getNode(ISD::ADD, dl, VT, Res, AhiBlo);
16591 }
16592
16593 SDValue X86TargetLowering::LowerWin64_i128OP(SDValue Op, SelectionDAG &DAG) const {
16594   assert(Subtarget->isTargetWin64() && "Unexpected target");
16595   EVT VT = Op.getValueType();
16596   assert(VT.isInteger() && VT.getSizeInBits() == 128 &&
16597          "Unexpected return type for lowering");
16598
16599   RTLIB::Libcall LC;
16600   bool isSigned;
16601   switch (Op->getOpcode()) {
16602   default: llvm_unreachable("Unexpected request for libcall!");
16603   case ISD::SDIV:      isSigned = true;  LC = RTLIB::SDIV_I128;    break;
16604   case ISD::UDIV:      isSigned = false; LC = RTLIB::UDIV_I128;    break;
16605   case ISD::SREM:      isSigned = true;  LC = RTLIB::SREM_I128;    break;
16606   case ISD::UREM:      isSigned = false; LC = RTLIB::UREM_I128;    break;
16607   case ISD::SDIVREM:   isSigned = true;  LC = RTLIB::SDIVREM_I128; break;
16608   case ISD::UDIVREM:   isSigned = false; LC = RTLIB::UDIVREM_I128; break;
16609   }
16610
16611   SDLoc dl(Op);
16612   SDValue InChain = DAG.getEntryNode();
16613
16614   TargetLowering::ArgListTy Args;
16615   TargetLowering::ArgListEntry Entry;
16616   for (unsigned i = 0, e = Op->getNumOperands(); i != e; ++i) {
16617     EVT ArgVT = Op->getOperand(i).getValueType();
16618     assert(ArgVT.isInteger() && ArgVT.getSizeInBits() == 128 &&
16619            "Unexpected argument type for lowering");
16620     SDValue StackPtr = DAG.CreateStackTemporary(ArgVT, 16);
16621     Entry.Node = StackPtr;
16622     InChain = DAG.getStore(InChain, dl, Op->getOperand(i), StackPtr, MachinePointerInfo(),
16623                            false, false, 16);
16624     Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
16625     Entry.Ty = PointerType::get(ArgTy,0);
16626     Entry.isSExt = false;
16627     Entry.isZExt = false;
16628     Args.push_back(Entry);
16629   }
16630
16631   SDValue Callee = DAG.getExternalSymbol(getLibcallName(LC),
16632                                          getPointerTy());
16633
16634   TargetLowering::CallLoweringInfo CLI(DAG);
16635   CLI.setDebugLoc(dl).setChain(InChain)
16636     .setCallee(getLibcallCallingConv(LC),
16637                static_cast<EVT>(MVT::v2i64).getTypeForEVT(*DAG.getContext()),
16638                Callee, std::move(Args), 0)
16639     .setInRegister().setSExtResult(isSigned).setZExtResult(!isSigned);
16640
16641   std::pair<SDValue, SDValue> CallInfo = LowerCallTo(CLI);
16642   return DAG.getBitcast(VT, CallInfo.first);
16643 }
16644
16645 static SDValue LowerMUL_LOHI(SDValue Op, const X86Subtarget *Subtarget,
16646                              SelectionDAG &DAG) {
16647   SDValue Op0 = Op.getOperand(0), Op1 = Op.getOperand(1);
16648   EVT VT = Op0.getValueType();
16649   SDLoc dl(Op);
16650
16651   assert((VT == MVT::v4i32 && Subtarget->hasSSE2()) ||
16652          (VT == MVT::v8i32 && Subtarget->hasInt256()));
16653
16654   // PMULxD operations multiply each even value (starting at 0) of LHS with
16655   // the related value of RHS and produce a widen result.
16656   // E.g., PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16657   // => <2 x i64> <ae|cg>
16658   //
16659   // In other word, to have all the results, we need to perform two PMULxD:
16660   // 1. one with the even values.
16661   // 2. one with the odd values.
16662   // To achieve #2, with need to place the odd values at an even position.
16663   //
16664   // Place the odd value at an even position (basically, shift all values 1
16665   // step to the left):
16666   const int Mask[] = {1, -1, 3, -1, 5, -1, 7, -1};
16667   // <a|b|c|d> => <b|undef|d|undef>
16668   SDValue Odd0 = DAG.getVectorShuffle(VT, dl, Op0, Op0, Mask);
16669   // <e|f|g|h> => <f|undef|h|undef>
16670   SDValue Odd1 = DAG.getVectorShuffle(VT, dl, Op1, Op1, Mask);
16671
16672   // Emit two multiplies, one for the lower 2 ints and one for the higher 2
16673   // ints.
16674   MVT MulVT = VT == MVT::v4i32 ? MVT::v2i64 : MVT::v4i64;
16675   bool IsSigned = Op->getOpcode() == ISD::SMUL_LOHI;
16676   unsigned Opcode =
16677       (!IsSigned || !Subtarget->hasSSE41()) ? X86ISD::PMULUDQ : X86ISD::PMULDQ;
16678   // PMULUDQ <4 x i32> <a|b|c|d>, <4 x i32> <e|f|g|h>
16679   // => <2 x i64> <ae|cg>
16680   SDValue Mul1 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Op0, Op1));
16681   // PMULUDQ <4 x i32> <b|undef|d|undef>, <4 x i32> <f|undef|h|undef>
16682   // => <2 x i64> <bf|dh>
16683   SDValue Mul2 = DAG.getBitcast(VT, DAG.getNode(Opcode, dl, MulVT, Odd0, Odd1));
16684
16685   // Shuffle it back into the right order.
16686   SDValue Highs, Lows;
16687   if (VT == MVT::v8i32) {
16688     const int HighMask[] = {1, 9, 3, 11, 5, 13, 7, 15};
16689     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16690     const int LowMask[] = {0, 8, 2, 10, 4, 12, 6, 14};
16691     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16692   } else {
16693     const int HighMask[] = {1, 5, 3, 7};
16694     Highs = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, HighMask);
16695     const int LowMask[] = {0, 4, 2, 6};
16696     Lows = DAG.getVectorShuffle(VT, dl, Mul1, Mul2, LowMask);
16697   }
16698
16699   // If we have a signed multiply but no PMULDQ fix up the high parts of a
16700   // unsigned multiply.
16701   if (IsSigned && !Subtarget->hasSSE41()) {
16702     SDValue ShAmt =
16703         DAG.getConstant(31, dl,
16704                         DAG.getTargetLoweringInfo().getShiftAmountTy(VT));
16705     SDValue T1 = DAG.getNode(ISD::AND, dl, VT,
16706                              DAG.getNode(ISD::SRA, dl, VT, Op0, ShAmt), Op1);
16707     SDValue T2 = DAG.getNode(ISD::AND, dl, VT,
16708                              DAG.getNode(ISD::SRA, dl, VT, Op1, ShAmt), Op0);
16709
16710     SDValue Fixup = DAG.getNode(ISD::ADD, dl, VT, T1, T2);
16711     Highs = DAG.getNode(ISD::SUB, dl, VT, Highs, Fixup);
16712   }
16713
16714   // The first result of MUL_LOHI is actually the low value, followed by the
16715   // high value.
16716   SDValue Ops[] = {Lows, Highs};
16717   return DAG.getMergeValues(Ops, dl);
16718 }
16719
16720 // Return true if the requred (according to Opcode) shift-imm form is natively
16721 // supported by the Subtarget
16722 static bool SupportedVectorShiftWithImm(MVT VT, const X86Subtarget *Subtarget,
16723                                         unsigned Opcode) {
16724   if (VT.getScalarSizeInBits() < 16)
16725     return false;
16726
16727   if (VT.is512BitVector() &&
16728       (VT.getScalarSizeInBits() > 16 || Subtarget->hasBWI()))
16729     return true;
16730
16731   bool LShift = VT.is128BitVector() ||
16732     (VT.is256BitVector() && Subtarget->hasInt256());
16733
16734   bool AShift = LShift && (Subtarget->hasVLX() ||
16735     (VT != MVT::v2i64 && VT != MVT::v4i64));
16736   return (Opcode == ISD::SRA) ? AShift : LShift;
16737 }
16738
16739 // The shift amount is a variable, but it is the same for all vector lanes.
16740 // These instrcutions are defined together with shift-immediate.
16741 static
16742 bool SupportedVectorShiftWithBaseAmnt(MVT VT, const X86Subtarget *Subtarget,
16743                                       unsigned Opcode) {
16744   return SupportedVectorShiftWithImm(VT, Subtarget, Opcode);
16745 }
16746
16747 // Return true if the requred (according to Opcode) variable-shift form is
16748 // natively supported by the Subtarget
16749 static bool SupportedVectorVarShift(MVT VT, const X86Subtarget *Subtarget,
16750                                     unsigned Opcode) {
16751
16752   if (!Subtarget->hasInt256() || VT.getScalarSizeInBits() < 16)
16753     return false;
16754
16755   // vXi16 supported only on AVX-512, BWI
16756   if (VT.getScalarSizeInBits() == 16 && !Subtarget->hasBWI())
16757     return false;
16758
16759   if (VT.is512BitVector() || Subtarget->hasVLX())
16760     return true;
16761
16762   bool LShift = VT.is128BitVector() || VT.is256BitVector();
16763   bool AShift = LShift &&  VT != MVT::v2i64 && VT != MVT::v4i64;
16764   return (Opcode == ISD::SRA) ? AShift : LShift;
16765 }
16766
16767 static SDValue LowerScalarImmediateShift(SDValue Op, SelectionDAG &DAG,
16768                                          const X86Subtarget *Subtarget) {
16769   MVT VT = Op.getSimpleValueType();
16770   SDLoc dl(Op);
16771   SDValue R = Op.getOperand(0);
16772   SDValue Amt = Op.getOperand(1);
16773
16774   unsigned X86Opc = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16775     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16776
16777   // Optimize shl/srl/sra with constant shift amount.
16778   if (auto *BVAmt = dyn_cast<BuildVectorSDNode>(Amt)) {
16779     if (auto *ShiftConst = BVAmt->getConstantSplatNode()) {
16780       uint64_t ShiftAmt = ShiftConst->getZExtValue();
16781
16782       if (SupportedVectorShiftWithImm(VT, Subtarget, Op.getOpcode()))
16783         return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16784
16785       if (VT == MVT::v16i8 || (Subtarget->hasInt256() && VT == MVT::v32i8)) {
16786         unsigned NumElts = VT.getVectorNumElements();
16787         MVT ShiftVT = MVT::getVectorVT(MVT::i16, NumElts / 2);
16788
16789         if (Op.getOpcode() == ISD::SHL) {
16790           // Simple i8 add case
16791           if (ShiftAmt == 1)
16792             return DAG.getNode(ISD::ADD, dl, VT, R, R);
16793
16794           // Make a large shift.
16795           SDValue SHL = getTargetVShiftByConstNode(X86ISD::VSHLI, dl, ShiftVT,
16796                                                    R, ShiftAmt, DAG);
16797           SHL = DAG.getBitcast(VT, SHL);
16798           // Zero out the rightmost bits.
16799           SmallVector<SDValue, 32> V(
16800               NumElts, DAG.getConstant(uint8_t(-1U << ShiftAmt), dl, MVT::i8));
16801           return DAG.getNode(ISD::AND, dl, VT, SHL,
16802                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16803         }
16804         if (Op.getOpcode() == ISD::SRL) {
16805           // Make a large shift.
16806           SDValue SRL = getTargetVShiftByConstNode(X86ISD::VSRLI, dl, ShiftVT,
16807                                                    R, ShiftAmt, DAG);
16808           SRL = DAG.getBitcast(VT, SRL);
16809           // Zero out the leftmost bits.
16810           SmallVector<SDValue, 32> V(
16811               NumElts, DAG.getConstant(uint8_t(-1U) >> ShiftAmt, dl, MVT::i8));
16812           return DAG.getNode(ISD::AND, dl, VT, SRL,
16813                              DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V));
16814         }
16815         if (Op.getOpcode() == ISD::SRA) {
16816           if (ShiftAmt == 7) {
16817             // R s>> 7  ===  R s< 0
16818             SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
16819             return DAG.getNode(X86ISD::PCMPGT, dl, VT, Zeros, R);
16820           }
16821
16822           // R s>> a === ((R u>> a) ^ m) - m
16823           SDValue Res = DAG.getNode(ISD::SRL, dl, VT, R, Amt);
16824           SmallVector<SDValue, 32> V(NumElts,
16825                                      DAG.getConstant(128 >> ShiftAmt, dl,
16826                                                      MVT::i8));
16827           SDValue Mask = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, V);
16828           Res = DAG.getNode(ISD::XOR, dl, VT, Res, Mask);
16829           Res = DAG.getNode(ISD::SUB, dl, VT, Res, Mask);
16830           return Res;
16831         }
16832         llvm_unreachable("Unknown shift opcode.");
16833       }
16834     }
16835   }
16836
16837   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16838   if (!Subtarget->is64Bit() &&
16839       (VT == MVT::v2i64 || (Subtarget->hasInt256() && VT == MVT::v4i64)) &&
16840       Amt.getOpcode() == ISD::BITCAST &&
16841       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16842     Amt = Amt.getOperand(0);
16843     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16844                      VT.getVectorNumElements();
16845     unsigned RatioInLog2 = Log2_32_Ceil(Ratio);
16846     uint64_t ShiftAmt = 0;
16847     for (unsigned i = 0; i != Ratio; ++i) {
16848       ConstantSDNode *C = dyn_cast<ConstantSDNode>(Amt.getOperand(i));
16849       if (!C)
16850         return SDValue();
16851       // 6 == Log2(64)
16852       ShiftAmt |= C->getZExtValue() << (i * (1 << (6 - RatioInLog2)));
16853     }
16854     // Check remaining shift amounts.
16855     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16856       uint64_t ShAmt = 0;
16857       for (unsigned j = 0; j != Ratio; ++j) {
16858         ConstantSDNode *C =
16859           dyn_cast<ConstantSDNode>(Amt.getOperand(i + j));
16860         if (!C)
16861           return SDValue();
16862         // 6 == Log2(64)
16863         ShAmt |= C->getZExtValue() << (j * (1 << (6 - RatioInLog2)));
16864       }
16865       if (ShAmt != ShiftAmt)
16866         return SDValue();
16867     }
16868     return getTargetVShiftByConstNode(X86Opc, dl, VT, R, ShiftAmt, DAG);
16869   }
16870
16871   return SDValue();
16872 }
16873
16874 static SDValue LowerScalarVariableShift(SDValue Op, SelectionDAG &DAG,
16875                                         const X86Subtarget* Subtarget) {
16876   MVT VT = Op.getSimpleValueType();
16877   SDLoc dl(Op);
16878   SDValue R = Op.getOperand(0);
16879   SDValue Amt = Op.getOperand(1);
16880
16881   unsigned X86OpcI = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHLI :
16882     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRLI : X86ISD::VSRAI;
16883
16884   unsigned X86OpcV = (Op.getOpcode() == ISD::SHL) ? X86ISD::VSHL :
16885     (Op.getOpcode() == ISD::SRL) ? X86ISD::VSRL : X86ISD::VSRA;
16886
16887   if (SupportedVectorShiftWithBaseAmnt(VT, Subtarget, Op.getOpcode())) {
16888     SDValue BaseShAmt;
16889     EVT EltVT = VT.getVectorElementType();
16890
16891     if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Amt)) {
16892       // Check if this build_vector node is doing a splat.
16893       // If so, then set BaseShAmt equal to the splat value.
16894       BaseShAmt = BV->getSplatValue();
16895       if (BaseShAmt && BaseShAmt.getOpcode() == ISD::UNDEF)
16896         BaseShAmt = SDValue();
16897     } else {
16898       if (Amt.getOpcode() == ISD::EXTRACT_SUBVECTOR)
16899         Amt = Amt.getOperand(0);
16900
16901       ShuffleVectorSDNode *SVN = dyn_cast<ShuffleVectorSDNode>(Amt);
16902       if (SVN && SVN->isSplat()) {
16903         unsigned SplatIdx = (unsigned)SVN->getSplatIndex();
16904         SDValue InVec = Amt.getOperand(0);
16905         if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
16906           assert((SplatIdx < InVec.getValueType().getVectorNumElements()) &&
16907                  "Unexpected shuffle index found!");
16908           BaseShAmt = InVec.getOperand(SplatIdx);
16909         } else if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT) {
16910            if (ConstantSDNode *C =
16911                dyn_cast<ConstantSDNode>(InVec.getOperand(2))) {
16912              if (C->getZExtValue() == SplatIdx)
16913                BaseShAmt = InVec.getOperand(1);
16914            }
16915         }
16916
16917         if (!BaseShAmt)
16918           // Avoid introducing an extract element from a shuffle.
16919           BaseShAmt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, EltVT, InVec,
16920                                   DAG.getIntPtrConstant(SplatIdx, dl));
16921       }
16922     }
16923
16924     if (BaseShAmt.getNode()) {
16925       assert(EltVT.bitsLE(MVT::i64) && "Unexpected element type!");
16926       if (EltVT != MVT::i64 && EltVT.bitsGT(MVT::i32))
16927         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i64, BaseShAmt);
16928       else if (EltVT.bitsLT(MVT::i32))
16929         BaseShAmt = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::i32, BaseShAmt);
16930
16931       return getTargetVShiftNode(X86OpcI, dl, VT, R, BaseShAmt, DAG);
16932     }
16933   }
16934
16935   // Special case in 32-bit mode, where i64 is expanded into high and low parts.
16936   if (!Subtarget->is64Bit() && VT == MVT::v2i64  &&
16937       Amt.getOpcode() == ISD::BITCAST &&
16938       Amt.getOperand(0).getOpcode() == ISD::BUILD_VECTOR) {
16939     Amt = Amt.getOperand(0);
16940     unsigned Ratio = Amt.getSimpleValueType().getVectorNumElements() /
16941                      VT.getVectorNumElements();
16942     std::vector<SDValue> Vals(Ratio);
16943     for (unsigned i = 0; i != Ratio; ++i)
16944       Vals[i] = Amt.getOperand(i);
16945     for (unsigned i = Ratio; i != Amt.getNumOperands(); i += Ratio) {
16946       for (unsigned j = 0; j != Ratio; ++j)
16947         if (Vals[j] != Amt.getOperand(i + j))
16948           return SDValue();
16949     }
16950     return DAG.getNode(X86OpcV, dl, VT, R, Op.getOperand(1));
16951   }
16952   return SDValue();
16953 }
16954
16955 static SDValue LowerShift(SDValue Op, const X86Subtarget* Subtarget,
16956                           SelectionDAG &DAG) {
16957   MVT VT = Op.getSimpleValueType();
16958   SDLoc dl(Op);
16959   SDValue R = Op.getOperand(0);
16960   SDValue Amt = Op.getOperand(1);
16961
16962   assert(VT.isVector() && "Custom lowering only for vector shifts!");
16963   assert(Subtarget->hasSSE2() && "Only custom lower when we have SSE2!");
16964
16965   if (SDValue V = LowerScalarImmediateShift(Op, DAG, Subtarget))
16966     return V;
16967
16968   if (SDValue V = LowerScalarVariableShift(Op, DAG, Subtarget))
16969       return V;
16970
16971   if (SupportedVectorVarShift(VT, Subtarget, Op.getOpcode()))
16972     return Op;
16973
16974   // 2i64 vector logical shifts can efficiently avoid scalarization - do the
16975   // shifts per-lane and then shuffle the partial results back together.
16976   if (VT == MVT::v2i64 && Op.getOpcode() != ISD::SRA) {
16977     // Splat the shift amounts so the scalar shifts above will catch it.
16978     SDValue Amt0 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {0, 0});
16979     SDValue Amt1 = DAG.getVectorShuffle(VT, dl, Amt, Amt, {1, 1});
16980     SDValue R0 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt0);
16981     SDValue R1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Amt1);
16982     return DAG.getVectorShuffle(VT, dl, R0, R1, {0, 3});
16983   }
16984
16985   // If possible, lower this packed shift into a vector multiply instead of
16986   // expanding it into a sequence of scalar shifts.
16987   // Do this only if the vector shift count is a constant build_vector.
16988   if (Op.getOpcode() == ISD::SHL &&
16989       (VT == MVT::v8i16 || VT == MVT::v4i32 ||
16990        (Subtarget->hasInt256() && VT == MVT::v16i16)) &&
16991       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
16992     SmallVector<SDValue, 8> Elts;
16993     EVT SVT = VT.getScalarType();
16994     unsigned SVTBits = SVT.getSizeInBits();
16995     const APInt &One = APInt(SVTBits, 1);
16996     unsigned NumElems = VT.getVectorNumElements();
16997
16998     for (unsigned i=0; i !=NumElems; ++i) {
16999       SDValue Op = Amt->getOperand(i);
17000       if (Op->getOpcode() == ISD::UNDEF) {
17001         Elts.push_back(Op);
17002         continue;
17003       }
17004
17005       ConstantSDNode *ND = cast<ConstantSDNode>(Op);
17006       const APInt &C = APInt(SVTBits, ND->getAPIntValue().getZExtValue());
17007       uint64_t ShAmt = C.getZExtValue();
17008       if (ShAmt >= SVTBits) {
17009         Elts.push_back(DAG.getUNDEF(SVT));
17010         continue;
17011       }
17012       Elts.push_back(DAG.getConstant(One.shl(ShAmt), dl, SVT));
17013     }
17014     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Elts);
17015     return DAG.getNode(ISD::MUL, dl, VT, R, BV);
17016   }
17017
17018   // Lower SHL with variable shift amount.
17019   if (VT == MVT::v4i32 && Op->getOpcode() == ISD::SHL) {
17020     Op = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(23, dl, VT));
17021
17022     Op = DAG.getNode(ISD::ADD, dl, VT, Op,
17023                      DAG.getConstant(0x3f800000U, dl, VT));
17024     Op = DAG.getBitcast(MVT::v4f32, Op);
17025     Op = DAG.getNode(ISD::FP_TO_SINT, dl, VT, Op);
17026     return DAG.getNode(ISD::MUL, dl, VT, Op, R);
17027   }
17028
17029   // If possible, lower this shift as a sequence of two shifts by
17030   // constant plus a MOVSS/MOVSD instead of scalarizing it.
17031   // Example:
17032   //   (v4i32 (srl A, (build_vector < X, Y, Y, Y>)))
17033   //
17034   // Could be rewritten as:
17035   //   (v4i32 (MOVSS (srl A, <Y,Y,Y,Y>), (srl A, <X,X,X,X>)))
17036   //
17037   // The advantage is that the two shifts from the example would be
17038   // lowered as X86ISD::VSRLI nodes. This would be cheaper than scalarizing
17039   // the vector shift into four scalar shifts plus four pairs of vector
17040   // insert/extract.
17041   if ((VT == MVT::v8i16 || VT == MVT::v4i32) &&
17042       ISD::isBuildVectorOfConstantSDNodes(Amt.getNode())) {
17043     unsigned TargetOpcode = X86ISD::MOVSS;
17044     bool CanBeSimplified;
17045     // The splat value for the first packed shift (the 'X' from the example).
17046     SDValue Amt1 = Amt->getOperand(0);
17047     // The splat value for the second packed shift (the 'Y' from the example).
17048     SDValue Amt2 = (VT == MVT::v4i32) ? Amt->getOperand(1) :
17049                                         Amt->getOperand(2);
17050
17051     // See if it is possible to replace this node with a sequence of
17052     // two shifts followed by a MOVSS/MOVSD
17053     if (VT == MVT::v4i32) {
17054       // Check if it is legal to use a MOVSS.
17055       CanBeSimplified = Amt2 == Amt->getOperand(2) &&
17056                         Amt2 == Amt->getOperand(3);
17057       if (!CanBeSimplified) {
17058         // Otherwise, check if we can still simplify this node using a MOVSD.
17059         CanBeSimplified = Amt1 == Amt->getOperand(1) &&
17060                           Amt->getOperand(2) == Amt->getOperand(3);
17061         TargetOpcode = X86ISD::MOVSD;
17062         Amt2 = Amt->getOperand(2);
17063       }
17064     } else {
17065       // Do similar checks for the case where the machine value type
17066       // is MVT::v8i16.
17067       CanBeSimplified = Amt1 == Amt->getOperand(1);
17068       for (unsigned i=3; i != 8 && CanBeSimplified; ++i)
17069         CanBeSimplified = Amt2 == Amt->getOperand(i);
17070
17071       if (!CanBeSimplified) {
17072         TargetOpcode = X86ISD::MOVSD;
17073         CanBeSimplified = true;
17074         Amt2 = Amt->getOperand(4);
17075         for (unsigned i=0; i != 4 && CanBeSimplified; ++i)
17076           CanBeSimplified = Amt1 == Amt->getOperand(i);
17077         for (unsigned j=4; j != 8 && CanBeSimplified; ++j)
17078           CanBeSimplified = Amt2 == Amt->getOperand(j);
17079       }
17080     }
17081
17082     if (CanBeSimplified && isa<ConstantSDNode>(Amt1) &&
17083         isa<ConstantSDNode>(Amt2)) {
17084       // Replace this node with two shifts followed by a MOVSS/MOVSD.
17085       EVT CastVT = MVT::v4i32;
17086       SDValue Splat1 =
17087         DAG.getConstant(cast<ConstantSDNode>(Amt1)->getAPIntValue(), dl, VT);
17088       SDValue Shift1 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat1);
17089       SDValue Splat2 =
17090         DAG.getConstant(cast<ConstantSDNode>(Amt2)->getAPIntValue(), dl, VT);
17091       SDValue Shift2 = DAG.getNode(Op->getOpcode(), dl, VT, R, Splat2);
17092       if (TargetOpcode == X86ISD::MOVSD)
17093         CastVT = MVT::v2i64;
17094       SDValue BitCast1 = DAG.getBitcast(CastVT, Shift1);
17095       SDValue BitCast2 = DAG.getBitcast(CastVT, Shift2);
17096       SDValue Result = getTargetShuffleNode(TargetOpcode, dl, CastVT, BitCast2,
17097                                             BitCast1, DAG);
17098       return DAG.getBitcast(VT, Result);
17099     }
17100   }
17101
17102   if (VT == MVT::v16i8 || (VT == MVT::v32i8 && Subtarget->hasInt256())) {
17103     MVT ExtVT = MVT::getVectorVT(MVT::i16, VT.getVectorNumElements() / 2);
17104     unsigned ShiftOpcode = Op->getOpcode();
17105
17106     auto SignBitSelect = [&](MVT SelVT, SDValue Sel, SDValue V0, SDValue V1) {
17107       // On SSE41 targets we make use of the fact that VSELECT lowers
17108       // to PBLENDVB which selects bytes based just on the sign bit.
17109       if (Subtarget->hasSSE41()) {
17110         V0 = DAG.getBitcast(VT, V0);
17111         V1 = DAG.getBitcast(VT, V1);
17112         Sel = DAG.getBitcast(VT, Sel);
17113         return DAG.getBitcast(SelVT,
17114                               DAG.getNode(ISD::VSELECT, dl, VT, Sel, V0, V1));
17115       }
17116       // On pre-SSE41 targets we test for the sign bit by comparing to
17117       // zero - a negative value will set all bits of the lanes to true
17118       // and VSELECT uses that in its OR(AND(V0,C),AND(V1,~C)) lowering.
17119       SDValue Z = getZeroVector(SelVT, Subtarget, DAG, dl);
17120       SDValue C = DAG.getNode(X86ISD::PCMPGT, dl, SelVT, Z, Sel);
17121       return DAG.getNode(ISD::VSELECT, dl, SelVT, C, V0, V1);
17122     };
17123
17124     // Turn 'a' into a mask suitable for VSELECT: a = a << 5;
17125     // We can safely do this using i16 shifts as we're only interested in
17126     // the 3 lower bits of each byte.
17127     Amt = DAG.getBitcast(ExtVT, Amt);
17128     Amt = DAG.getNode(ISD::SHL, dl, ExtVT, Amt, DAG.getConstant(5, dl, ExtVT));
17129     Amt = DAG.getBitcast(VT, Amt);
17130
17131     if (Op->getOpcode() == ISD::SHL || Op->getOpcode() == ISD::SRL) {
17132       // r = VSELECT(r, shift(r, 4), a);
17133       SDValue M =
17134           DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17135       R = SignBitSelect(VT, Amt, M, R);
17136
17137       // a += a
17138       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17139
17140       // r = VSELECT(r, shift(r, 2), a);
17141       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17142       R = SignBitSelect(VT, Amt, M, R);
17143
17144       // a += a
17145       Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17146
17147       // return VSELECT(r, shift(r, 1), a);
17148       M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17149       R = SignBitSelect(VT, Amt, M, R);
17150       return R;
17151     }
17152
17153     if (Op->getOpcode() == ISD::SRA) {
17154       // For SRA we need to unpack each byte to the higher byte of a i16 vector
17155       // so we can correctly sign extend. We don't care what happens to the
17156       // lower byte.
17157       SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), Amt);
17158       SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), Amt);
17159       SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, DAG.getUNDEF(VT), R);
17160       SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, DAG.getUNDEF(VT), R);
17161       ALo = DAG.getBitcast(ExtVT, ALo);
17162       AHi = DAG.getBitcast(ExtVT, AHi);
17163       RLo = DAG.getBitcast(ExtVT, RLo);
17164       RHi = DAG.getBitcast(ExtVT, RHi);
17165
17166       // r = VSELECT(r, shift(r, 4), a);
17167       SDValue MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17168                                 DAG.getConstant(4, dl, ExtVT));
17169       SDValue MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17170                                 DAG.getConstant(4, dl, ExtVT));
17171       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17172       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17173
17174       // a += a
17175       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17176       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17177
17178       // r = VSELECT(r, shift(r, 2), a);
17179       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17180                         DAG.getConstant(2, dl, ExtVT));
17181       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17182                         DAG.getConstant(2, dl, ExtVT));
17183       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17184       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17185
17186       // a += a
17187       ALo = DAG.getNode(ISD::ADD, dl, ExtVT, ALo, ALo);
17188       AHi = DAG.getNode(ISD::ADD, dl, ExtVT, AHi, AHi);
17189
17190       // r = VSELECT(r, shift(r, 1), a);
17191       MLo = DAG.getNode(ShiftOpcode, dl, ExtVT, RLo,
17192                         DAG.getConstant(1, dl, ExtVT));
17193       MHi = DAG.getNode(ShiftOpcode, dl, ExtVT, RHi,
17194                         DAG.getConstant(1, dl, ExtVT));
17195       RLo = SignBitSelect(ExtVT, ALo, MLo, RLo);
17196       RHi = SignBitSelect(ExtVT, AHi, MHi, RHi);
17197
17198       // Logical shift the result back to the lower byte, leaving a zero upper
17199       // byte
17200       // meaning that we can safely pack with PACKUSWB.
17201       RLo =
17202           DAG.getNode(ISD::SRL, dl, ExtVT, RLo, DAG.getConstant(8, dl, ExtVT));
17203       RHi =
17204           DAG.getNode(ISD::SRL, dl, ExtVT, RHi, DAG.getConstant(8, dl, ExtVT));
17205       return DAG.getNode(X86ISD::PACKUS, dl, VT, RLo, RHi);
17206     }
17207   }
17208
17209   // It's worth extending once and using the v8i32 shifts for 16-bit types, but
17210   // the extra overheads to get from v16i8 to v8i32 make the existing SSE
17211   // solution better.
17212   if (Subtarget->hasInt256() && VT == MVT::v8i16) {
17213     MVT ExtVT = MVT::v8i32;
17214     unsigned ExtOpc =
17215         Op.getOpcode() == ISD::SRA ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
17216     R = DAG.getNode(ExtOpc, dl, ExtVT, R);
17217     Amt = DAG.getNode(ISD::ANY_EXTEND, dl, ExtVT, Amt);
17218     return DAG.getNode(ISD::TRUNCATE, dl, VT,
17219                        DAG.getNode(Op.getOpcode(), dl, ExtVT, R, Amt));
17220   }
17221
17222   if (Subtarget->hasInt256() && VT == MVT::v16i16) {
17223     MVT ExtVT = MVT::v8i32;
17224     SDValue Z = getZeroVector(VT, Subtarget, DAG, dl);
17225     SDValue ALo = DAG.getNode(X86ISD::UNPCKL, dl, VT, Amt, Z);
17226     SDValue AHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, Amt, Z);
17227     SDValue RLo = DAG.getNode(X86ISD::UNPCKL, dl, VT, R, R);
17228     SDValue RHi = DAG.getNode(X86ISD::UNPCKH, dl, VT, R, R);
17229     ALo = DAG.getBitcast(ExtVT, ALo);
17230     AHi = DAG.getBitcast(ExtVT, AHi);
17231     RLo = DAG.getBitcast(ExtVT, RLo);
17232     RHi = DAG.getBitcast(ExtVT, RHi);
17233     SDValue Lo = DAG.getNode(Op.getOpcode(), dl, ExtVT, RLo, ALo);
17234     SDValue Hi = DAG.getNode(Op.getOpcode(), dl, ExtVT, RHi, AHi);
17235     Lo = DAG.getNode(ISD::SRL, dl, ExtVT, Lo, DAG.getConstant(16, dl, ExtVT));
17236     Hi = DAG.getNode(ISD::SRL, dl, ExtVT, Hi, DAG.getConstant(16, dl, ExtVT));
17237     return DAG.getNode(X86ISD::PACKUS, dl, VT, Lo, Hi);
17238   }
17239
17240   if (VT == MVT::v8i16) {
17241     unsigned ShiftOpcode = Op->getOpcode();
17242
17243     auto SignBitSelect = [&](SDValue Sel, SDValue V0, SDValue V1) {
17244       // On SSE41 targets we make use of the fact that VSELECT lowers
17245       // to PBLENDVB which selects bytes based just on the sign bit.
17246       if (Subtarget->hasSSE41()) {
17247         MVT ExtVT = MVT::getVectorVT(MVT::i8, VT.getVectorNumElements() * 2);
17248         V0 = DAG.getBitcast(ExtVT, V0);
17249         V1 = DAG.getBitcast(ExtVT, V1);
17250         Sel = DAG.getBitcast(ExtVT, Sel);
17251         return DAG.getBitcast(
17252             VT, DAG.getNode(ISD::VSELECT, dl, ExtVT, Sel, V0, V1));
17253       }
17254       // On pre-SSE41 targets we splat the sign bit - a negative value will
17255       // set all bits of the lanes to true and VSELECT uses that in
17256       // its OR(AND(V0,C),AND(V1,~C)) lowering.
17257       SDValue C =
17258           DAG.getNode(ISD::SRA, dl, VT, Sel, DAG.getConstant(15, dl, VT));
17259       return DAG.getNode(ISD::VSELECT, dl, VT, C, V0, V1);
17260     };
17261
17262     // Turn 'a' into a mask suitable for VSELECT: a = a << 12;
17263     if (Subtarget->hasSSE41()) {
17264       // On SSE41 targets we need to replicate the shift mask in both
17265       // bytes for PBLENDVB.
17266       Amt = DAG.getNode(
17267           ISD::OR, dl, VT,
17268           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(4, dl, VT)),
17269           DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT)));
17270     } else {
17271       Amt = DAG.getNode(ISD::SHL, dl, VT, Amt, DAG.getConstant(12, dl, VT));
17272     }
17273
17274     // r = VSELECT(r, shift(r, 8), a);
17275     SDValue M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(8, dl, VT));
17276     R = SignBitSelect(Amt, M, R);
17277
17278     // a += a
17279     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17280
17281     // r = VSELECT(r, shift(r, 4), a);
17282     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(4, dl, VT));
17283     R = SignBitSelect(Amt, M, R);
17284
17285     // a += a
17286     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17287
17288     // r = VSELECT(r, shift(r, 2), a);
17289     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(2, dl, VT));
17290     R = SignBitSelect(Amt, M, R);
17291
17292     // a += a
17293     Amt = DAG.getNode(ISD::ADD, dl, VT, Amt, Amt);
17294
17295     // return VSELECT(r, shift(r, 1), a);
17296     M = DAG.getNode(ShiftOpcode, dl, VT, R, DAG.getConstant(1, dl, VT));
17297     R = SignBitSelect(Amt, M, R);
17298     return R;
17299   }
17300
17301   // Decompose 256-bit shifts into smaller 128-bit shifts.
17302   if (VT.is256BitVector()) {
17303     unsigned NumElems = VT.getVectorNumElements();
17304     MVT EltVT = VT.getVectorElementType();
17305     EVT NewVT = MVT::getVectorVT(EltVT, NumElems/2);
17306
17307     // Extract the two vectors
17308     SDValue V1 = Extract128BitVector(R, 0, DAG, dl);
17309     SDValue V2 = Extract128BitVector(R, NumElems/2, DAG, dl);
17310
17311     // Recreate the shift amount vectors
17312     SDValue Amt1, Amt2;
17313     if (Amt.getOpcode() == ISD::BUILD_VECTOR) {
17314       // Constant shift amount
17315       SmallVector<SDValue, 8> Ops(Amt->op_begin(), Amt->op_begin() + NumElems);
17316       ArrayRef<SDValue> Amt1Csts = makeArrayRef(Ops).slice(0, NumElems / 2);
17317       ArrayRef<SDValue> Amt2Csts = makeArrayRef(Ops).slice(NumElems / 2);
17318
17319       Amt1 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt1Csts);
17320       Amt2 = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Amt2Csts);
17321     } else {
17322       // Variable shift amount
17323       Amt1 = Extract128BitVector(Amt, 0, DAG, dl);
17324       Amt2 = Extract128BitVector(Amt, NumElems/2, DAG, dl);
17325     }
17326
17327     // Issue new vector shifts for the smaller types
17328     V1 = DAG.getNode(Op.getOpcode(), dl, NewVT, V1, Amt1);
17329     V2 = DAG.getNode(Op.getOpcode(), dl, NewVT, V2, Amt2);
17330
17331     // Concatenate the result back
17332     return DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, V1, V2);
17333   }
17334
17335   return SDValue();
17336 }
17337
17338 static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
17339   // Lower the "add/sub/mul with overflow" instruction into a regular ins plus
17340   // a "setcc" instruction that checks the overflow flag. The "brcond" lowering
17341   // looks for this combo and may remove the "setcc" instruction if the "setcc"
17342   // has only one use.
17343   SDNode *N = Op.getNode();
17344   SDValue LHS = N->getOperand(0);
17345   SDValue RHS = N->getOperand(1);
17346   unsigned BaseOp = 0;
17347   unsigned Cond = 0;
17348   SDLoc DL(Op);
17349   switch (Op.getOpcode()) {
17350   default: llvm_unreachable("Unknown ovf instruction!");
17351   case ISD::SADDO:
17352     // A subtract of one will be selected as a INC. Note that INC doesn't
17353     // set CF, so we can't do this for UADDO.
17354     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17355       if (C->isOne()) {
17356         BaseOp = X86ISD::INC;
17357         Cond = X86::COND_O;
17358         break;
17359       }
17360     BaseOp = X86ISD::ADD;
17361     Cond = X86::COND_O;
17362     break;
17363   case ISD::UADDO:
17364     BaseOp = X86ISD::ADD;
17365     Cond = X86::COND_B;
17366     break;
17367   case ISD::SSUBO:
17368     // A subtract of one will be selected as a DEC. Note that DEC doesn't
17369     // set CF, so we can't do this for USUBO.
17370     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS))
17371       if (C->isOne()) {
17372         BaseOp = X86ISD::DEC;
17373         Cond = X86::COND_O;
17374         break;
17375       }
17376     BaseOp = X86ISD::SUB;
17377     Cond = X86::COND_O;
17378     break;
17379   case ISD::USUBO:
17380     BaseOp = X86ISD::SUB;
17381     Cond = X86::COND_B;
17382     break;
17383   case ISD::SMULO:
17384     BaseOp = N->getValueType(0) == MVT::i8 ? X86ISD::SMUL8 : X86ISD::SMUL;
17385     Cond = X86::COND_O;
17386     break;
17387   case ISD::UMULO: { // i64, i8 = umulo lhs, rhs --> i64, i64, i32 umul lhs,rhs
17388     if (N->getValueType(0) == MVT::i8) {
17389       BaseOp = X86ISD::UMUL8;
17390       Cond = X86::COND_O;
17391       break;
17392     }
17393     SDVTList VTs = DAG.getVTList(N->getValueType(0), N->getValueType(0),
17394                                  MVT::i32);
17395     SDValue Sum = DAG.getNode(X86ISD::UMUL, DL, VTs, LHS, RHS);
17396
17397     SDValue SetCC =
17398       DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
17399                   DAG.getConstant(X86::COND_O, DL, MVT::i32),
17400                   SDValue(Sum.getNode(), 2));
17401
17402     return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17403   }
17404   }
17405
17406   // Also sets EFLAGS.
17407   SDVTList VTs = DAG.getVTList(N->getValueType(0), MVT::i32);
17408   SDValue Sum = DAG.getNode(BaseOp, DL, VTs, LHS, RHS);
17409
17410   SDValue SetCC =
17411     DAG.getNode(X86ISD::SETCC, DL, N->getValueType(1),
17412                 DAG.getConstant(Cond, DL, MVT::i32),
17413                 SDValue(Sum.getNode(), 1));
17414
17415   return DAG.getNode(ISD::MERGE_VALUES, DL, N->getVTList(), Sum, SetCC);
17416 }
17417
17418 /// Returns true if the operand type is exactly twice the native width, and
17419 /// the corresponding cmpxchg8b or cmpxchg16b instruction is available.
17420 /// Used to know whether to use cmpxchg8/16b when expanding atomic operations
17421 /// (otherwise we leave them alone to become __sync_fetch_and_... calls).
17422 bool X86TargetLowering::needsCmpXchgNb(const Type *MemType) const {
17423   unsigned OpWidth = MemType->getPrimitiveSizeInBits();
17424
17425   if (OpWidth == 64)
17426     return !Subtarget->is64Bit(); // FIXME this should be Subtarget.hasCmpxchg8b
17427   else if (OpWidth == 128)
17428     return Subtarget->hasCmpxchg16b();
17429   else
17430     return false;
17431 }
17432
17433 bool X86TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
17434   return needsCmpXchgNb(SI->getValueOperand()->getType());
17435 }
17436
17437 // Note: this turns large loads into lock cmpxchg8b/16b.
17438 // FIXME: On 32 bits x86, fild/movq might be faster than lock cmpxchg8b.
17439 bool X86TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
17440   auto PTy = cast<PointerType>(LI->getPointerOperand()->getType());
17441   return needsCmpXchgNb(PTy->getElementType());
17442 }
17443
17444 TargetLoweringBase::AtomicRMWExpansionKind
17445 X86TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
17446   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17447   const Type *MemType = AI->getType();
17448
17449   // If the operand is too big, we must see if cmpxchg8/16b is available
17450   // and default to library calls otherwise.
17451   if (MemType->getPrimitiveSizeInBits() > NativeWidth) {
17452     return needsCmpXchgNb(MemType) ? AtomicRMWExpansionKind::CmpXChg
17453                                    : AtomicRMWExpansionKind::None;
17454   }
17455
17456   AtomicRMWInst::BinOp Op = AI->getOperation();
17457   switch (Op) {
17458   default:
17459     llvm_unreachable("Unknown atomic operation");
17460   case AtomicRMWInst::Xchg:
17461   case AtomicRMWInst::Add:
17462   case AtomicRMWInst::Sub:
17463     // It's better to use xadd, xsub or xchg for these in all cases.
17464     return AtomicRMWExpansionKind::None;
17465   case AtomicRMWInst::Or:
17466   case AtomicRMWInst::And:
17467   case AtomicRMWInst::Xor:
17468     // If the atomicrmw's result isn't actually used, we can just add a "lock"
17469     // prefix to a normal instruction for these operations.
17470     return !AI->use_empty() ? AtomicRMWExpansionKind::CmpXChg
17471                             : AtomicRMWExpansionKind::None;
17472   case AtomicRMWInst::Nand:
17473   case AtomicRMWInst::Max:
17474   case AtomicRMWInst::Min:
17475   case AtomicRMWInst::UMax:
17476   case AtomicRMWInst::UMin:
17477     // These always require a non-trivial set of data operations on x86. We must
17478     // use a cmpxchg loop.
17479     return AtomicRMWExpansionKind::CmpXChg;
17480   }
17481 }
17482
17483 static bool hasMFENCE(const X86Subtarget& Subtarget) {
17484   // Use mfence if we have SSE2 or we're on x86-64 (even if we asked for
17485   // no-sse2). There isn't any reason to disable it if the target processor
17486   // supports it.
17487   return Subtarget.hasSSE2() || Subtarget.is64Bit();
17488 }
17489
17490 LoadInst *
17491 X86TargetLowering::lowerIdempotentRMWIntoFencedLoad(AtomicRMWInst *AI) const {
17492   unsigned NativeWidth = Subtarget->is64Bit() ? 64 : 32;
17493   const Type *MemType = AI->getType();
17494   // Accesses larger than the native width are turned into cmpxchg/libcalls, so
17495   // there is no benefit in turning such RMWs into loads, and it is actually
17496   // harmful as it introduces a mfence.
17497   if (MemType->getPrimitiveSizeInBits() > NativeWidth)
17498     return nullptr;
17499
17500   auto Builder = IRBuilder<>(AI);
17501   Module *M = Builder.GetInsertBlock()->getParent()->getParent();
17502   auto SynchScope = AI->getSynchScope();
17503   // We must restrict the ordering to avoid generating loads with Release or
17504   // ReleaseAcquire orderings.
17505   auto Order = AtomicCmpXchgInst::getStrongestFailureOrdering(AI->getOrdering());
17506   auto Ptr = AI->getPointerOperand();
17507
17508   // Before the load we need a fence. Here is an example lifted from
17509   // http://www.hpl.hp.com/techreports/2012/HPL-2012-68.pdf showing why a fence
17510   // is required:
17511   // Thread 0:
17512   //   x.store(1, relaxed);
17513   //   r1 = y.fetch_add(0, release);
17514   // Thread 1:
17515   //   y.fetch_add(42, acquire);
17516   //   r2 = x.load(relaxed);
17517   // r1 = r2 = 0 is impossible, but becomes possible if the idempotent rmw is
17518   // lowered to just a load without a fence. A mfence flushes the store buffer,
17519   // making the optimization clearly correct.
17520   // FIXME: it is required if isAtLeastRelease(Order) but it is not clear
17521   // otherwise, we might be able to be more agressive on relaxed idempotent
17522   // rmw. In practice, they do not look useful, so we don't try to be
17523   // especially clever.
17524   if (SynchScope == SingleThread)
17525     // FIXME: we could just insert an X86ISD::MEMBARRIER here, except we are at
17526     // the IR level, so we must wrap it in an intrinsic.
17527     return nullptr;
17528
17529   if (!hasMFENCE(*Subtarget))
17530     // FIXME: it might make sense to use a locked operation here but on a
17531     // different cache-line to prevent cache-line bouncing. In practice it
17532     // is probably a small win, and x86 processors without mfence are rare
17533     // enough that we do not bother.
17534     return nullptr;
17535
17536   Function *MFence =
17537       llvm::Intrinsic::getDeclaration(M, Intrinsic::x86_sse2_mfence);
17538   Builder.CreateCall(MFence, {});
17539
17540   // Finally we can emit the atomic load.
17541   LoadInst *Loaded = Builder.CreateAlignedLoad(Ptr,
17542           AI->getType()->getPrimitiveSizeInBits());
17543   Loaded->setAtomic(Order, SynchScope);
17544   AI->replaceAllUsesWith(Loaded);
17545   AI->eraseFromParent();
17546   return Loaded;
17547 }
17548
17549 static SDValue LowerATOMIC_FENCE(SDValue Op, const X86Subtarget *Subtarget,
17550                                  SelectionDAG &DAG) {
17551   SDLoc dl(Op);
17552   AtomicOrdering FenceOrdering = static_cast<AtomicOrdering>(
17553     cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
17554   SynchronizationScope FenceScope = static_cast<SynchronizationScope>(
17555     cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
17556
17557   // The only fence that needs an instruction is a sequentially-consistent
17558   // cross-thread fence.
17559   if (FenceOrdering == SequentiallyConsistent && FenceScope == CrossThread) {
17560     if (hasMFENCE(*Subtarget))
17561       return DAG.getNode(X86ISD::MFENCE, dl, MVT::Other, Op.getOperand(0));
17562
17563     SDValue Chain = Op.getOperand(0);
17564     SDValue Zero = DAG.getConstant(0, dl, MVT::i32);
17565     SDValue Ops[] = {
17566       DAG.getRegister(X86::ESP, MVT::i32),     // Base
17567       DAG.getTargetConstant(1, dl, MVT::i8),   // Scale
17568       DAG.getRegister(0, MVT::i32),            // Index
17569       DAG.getTargetConstant(0, dl, MVT::i32),  // Disp
17570       DAG.getRegister(0, MVT::i32),            // Segment.
17571       Zero,
17572       Chain
17573     };
17574     SDNode *Res = DAG.getMachineNode(X86::OR32mrLocked, dl, MVT::Other, Ops);
17575     return SDValue(Res, 0);
17576   }
17577
17578   // MEMBARRIER is a compiler barrier; it codegens to a no-op.
17579   return DAG.getNode(X86ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
17580 }
17581
17582 static SDValue LowerCMP_SWAP(SDValue Op, const X86Subtarget *Subtarget,
17583                              SelectionDAG &DAG) {
17584   MVT T = Op.getSimpleValueType();
17585   SDLoc DL(Op);
17586   unsigned Reg = 0;
17587   unsigned size = 0;
17588   switch(T.SimpleTy) {
17589   default: llvm_unreachable("Invalid value type!");
17590   case MVT::i8:  Reg = X86::AL;  size = 1; break;
17591   case MVT::i16: Reg = X86::AX;  size = 2; break;
17592   case MVT::i32: Reg = X86::EAX; size = 4; break;
17593   case MVT::i64:
17594     assert(Subtarget->is64Bit() && "Node not type legal!");
17595     Reg = X86::RAX; size = 8;
17596     break;
17597   }
17598   SDValue cpIn = DAG.getCopyToReg(Op.getOperand(0), DL, Reg,
17599                                   Op.getOperand(2), SDValue());
17600   SDValue Ops[] = { cpIn.getValue(0),
17601                     Op.getOperand(1),
17602                     Op.getOperand(3),
17603                     DAG.getTargetConstant(size, DL, MVT::i8),
17604                     cpIn.getValue(1) };
17605   SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
17606   MachineMemOperand *MMO = cast<AtomicSDNode>(Op)->getMemOperand();
17607   SDValue Result = DAG.getMemIntrinsicNode(X86ISD::LCMPXCHG_DAG, DL, Tys,
17608                                            Ops, T, MMO);
17609
17610   SDValue cpOut =
17611     DAG.getCopyFromReg(Result.getValue(0), DL, Reg, T, Result.getValue(1));
17612   SDValue EFLAGS = DAG.getCopyFromReg(cpOut.getValue(1), DL, X86::EFLAGS,
17613                                       MVT::i32, cpOut.getValue(2));
17614   SDValue Success = DAG.getNode(X86ISD::SETCC, DL, Op->getValueType(1),
17615                                 DAG.getConstant(X86::COND_E, DL, MVT::i8),
17616                                 EFLAGS);
17617
17618   DAG.ReplaceAllUsesOfValueWith(Op.getValue(0), cpOut);
17619   DAG.ReplaceAllUsesOfValueWith(Op.getValue(1), Success);
17620   DAG.ReplaceAllUsesOfValueWith(Op.getValue(2), EFLAGS.getValue(1));
17621   return SDValue();
17622 }
17623
17624 static SDValue LowerBITCAST(SDValue Op, const X86Subtarget *Subtarget,
17625                             SelectionDAG &DAG) {
17626   MVT SrcVT = Op.getOperand(0).getSimpleValueType();
17627   MVT DstVT = Op.getSimpleValueType();
17628
17629   if (SrcVT == MVT::v2i32 || SrcVT == MVT::v4i16 || SrcVT == MVT::v8i8) {
17630     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
17631     if (DstVT != MVT::f64)
17632       // This conversion needs to be expanded.
17633       return SDValue();
17634
17635     SDValue InVec = Op->getOperand(0);
17636     SDLoc dl(Op);
17637     unsigned NumElts = SrcVT.getVectorNumElements();
17638     EVT SVT = SrcVT.getVectorElementType();
17639
17640     // Widen the vector in input in the case of MVT::v2i32.
17641     // Example: from MVT::v2i32 to MVT::v4i32.
17642     SmallVector<SDValue, 16> Elts;
17643     for (unsigned i = 0, e = NumElts; i != e; ++i)
17644       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT, InVec,
17645                                  DAG.getIntPtrConstant(i, dl)));
17646
17647     // Explicitly mark the extra elements as Undef.
17648     Elts.append(NumElts, DAG.getUNDEF(SVT));
17649
17650     EVT NewVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
17651     SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NewVT, Elts);
17652     SDValue ToV2F64 = DAG.getBitcast(MVT::v2f64, BV);
17653     return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64, ToV2F64,
17654                        DAG.getIntPtrConstant(0, dl));
17655   }
17656
17657   assert(Subtarget->is64Bit() && !Subtarget->hasSSE2() &&
17658          Subtarget->hasMMX() && "Unexpected custom BITCAST");
17659   assert((DstVT == MVT::i64 ||
17660           (DstVT.isVector() && DstVT.getSizeInBits()==64)) &&
17661          "Unexpected custom BITCAST");
17662   // i64 <=> MMX conversions are Legal.
17663   if (SrcVT==MVT::i64 && DstVT.isVector())
17664     return Op;
17665   if (DstVT==MVT::i64 && SrcVT.isVector())
17666     return Op;
17667   // MMX <=> MMX conversions are Legal.
17668   if (SrcVT.isVector() && DstVT.isVector())
17669     return Op;
17670   // All other conversions need to be expanded.
17671   return SDValue();
17672 }
17673
17674 /// Compute the horizontal sum of bytes in V for the elements of VT.
17675 ///
17676 /// Requires V to be a byte vector and VT to be an integer vector type with
17677 /// wider elements than V's type. The width of the elements of VT determines
17678 /// how many bytes of V are summed horizontally to produce each element of the
17679 /// result.
17680 static SDValue LowerHorizontalByteSum(SDValue V, MVT VT,
17681                                       const X86Subtarget *Subtarget,
17682                                       SelectionDAG &DAG) {
17683   SDLoc DL(V);
17684   MVT ByteVecVT = V.getSimpleValueType();
17685   MVT EltVT = VT.getVectorElementType();
17686   int NumElts = VT.getVectorNumElements();
17687   assert(ByteVecVT.getVectorElementType() == MVT::i8 &&
17688          "Expected value to have byte element type.");
17689   assert(EltVT != MVT::i8 &&
17690          "Horizontal byte sum only makes sense for wider elements!");
17691   unsigned VecSize = VT.getSizeInBits();
17692   assert(ByteVecVT.getSizeInBits() == VecSize && "Cannot change vector size!");
17693
17694   // PSADBW instruction horizontally add all bytes and leave the result in i64
17695   // chunks, thus directly computes the pop count for v2i64 and v4i64.
17696   if (EltVT == MVT::i64) {
17697     SDValue Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17698     V = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT, V, Zeros);
17699     return DAG.getBitcast(VT, V);
17700   }
17701
17702   if (EltVT == MVT::i32) {
17703     // We unpack the low half and high half into i32s interleaved with zeros so
17704     // that we can use PSADBW to horizontally sum them. The most useful part of
17705     // this is that it lines up the results of two PSADBW instructions to be
17706     // two v2i64 vectors which concatenated are the 4 population counts. We can
17707     // then use PACKUSWB to shrink and concatenate them into a v4i32 again.
17708     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, DL);
17709     SDValue Low = DAG.getNode(X86ISD::UNPCKL, DL, VT, V, Zeros);
17710     SDValue High = DAG.getNode(X86ISD::UNPCKH, DL, VT, V, Zeros);
17711
17712     // Do the horizontal sums into two v2i64s.
17713     Zeros = getZeroVector(ByteVecVT, Subtarget, DAG, DL);
17714     Low = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17715                       DAG.getBitcast(ByteVecVT, Low), Zeros);
17716     High = DAG.getNode(X86ISD::PSADBW, DL, ByteVecVT,
17717                        DAG.getBitcast(ByteVecVT, High), Zeros);
17718
17719     // Merge them together.
17720     MVT ShortVecVT = MVT::getVectorVT(MVT::i16, VecSize / 16);
17721     V = DAG.getNode(X86ISD::PACKUS, DL, ByteVecVT,
17722                     DAG.getBitcast(ShortVecVT, Low),
17723                     DAG.getBitcast(ShortVecVT, High));
17724
17725     return DAG.getBitcast(VT, V);
17726   }
17727
17728   // The only element type left is i16.
17729   assert(EltVT == MVT::i16 && "Unknown how to handle type");
17730
17731   // To obtain pop count for each i16 element starting from the pop count for
17732   // i8 elements, shift the i16s left by 8, sum as i8s, and then shift as i16s
17733   // right by 8. It is important to shift as i16s as i8 vector shift isn't
17734   // directly supported.
17735   SmallVector<SDValue, 16> Shifters(NumElts, DAG.getConstant(8, DL, EltVT));
17736   SDValue Shifter = DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters);
17737   SDValue Shl = DAG.getNode(ISD::SHL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17738   V = DAG.getNode(ISD::ADD, DL, ByteVecVT, DAG.getBitcast(ByteVecVT, Shl),
17739                   DAG.getBitcast(ByteVecVT, V));
17740   return DAG.getNode(ISD::SRL, DL, VT, DAG.getBitcast(VT, V), Shifter);
17741 }
17742
17743 static SDValue LowerVectorCTPOPInRegLUT(SDValue Op, SDLoc DL,
17744                                         const X86Subtarget *Subtarget,
17745                                         SelectionDAG &DAG) {
17746   MVT VT = Op.getSimpleValueType();
17747   MVT EltVT = VT.getVectorElementType();
17748   unsigned VecSize = VT.getSizeInBits();
17749
17750   // Implement a lookup table in register by using an algorithm based on:
17751   // http://wm.ite.pl/articles/sse-popcount.html
17752   //
17753   // The general idea is that every lower byte nibble in the input vector is an
17754   // index into a in-register pre-computed pop count table. We then split up the
17755   // input vector in two new ones: (1) a vector with only the shifted-right
17756   // higher nibbles for each byte and (2) a vector with the lower nibbles (and
17757   // masked out higher ones) for each byte. PSHUB is used separately with both
17758   // to index the in-register table. Next, both are added and the result is a
17759   // i8 vector where each element contains the pop count for input byte.
17760   //
17761   // To obtain the pop count for elements != i8, we follow up with the same
17762   // approach and use additional tricks as described below.
17763   //
17764   const int LUT[16] = {/* 0 */ 0, /* 1 */ 1, /* 2 */ 1, /* 3 */ 2,
17765                        /* 4 */ 1, /* 5 */ 2, /* 6 */ 2, /* 7 */ 3,
17766                        /* 8 */ 1, /* 9 */ 2, /* a */ 2, /* b */ 3,
17767                        /* c */ 2, /* d */ 3, /* e */ 3, /* f */ 4};
17768
17769   int NumByteElts = VecSize / 8;
17770   MVT ByteVecVT = MVT::getVectorVT(MVT::i8, NumByteElts);
17771   SDValue In = DAG.getBitcast(ByteVecVT, Op);
17772   SmallVector<SDValue, 16> LUTVec;
17773   for (int i = 0; i < NumByteElts; ++i)
17774     LUTVec.push_back(DAG.getConstant(LUT[i % 16], DL, MVT::i8));
17775   SDValue InRegLUT = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, LUTVec);
17776   SmallVector<SDValue, 16> Mask0F(NumByteElts,
17777                                   DAG.getConstant(0x0F, DL, MVT::i8));
17778   SDValue M0F = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Mask0F);
17779
17780   // High nibbles
17781   SmallVector<SDValue, 16> Four(NumByteElts, DAG.getConstant(4, DL, MVT::i8));
17782   SDValue FourV = DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVecVT, Four);
17783   SDValue HighNibbles = DAG.getNode(ISD::SRL, DL, ByteVecVT, In, FourV);
17784
17785   // Low nibbles
17786   SDValue LowNibbles = DAG.getNode(ISD::AND, DL, ByteVecVT, In, M0F);
17787
17788   // The input vector is used as the shuffle mask that index elements into the
17789   // LUT. After counting low and high nibbles, add the vector to obtain the
17790   // final pop count per i8 element.
17791   SDValue HighPopCnt =
17792       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, HighNibbles);
17793   SDValue LowPopCnt =
17794       DAG.getNode(X86ISD::PSHUFB, DL, ByteVecVT, InRegLUT, LowNibbles);
17795   SDValue PopCnt = DAG.getNode(ISD::ADD, DL, ByteVecVT, HighPopCnt, LowPopCnt);
17796
17797   if (EltVT == MVT::i8)
17798     return PopCnt;
17799
17800   return LowerHorizontalByteSum(PopCnt, VT, Subtarget, DAG);
17801 }
17802
17803 static SDValue LowerVectorCTPOPBitmath(SDValue Op, SDLoc DL,
17804                                        const X86Subtarget *Subtarget,
17805                                        SelectionDAG &DAG) {
17806   MVT VT = Op.getSimpleValueType();
17807   assert(VT.is128BitVector() &&
17808          "Only 128-bit vector bitmath lowering supported.");
17809
17810   int VecSize = VT.getSizeInBits();
17811   MVT EltVT = VT.getVectorElementType();
17812   int Len = EltVT.getSizeInBits();
17813
17814   // This is the vectorized version of the "best" algorithm from
17815   // http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetParallel
17816   // with a minor tweak to use a series of adds + shifts instead of vector
17817   // multiplications. Implemented for all integer vector types. We only use
17818   // this when we don't have SSSE3 which allows a LUT-based lowering that is
17819   // much faster, even faster than using native popcnt instructions.
17820
17821   auto GetShift = [&](unsigned OpCode, SDValue V, int Shifter) {
17822     MVT VT = V.getSimpleValueType();
17823     SmallVector<SDValue, 32> Shifters(
17824         VT.getVectorNumElements(),
17825         DAG.getConstant(Shifter, DL, VT.getVectorElementType()));
17826     return DAG.getNode(OpCode, DL, VT, V,
17827                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Shifters));
17828   };
17829   auto GetMask = [&](SDValue V, APInt Mask) {
17830     MVT VT = V.getSimpleValueType();
17831     SmallVector<SDValue, 32> Masks(
17832         VT.getVectorNumElements(),
17833         DAG.getConstant(Mask, DL, VT.getVectorElementType()));
17834     return DAG.getNode(ISD::AND, DL, VT, V,
17835                        DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Masks));
17836   };
17837
17838   // We don't want to incur the implicit masks required to SRL vNi8 vectors on
17839   // x86, so set the SRL type to have elements at least i16 wide. This is
17840   // correct because all of our SRLs are followed immediately by a mask anyways
17841   // that handles any bits that sneak into the high bits of the byte elements.
17842   MVT SrlVT = Len > 8 ? VT : MVT::getVectorVT(MVT::i16, VecSize / 16);
17843
17844   SDValue V = Op;
17845
17846   // v = v - ((v >> 1) & 0x55555555...)
17847   SDValue Srl =
17848       DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 1));
17849   SDValue And = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x55)));
17850   V = DAG.getNode(ISD::SUB, DL, VT, V, And);
17851
17852   // v = (v & 0x33333333...) + ((v >> 2) & 0x33333333...)
17853   SDValue AndLHS = GetMask(V, APInt::getSplat(Len, APInt(8, 0x33)));
17854   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 2));
17855   SDValue AndRHS = GetMask(Srl, APInt::getSplat(Len, APInt(8, 0x33)));
17856   V = DAG.getNode(ISD::ADD, DL, VT, AndLHS, AndRHS);
17857
17858   // v = (v + (v >> 4)) & 0x0F0F0F0F...
17859   Srl = DAG.getBitcast(VT, GetShift(ISD::SRL, DAG.getBitcast(SrlVT, V), 4));
17860   SDValue Add = DAG.getNode(ISD::ADD, DL, VT, V, Srl);
17861   V = GetMask(Add, APInt::getSplat(Len, APInt(8, 0x0F)));
17862
17863   // At this point, V contains the byte-wise population count, and we are
17864   // merely doing a horizontal sum if necessary to get the wider element
17865   // counts.
17866   if (EltVT == MVT::i8)
17867     return V;
17868
17869   return LowerHorizontalByteSum(
17870       DAG.getBitcast(MVT::getVectorVT(MVT::i8, VecSize / 8), V), VT, Subtarget,
17871       DAG);
17872 }
17873
17874 static SDValue LowerVectorCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17875                                 SelectionDAG &DAG) {
17876   MVT VT = Op.getSimpleValueType();
17877   // FIXME: Need to add AVX-512 support here!
17878   assert((VT.is256BitVector() || VT.is128BitVector()) &&
17879          "Unknown CTPOP type to handle");
17880   SDLoc DL(Op.getNode());
17881   SDValue Op0 = Op.getOperand(0);
17882
17883   if (!Subtarget->hasSSSE3()) {
17884     // We can't use the fast LUT approach, so fall back on vectorized bitmath.
17885     assert(VT.is128BitVector() && "Only 128-bit vectors supported in SSE!");
17886     return LowerVectorCTPOPBitmath(Op0, DL, Subtarget, DAG);
17887   }
17888
17889   if (VT.is256BitVector() && !Subtarget->hasInt256()) {
17890     unsigned NumElems = VT.getVectorNumElements();
17891
17892     // Extract each 128-bit vector, compute pop count and concat the result.
17893     SDValue LHS = Extract128BitVector(Op0, 0, DAG, DL);
17894     SDValue RHS = Extract128BitVector(Op0, NumElems/2, DAG, DL);
17895
17896     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT,
17897                        LowerVectorCTPOPInRegLUT(LHS, DL, Subtarget, DAG),
17898                        LowerVectorCTPOPInRegLUT(RHS, DL, Subtarget, DAG));
17899   }
17900
17901   return LowerVectorCTPOPInRegLUT(Op0, DL, Subtarget, DAG);
17902 }
17903
17904 static SDValue LowerCTPOP(SDValue Op, const X86Subtarget *Subtarget,
17905                           SelectionDAG &DAG) {
17906   assert(Op.getValueType().isVector() &&
17907          "We only do custom lowering for vector population count.");
17908   return LowerVectorCTPOP(Op, Subtarget, DAG);
17909 }
17910
17911 static SDValue LowerLOAD_SUB(SDValue Op, SelectionDAG &DAG) {
17912   SDNode *Node = Op.getNode();
17913   SDLoc dl(Node);
17914   EVT T = Node->getValueType(0);
17915   SDValue negOp = DAG.getNode(ISD::SUB, dl, T,
17916                               DAG.getConstant(0, dl, T), Node->getOperand(2));
17917   return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl,
17918                        cast<AtomicSDNode>(Node)->getMemoryVT(),
17919                        Node->getOperand(0),
17920                        Node->getOperand(1), negOp,
17921                        cast<AtomicSDNode>(Node)->getMemOperand(),
17922                        cast<AtomicSDNode>(Node)->getOrdering(),
17923                        cast<AtomicSDNode>(Node)->getSynchScope());
17924 }
17925
17926 static SDValue LowerATOMIC_STORE(SDValue Op, SelectionDAG &DAG) {
17927   SDNode *Node = Op.getNode();
17928   SDLoc dl(Node);
17929   EVT VT = cast<AtomicSDNode>(Node)->getMemoryVT();
17930
17931   // Convert seq_cst store -> xchg
17932   // Convert wide store -> swap (-> cmpxchg8b/cmpxchg16b)
17933   // FIXME: On 32-bit, store -> fist or movq would be more efficient
17934   //        (The only way to get a 16-byte store is cmpxchg16b)
17935   // FIXME: 16-byte ATOMIC_SWAP isn't actually hooked up at the moment.
17936   if (cast<AtomicSDNode>(Node)->getOrdering() == SequentiallyConsistent ||
17937       !DAG.getTargetLoweringInfo().isTypeLegal(VT)) {
17938     SDValue Swap = DAG.getAtomic(ISD::ATOMIC_SWAP, dl,
17939                                  cast<AtomicSDNode>(Node)->getMemoryVT(),
17940                                  Node->getOperand(0),
17941                                  Node->getOperand(1), Node->getOperand(2),
17942                                  cast<AtomicSDNode>(Node)->getMemOperand(),
17943                                  cast<AtomicSDNode>(Node)->getOrdering(),
17944                                  cast<AtomicSDNode>(Node)->getSynchScope());
17945     return Swap.getValue(1);
17946   }
17947   // Other atomic stores have a simple pattern.
17948   return Op;
17949 }
17950
17951 static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
17952   EVT VT = Op.getNode()->getSimpleValueType(0);
17953
17954   // Let legalize expand this if it isn't a legal type yet.
17955   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
17956     return SDValue();
17957
17958   SDVTList VTs = DAG.getVTList(VT, MVT::i32);
17959
17960   unsigned Opc;
17961   bool ExtraOp = false;
17962   switch (Op.getOpcode()) {
17963   default: llvm_unreachable("Invalid code");
17964   case ISD::ADDC: Opc = X86ISD::ADD; break;
17965   case ISD::ADDE: Opc = X86ISD::ADC; ExtraOp = true; break;
17966   case ISD::SUBC: Opc = X86ISD::SUB; break;
17967   case ISD::SUBE: Opc = X86ISD::SBB; ExtraOp = true; break;
17968   }
17969
17970   if (!ExtraOp)
17971     return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17972                        Op.getOperand(1));
17973   return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0),
17974                      Op.getOperand(1), Op.getOperand(2));
17975 }
17976
17977 static SDValue LowerFSINCOS(SDValue Op, const X86Subtarget *Subtarget,
17978                             SelectionDAG &DAG) {
17979   assert(Subtarget->isTargetDarwin() && Subtarget->is64Bit());
17980
17981   // For MacOSX, we want to call an alternative entry point: __sincos_stret,
17982   // which returns the values as { float, float } (in XMM0) or
17983   // { double, double } (which is returned in XMM0, XMM1).
17984   SDLoc dl(Op);
17985   SDValue Arg = Op.getOperand(0);
17986   EVT ArgVT = Arg.getValueType();
17987   Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
17988
17989   TargetLowering::ArgListTy Args;
17990   TargetLowering::ArgListEntry Entry;
17991
17992   Entry.Node = Arg;
17993   Entry.Ty = ArgTy;
17994   Entry.isSExt = false;
17995   Entry.isZExt = false;
17996   Args.push_back(Entry);
17997
17998   bool isF64 = ArgVT == MVT::f64;
17999   // Only optimize x86_64 for now. i386 is a bit messy. For f32,
18000   // the small struct {f32, f32} is returned in (eax, edx). For f64,
18001   // the results are returned via SRet in memory.
18002   const char *LibcallName =  isF64 ? "__sincos_stret" : "__sincosf_stret";
18003   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18004   SDValue Callee = DAG.getExternalSymbol(LibcallName, TLI.getPointerTy());
18005
18006   Type *RetTy = isF64
18007     ? (Type*)StructType::get(ArgTy, ArgTy, nullptr)
18008     : (Type*)VectorType::get(ArgTy, 4);
18009
18010   TargetLowering::CallLoweringInfo CLI(DAG);
18011   CLI.setDebugLoc(dl).setChain(DAG.getEntryNode())
18012     .setCallee(CallingConv::C, RetTy, Callee, std::move(Args), 0);
18013
18014   std::pair<SDValue, SDValue> CallResult = TLI.LowerCallTo(CLI);
18015
18016   if (isF64)
18017     // Returned in xmm0 and xmm1.
18018     return CallResult.first;
18019
18020   // Returned in bits 0:31 and 32:64 xmm0.
18021   SDValue SinVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18022                                CallResult.first, DAG.getIntPtrConstant(0, dl));
18023   SDValue CosVal = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ArgVT,
18024                                CallResult.first, DAG.getIntPtrConstant(1, dl));
18025   SDVTList Tys = DAG.getVTList(ArgVT, ArgVT);
18026   return DAG.getNode(ISD::MERGE_VALUES, dl, Tys, SinVal, CosVal);
18027 }
18028
18029 static SDValue LowerMSCATTER(SDValue Op, const X86Subtarget *Subtarget,
18030                              SelectionDAG &DAG) {
18031   assert(Subtarget->hasAVX512() &&
18032          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18033
18034   MaskedScatterSDNode *N = cast<MaskedScatterSDNode>(Op.getNode());
18035   EVT VT = N->getValue().getValueType();
18036   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported scatter op");
18037   SDLoc dl(Op);
18038
18039   // X86 scatter kills mask register, so its type should be added to
18040   // the list of return values
18041   if (N->getNumValues() == 1) {
18042     SDValue Index = N->getIndex();
18043     if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18044         !Index.getValueType().is512BitVector())
18045       Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18046
18047     SDVTList VTs = DAG.getVTList(N->getMask().getValueType(), MVT::Other);
18048     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18049                       N->getOperand(3), Index };
18050
18051     SDValue NewScatter = DAG.getMaskedScatter(VTs, VT, dl, Ops, N->getMemOperand());
18052     DAG.ReplaceAllUsesWith(Op, SDValue(NewScatter.getNode(), 1));
18053     return SDValue(NewScatter.getNode(), 0);
18054   }
18055   return Op;
18056 }
18057
18058 static SDValue LowerMGATHER(SDValue Op, const X86Subtarget *Subtarget,
18059                             SelectionDAG &DAG) {
18060   assert(Subtarget->hasAVX512() &&
18061          "MGATHER/MSCATTER are supported on AVX-512 arch only");
18062
18063   MaskedGatherSDNode *N = cast<MaskedGatherSDNode>(Op.getNode());
18064   EVT VT = Op.getValueType();
18065   assert(VT.getScalarSizeInBits() >= 32 && "Unsupported gather op");
18066   SDLoc dl(Op);
18067
18068   SDValue Index = N->getIndex();
18069   if (!Subtarget->hasVLX() && !VT.is512BitVector() &&
18070       !Index.getValueType().is512BitVector()) {
18071     Index = DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v8i64, Index);
18072     SDValue Ops[] = { N->getOperand(0), N->getOperand(1),  N->getOperand(2),
18073                       N->getOperand(3), Index };
18074     DAG.UpdateNodeOperands(N, Ops);
18075   }
18076   return Op;
18077 }
18078
18079 SDValue X86TargetLowering::LowerGC_TRANSITION_START(SDValue Op,
18080                                                     SelectionDAG &DAG) const {
18081   // TODO: Eventually, the lowering of these nodes should be informed by or
18082   // deferred to the GC strategy for the function in which they appear. For
18083   // now, however, they must be lowered to something. Since they are logically
18084   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18085   // require special handling for these nodes), lower them as literal NOOPs for
18086   // the time being.
18087   SmallVector<SDValue, 2> Ops;
18088
18089   Ops.push_back(Op.getOperand(0));
18090   if (Op->getGluedNode())
18091     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18092
18093   SDLoc OpDL(Op);
18094   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18095   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18096
18097   return NOOP;
18098 }
18099
18100 SDValue X86TargetLowering::LowerGC_TRANSITION_END(SDValue Op,
18101                                                   SelectionDAG &DAG) const {
18102   // TODO: Eventually, the lowering of these nodes should be informed by or
18103   // deferred to the GC strategy for the function in which they appear. For
18104   // now, however, they must be lowered to something. Since they are logically
18105   // no-ops in the case of a null GC strategy (or a GC strategy which does not
18106   // require special handling for these nodes), lower them as literal NOOPs for
18107   // the time being.
18108   SmallVector<SDValue, 2> Ops;
18109
18110   Ops.push_back(Op.getOperand(0));
18111   if (Op->getGluedNode())
18112     Ops.push_back(Op->getOperand(Op->getNumOperands() - 1));
18113
18114   SDLoc OpDL(Op);
18115   SDVTList VTs = DAG.getVTList(MVT::Other, MVT::Glue);
18116   SDValue NOOP(DAG.getMachineNode(X86::NOOP, SDLoc(Op), VTs, Ops), 0);
18117
18118   return NOOP;
18119 }
18120
18121 /// LowerOperation - Provide custom lowering hooks for some operations.
18122 ///
18123 SDValue X86TargetLowering::LowerOperation(SDValue Op, SelectionDAG &DAG) const {
18124   switch (Op.getOpcode()) {
18125   default: llvm_unreachable("Should not custom lower this!");
18126   case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, Subtarget, DAG);
18127   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
18128     return LowerCMP_SWAP(Op, Subtarget, DAG);
18129   case ISD::CTPOP:              return LowerCTPOP(Op, Subtarget, DAG);
18130   case ISD::ATOMIC_LOAD_SUB:    return LowerLOAD_SUB(Op,DAG);
18131   case ISD::ATOMIC_STORE:       return LowerATOMIC_STORE(Op,DAG);
18132   case ISD::BUILD_VECTOR:       return LowerBUILD_VECTOR(Op, DAG);
18133   case ISD::CONCAT_VECTORS:     return LowerCONCAT_VECTORS(Op, Subtarget, DAG);
18134   case ISD::VECTOR_SHUFFLE:     return lowerVectorShuffle(Op, Subtarget, DAG);
18135   case ISD::VSELECT:            return LowerVSELECT(Op, DAG);
18136   case ISD::EXTRACT_VECTOR_ELT: return LowerEXTRACT_VECTOR_ELT(Op, DAG);
18137   case ISD::INSERT_VECTOR_ELT:  return LowerINSERT_VECTOR_ELT(Op, DAG);
18138   case ISD::EXTRACT_SUBVECTOR:  return LowerEXTRACT_SUBVECTOR(Op,Subtarget,DAG);
18139   case ISD::INSERT_SUBVECTOR:   return LowerINSERT_SUBVECTOR(Op, Subtarget,DAG);
18140   case ISD::SCALAR_TO_VECTOR:   return LowerSCALAR_TO_VECTOR(Op, DAG);
18141   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
18142   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
18143   case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
18144   case ISD::ExternalSymbol:     return LowerExternalSymbol(Op, DAG);
18145   case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
18146   case ISD::SHL_PARTS:
18147   case ISD::SRA_PARTS:
18148   case ISD::SRL_PARTS:          return LowerShiftParts(Op, DAG);
18149   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
18150   case ISD::UINT_TO_FP:         return LowerUINT_TO_FP(Op, DAG);
18151   case ISD::TRUNCATE:           return LowerTRUNCATE(Op, DAG);
18152   case ISD::ZERO_EXTEND:        return LowerZERO_EXTEND(Op, Subtarget, DAG);
18153   case ISD::SIGN_EXTEND:        return LowerSIGN_EXTEND(Op, Subtarget, DAG);
18154   case ISD::ANY_EXTEND:         return LowerANY_EXTEND(Op, Subtarget, DAG);
18155   case ISD::SIGN_EXTEND_VECTOR_INREG:
18156     return LowerSIGN_EXTEND_VECTOR_INREG(Op, Subtarget, DAG);
18157   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
18158   case ISD::FP_TO_UINT:         return LowerFP_TO_UINT(Op, DAG);
18159   case ISD::FP_EXTEND:          return LowerFP_EXTEND(Op, DAG);
18160   case ISD::LOAD:               return LowerExtendedLoad(Op, Subtarget, DAG);
18161   case ISD::FABS:
18162   case ISD::FNEG:               return LowerFABSorFNEG(Op, DAG);
18163   case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
18164   case ISD::FGETSIGN:           return LowerFGETSIGN(Op, DAG);
18165   case ISD::SETCC:              return LowerSETCC(Op, DAG);
18166   case ISD::SELECT:             return LowerSELECT(Op, DAG);
18167   case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
18168   case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
18169   case ISD::VASTART:            return LowerVASTART(Op, DAG);
18170   case ISD::VAARG:              return LowerVAARG(Op, DAG);
18171   case ISD::VACOPY:             return LowerVACOPY(Op, Subtarget, DAG);
18172   case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, Subtarget, DAG);
18173   case ISD::INTRINSIC_VOID:
18174   case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, Subtarget, DAG);
18175   case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
18176   case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
18177   case ISD::FRAME_TO_ARGS_OFFSET:
18178                                 return LowerFRAME_TO_ARGS_OFFSET(Op, DAG);
18179   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
18180   case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
18181   case ISD::EH_SJLJ_SETJMP:     return lowerEH_SJLJ_SETJMP(Op, DAG);
18182   case ISD::EH_SJLJ_LONGJMP:    return lowerEH_SJLJ_LONGJMP(Op, DAG);
18183   case ISD::INIT_TRAMPOLINE:    return LowerINIT_TRAMPOLINE(Op, DAG);
18184   case ISD::ADJUST_TRAMPOLINE:  return LowerADJUST_TRAMPOLINE(Op, DAG);
18185   case ISD::FLT_ROUNDS_:        return LowerFLT_ROUNDS_(Op, DAG);
18186   case ISD::CTLZ:               return LowerCTLZ(Op, DAG);
18187   case ISD::CTLZ_ZERO_UNDEF:    return LowerCTLZ_ZERO_UNDEF(Op, DAG);
18188   case ISD::CTTZ:               return LowerCTTZ(Op, DAG);
18189   case ISD::MUL:                return LowerMUL(Op, Subtarget, DAG);
18190   case ISD::UMUL_LOHI:
18191   case ISD::SMUL_LOHI:          return LowerMUL_LOHI(Op, Subtarget, DAG);
18192   case ISD::SRA:
18193   case ISD::SRL:
18194   case ISD::SHL:                return LowerShift(Op, Subtarget, DAG);
18195   case ISD::SADDO:
18196   case ISD::UADDO:
18197   case ISD::SSUBO:
18198   case ISD::USUBO:
18199   case ISD::SMULO:
18200   case ISD::UMULO:              return LowerXALUO(Op, DAG);
18201   case ISD::READCYCLECOUNTER:   return LowerREADCYCLECOUNTER(Op, Subtarget,DAG);
18202   case ISD::BITCAST:            return LowerBITCAST(Op, Subtarget, DAG);
18203   case ISD::ADDC:
18204   case ISD::ADDE:
18205   case ISD::SUBC:
18206   case ISD::SUBE:               return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
18207   case ISD::ADD:                return LowerADD(Op, DAG);
18208   case ISD::SUB:                return LowerSUB(Op, DAG);
18209   case ISD::FSINCOS:            return LowerFSINCOS(Op, Subtarget, DAG);
18210   case ISD::MGATHER:            return LowerMGATHER(Op, Subtarget, DAG);
18211   case ISD::MSCATTER:           return LowerMSCATTER(Op, Subtarget, DAG);
18212   case ISD::GC_TRANSITION_START:
18213                                 return LowerGC_TRANSITION_START(Op, DAG);
18214   case ISD::GC_TRANSITION_END:  return LowerGC_TRANSITION_END(Op, DAG);
18215   }
18216 }
18217
18218 /// ReplaceNodeResults - Replace a node with an illegal result type
18219 /// with a new node built out of custom code.
18220 void X86TargetLowering::ReplaceNodeResults(SDNode *N,
18221                                            SmallVectorImpl<SDValue>&Results,
18222                                            SelectionDAG &DAG) const {
18223   SDLoc dl(N);
18224   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
18225   switch (N->getOpcode()) {
18226   default:
18227     llvm_unreachable("Do not know how to custom type legalize this operation!");
18228   // We might have generated v2f32 FMIN/FMAX operations. Widen them to v4f32.
18229   case X86ISD::FMINC:
18230   case X86ISD::FMIN:
18231   case X86ISD::FMAXC:
18232   case X86ISD::FMAX: {
18233     EVT VT = N->getValueType(0);
18234     if (VT != MVT::v2f32)
18235       llvm_unreachable("Unexpected type (!= v2f32) on FMIN/FMAX.");
18236     SDValue UNDEF = DAG.getUNDEF(VT);
18237     SDValue LHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18238                               N->getOperand(0), UNDEF);
18239     SDValue RHS = DAG.getNode(ISD::CONCAT_VECTORS, dl, MVT::v4f32,
18240                               N->getOperand(1), UNDEF);
18241     Results.push_back(DAG.getNode(N->getOpcode(), dl, MVT::v4f32, LHS, RHS));
18242     return;
18243   }
18244   case ISD::SIGN_EXTEND_INREG:
18245   case ISD::ADDC:
18246   case ISD::ADDE:
18247   case ISD::SUBC:
18248   case ISD::SUBE:
18249     // We don't want to expand or promote these.
18250     return;
18251   case ISD::SDIV:
18252   case ISD::UDIV:
18253   case ISD::SREM:
18254   case ISD::UREM:
18255   case ISD::SDIVREM:
18256   case ISD::UDIVREM: {
18257     SDValue V = LowerWin64_i128OP(SDValue(N,0), DAG);
18258     Results.push_back(V);
18259     return;
18260   }
18261   case ISD::FP_TO_SINT:
18262     // FP_TO_INT*_IN_MEM is not legal for f16 inputs.  Do not convert
18263     // (FP_TO_SINT (load f16)) to FP_TO_INT*.
18264     if (N->getOperand(0).getValueType() == MVT::f16)
18265       break;
18266     // fallthrough
18267   case ISD::FP_TO_UINT: {
18268     bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
18269
18270     if (!IsSigned && !isIntegerTypeFTOL(SDValue(N, 0).getValueType()))
18271       return;
18272
18273     std::pair<SDValue,SDValue> Vals =
18274         FP_TO_INTHelper(SDValue(N, 0), DAG, IsSigned, /*IsReplace=*/ true);
18275     SDValue FIST = Vals.first, StackSlot = Vals.second;
18276     if (FIST.getNode()) {
18277       EVT VT = N->getValueType(0);
18278       // Return a load from the stack slot.
18279       if (StackSlot.getNode())
18280         Results.push_back(DAG.getLoad(VT, dl, FIST, StackSlot,
18281                                       MachinePointerInfo(),
18282                                       false, false, false, 0));
18283       else
18284         Results.push_back(FIST);
18285     }
18286     return;
18287   }
18288   case ISD::UINT_TO_FP: {
18289     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18290     if (N->getOperand(0).getValueType() != MVT::v2i32 ||
18291         N->getValueType(0) != MVT::v2f32)
18292       return;
18293     SDValue ZExtIn = DAG.getNode(ISD::ZERO_EXTEND, dl, MVT::v2i64,
18294                                  N->getOperand(0));
18295     SDValue Bias = DAG.getConstantFP(BitsToDouble(0x4330000000000000ULL), dl,
18296                                      MVT::f64);
18297     SDValue VBias = DAG.getNode(ISD::BUILD_VECTOR, dl, MVT::v2f64, Bias, Bias);
18298     SDValue Or = DAG.getNode(ISD::OR, dl, MVT::v2i64, ZExtIn,
18299                              DAG.getBitcast(MVT::v2i64, VBias));
18300     Or = DAG.getBitcast(MVT::v2f64, Or);
18301     SDValue Sub = DAG.getNode(ISD::FSUB, dl, MVT::v2f64, Or, VBias);
18302     Results.push_back(DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, Sub));
18303     return;
18304   }
18305   case ISD::FP_ROUND: {
18306     if (!TLI.isTypeLegal(N->getOperand(0).getValueType()))
18307         return;
18308     SDValue V = DAG.getNode(X86ISD::VFPROUND, dl, MVT::v4f32, N->getOperand(0));
18309     Results.push_back(V);
18310     return;
18311   }
18312   case ISD::FP_EXTEND: {
18313     // Right now, only MVT::v2f32 has OperationAction for FP_EXTEND.
18314     // No other ValueType for FP_EXTEND should reach this point.
18315     assert(N->getValueType(0) == MVT::v2f32 &&
18316            "Do not know how to legalize this Node");
18317     return;
18318   }
18319   case ISD::INTRINSIC_W_CHAIN: {
18320     unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
18321     switch (IntNo) {
18322     default : llvm_unreachable("Do not know how to custom type "
18323                                "legalize this intrinsic operation!");
18324     case Intrinsic::x86_rdtsc:
18325       return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18326                                      Results);
18327     case Intrinsic::x86_rdtscp:
18328       return getReadTimeStampCounter(N, dl, X86ISD::RDTSCP_DAG, DAG, Subtarget,
18329                                      Results);
18330     case Intrinsic::x86_rdpmc:
18331       return getReadPerformanceCounter(N, dl, DAG, Subtarget, Results);
18332     }
18333   }
18334   case ISD::READCYCLECOUNTER: {
18335     return getReadTimeStampCounter(N, dl, X86ISD::RDTSC_DAG, DAG, Subtarget,
18336                                    Results);
18337   }
18338   case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS: {
18339     EVT T = N->getValueType(0);
18340     assert((T == MVT::i64 || T == MVT::i128) && "can only expand cmpxchg pair");
18341     bool Regs64bit = T == MVT::i128;
18342     EVT HalfT = Regs64bit ? MVT::i64 : MVT::i32;
18343     SDValue cpInL, cpInH;
18344     cpInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18345                         DAG.getConstant(0, dl, HalfT));
18346     cpInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(2),
18347                         DAG.getConstant(1, dl, HalfT));
18348     cpInL = DAG.getCopyToReg(N->getOperand(0), dl,
18349                              Regs64bit ? X86::RAX : X86::EAX,
18350                              cpInL, SDValue());
18351     cpInH = DAG.getCopyToReg(cpInL.getValue(0), dl,
18352                              Regs64bit ? X86::RDX : X86::EDX,
18353                              cpInH, cpInL.getValue(1));
18354     SDValue swapInL, swapInH;
18355     swapInL = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18356                           DAG.getConstant(0, dl, HalfT));
18357     swapInH = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, HalfT, N->getOperand(3),
18358                           DAG.getConstant(1, dl, HalfT));
18359     swapInL = DAG.getCopyToReg(cpInH.getValue(0), dl,
18360                                Regs64bit ? X86::RBX : X86::EBX,
18361                                swapInL, cpInH.getValue(1));
18362     swapInH = DAG.getCopyToReg(swapInL.getValue(0), dl,
18363                                Regs64bit ? X86::RCX : X86::ECX,
18364                                swapInH, swapInL.getValue(1));
18365     SDValue Ops[] = { swapInH.getValue(0),
18366                       N->getOperand(1),
18367                       swapInH.getValue(1) };
18368     SDVTList Tys = DAG.getVTList(MVT::Other, MVT::Glue);
18369     MachineMemOperand *MMO = cast<AtomicSDNode>(N)->getMemOperand();
18370     unsigned Opcode = Regs64bit ? X86ISD::LCMPXCHG16_DAG :
18371                                   X86ISD::LCMPXCHG8_DAG;
18372     SDValue Result = DAG.getMemIntrinsicNode(Opcode, dl, Tys, Ops, T, MMO);
18373     SDValue cpOutL = DAG.getCopyFromReg(Result.getValue(0), dl,
18374                                         Regs64bit ? X86::RAX : X86::EAX,
18375                                         HalfT, Result.getValue(1));
18376     SDValue cpOutH = DAG.getCopyFromReg(cpOutL.getValue(1), dl,
18377                                         Regs64bit ? X86::RDX : X86::EDX,
18378                                         HalfT, cpOutL.getValue(2));
18379     SDValue OpsF[] = { cpOutL.getValue(0), cpOutH.getValue(0)};
18380
18381     SDValue EFLAGS = DAG.getCopyFromReg(cpOutH.getValue(1), dl, X86::EFLAGS,
18382                                         MVT::i32, cpOutH.getValue(2));
18383     SDValue Success =
18384         DAG.getNode(X86ISD::SETCC, dl, MVT::i8,
18385                     DAG.getConstant(X86::COND_E, dl, MVT::i8), EFLAGS);
18386     Success = DAG.getZExtOrTrunc(Success, dl, N->getValueType(1));
18387
18388     Results.push_back(DAG.getNode(ISD::BUILD_PAIR, dl, T, OpsF));
18389     Results.push_back(Success);
18390     Results.push_back(EFLAGS.getValue(1));
18391     return;
18392   }
18393   case ISD::ATOMIC_SWAP:
18394   case ISD::ATOMIC_LOAD_ADD:
18395   case ISD::ATOMIC_LOAD_SUB:
18396   case ISD::ATOMIC_LOAD_AND:
18397   case ISD::ATOMIC_LOAD_OR:
18398   case ISD::ATOMIC_LOAD_XOR:
18399   case ISD::ATOMIC_LOAD_NAND:
18400   case ISD::ATOMIC_LOAD_MIN:
18401   case ISD::ATOMIC_LOAD_MAX:
18402   case ISD::ATOMIC_LOAD_UMIN:
18403   case ISD::ATOMIC_LOAD_UMAX:
18404   case ISD::ATOMIC_LOAD: {
18405     // Delegate to generic TypeLegalization. Situations we can really handle
18406     // should have already been dealt with by AtomicExpandPass.cpp.
18407     break;
18408   }
18409   case ISD::BITCAST: {
18410     assert(Subtarget->hasSSE2() && "Requires at least SSE2!");
18411     EVT DstVT = N->getValueType(0);
18412     EVT SrcVT = N->getOperand(0)->getValueType(0);
18413
18414     if (SrcVT != MVT::f64 ||
18415         (DstVT != MVT::v2i32 && DstVT != MVT::v4i16 && DstVT != MVT::v8i8))
18416       return;
18417
18418     unsigned NumElts = DstVT.getVectorNumElements();
18419     EVT SVT = DstVT.getVectorElementType();
18420     EVT WiderVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumElts * 2);
18421     SDValue Expanded = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl,
18422                                    MVT::v2f64, N->getOperand(0));
18423     SDValue ToVecInt = DAG.getBitcast(WiderVT, Expanded);
18424
18425     if (ExperimentalVectorWideningLegalization) {
18426       // If we are legalizing vectors by widening, we already have the desired
18427       // legal vector type, just return it.
18428       Results.push_back(ToVecInt);
18429       return;
18430     }
18431
18432     SmallVector<SDValue, 8> Elts;
18433     for (unsigned i = 0, e = NumElts; i != e; ++i)
18434       Elts.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, SVT,
18435                                    ToVecInt, DAG.getIntPtrConstant(i, dl)));
18436
18437     Results.push_back(DAG.getNode(ISD::BUILD_VECTOR, dl, DstVT, Elts));
18438   }
18439   }
18440 }
18441
18442 const char *X86TargetLowering::getTargetNodeName(unsigned Opcode) const {
18443   switch ((X86ISD::NodeType)Opcode) {
18444   case X86ISD::FIRST_NUMBER:       break;
18445   case X86ISD::BSF:                return "X86ISD::BSF";
18446   case X86ISD::BSR:                return "X86ISD::BSR";
18447   case X86ISD::SHLD:               return "X86ISD::SHLD";
18448   case X86ISD::SHRD:               return "X86ISD::SHRD";
18449   case X86ISD::FAND:               return "X86ISD::FAND";
18450   case X86ISD::FANDN:              return "X86ISD::FANDN";
18451   case X86ISD::FOR:                return "X86ISD::FOR";
18452   case X86ISD::FXOR:               return "X86ISD::FXOR";
18453   case X86ISD::FILD:               return "X86ISD::FILD";
18454   case X86ISD::FILD_FLAG:          return "X86ISD::FILD_FLAG";
18455   case X86ISD::FP_TO_INT16_IN_MEM: return "X86ISD::FP_TO_INT16_IN_MEM";
18456   case X86ISD::FP_TO_INT32_IN_MEM: return "X86ISD::FP_TO_INT32_IN_MEM";
18457   case X86ISD::FP_TO_INT64_IN_MEM: return "X86ISD::FP_TO_INT64_IN_MEM";
18458   case X86ISD::FLD:                return "X86ISD::FLD";
18459   case X86ISD::FST:                return "X86ISD::FST";
18460   case X86ISD::CALL:               return "X86ISD::CALL";
18461   case X86ISD::RDTSC_DAG:          return "X86ISD::RDTSC_DAG";
18462   case X86ISD::RDTSCP_DAG:         return "X86ISD::RDTSCP_DAG";
18463   case X86ISD::RDPMC_DAG:          return "X86ISD::RDPMC_DAG";
18464   case X86ISD::BT:                 return "X86ISD::BT";
18465   case X86ISD::CMP:                return "X86ISD::CMP";
18466   case X86ISD::COMI:               return "X86ISD::COMI";
18467   case X86ISD::UCOMI:              return "X86ISD::UCOMI";
18468   case X86ISD::CMPM:               return "X86ISD::CMPM";
18469   case X86ISD::CMPMU:              return "X86ISD::CMPMU";
18470   case X86ISD::CMPM_RND:           return "X86ISD::CMPM_RND";
18471   case X86ISD::SETCC:              return "X86ISD::SETCC";
18472   case X86ISD::SETCC_CARRY:        return "X86ISD::SETCC_CARRY";
18473   case X86ISD::FSETCC:             return "X86ISD::FSETCC";
18474   case X86ISD::FGETSIGNx86:        return "X86ISD::FGETSIGNx86";
18475   case X86ISD::CMOV:               return "X86ISD::CMOV";
18476   case X86ISD::BRCOND:             return "X86ISD::BRCOND";
18477   case X86ISD::RET_FLAG:           return "X86ISD::RET_FLAG";
18478   case X86ISD::REP_STOS:           return "X86ISD::REP_STOS";
18479   case X86ISD::REP_MOVS:           return "X86ISD::REP_MOVS";
18480   case X86ISD::GlobalBaseReg:      return "X86ISD::GlobalBaseReg";
18481   case X86ISD::Wrapper:            return "X86ISD::Wrapper";
18482   case X86ISD::WrapperRIP:         return "X86ISD::WrapperRIP";
18483   case X86ISD::MOVDQ2Q:            return "X86ISD::MOVDQ2Q";
18484   case X86ISD::MMX_MOVD2W:         return "X86ISD::MMX_MOVD2W";
18485   case X86ISD::MMX_MOVW2D:         return "X86ISD::MMX_MOVW2D";
18486   case X86ISD::PEXTRB:             return "X86ISD::PEXTRB";
18487   case X86ISD::PEXTRW:             return "X86ISD::PEXTRW";
18488   case X86ISD::INSERTPS:           return "X86ISD::INSERTPS";
18489   case X86ISD::PINSRB:             return "X86ISD::PINSRB";
18490   case X86ISD::PINSRW:             return "X86ISD::PINSRW";
18491   case X86ISD::MMX_PINSRW:         return "X86ISD::MMX_PINSRW";
18492   case X86ISD::PSHUFB:             return "X86ISD::PSHUFB";
18493   case X86ISD::ANDNP:              return "X86ISD::ANDNP";
18494   case X86ISD::PSIGN:              return "X86ISD::PSIGN";
18495   case X86ISD::BLENDI:             return "X86ISD::BLENDI";
18496   case X86ISD::SHRUNKBLEND:        return "X86ISD::SHRUNKBLEND";
18497   case X86ISD::ADDUS:              return "X86ISD::ADDUS";
18498   case X86ISD::SUBUS:              return "X86ISD::SUBUS";
18499   case X86ISD::HADD:               return "X86ISD::HADD";
18500   case X86ISD::HSUB:               return "X86ISD::HSUB";
18501   case X86ISD::FHADD:              return "X86ISD::FHADD";
18502   case X86ISD::FHSUB:              return "X86ISD::FHSUB";
18503   case X86ISD::ABS:                return "X86ISD::ABS";
18504   case X86ISD::FMAX:               return "X86ISD::FMAX";
18505   case X86ISD::FMAX_RND:           return "X86ISD::FMAX_RND";
18506   case X86ISD::FMIN:               return "X86ISD::FMIN";
18507   case X86ISD::FMIN_RND:           return "X86ISD::FMIN_RND";
18508   case X86ISD::FMAXC:              return "X86ISD::FMAXC";
18509   case X86ISD::FMINC:              return "X86ISD::FMINC";
18510   case X86ISD::FRSQRT:             return "X86ISD::FRSQRT";
18511   case X86ISD::FRCP:               return "X86ISD::FRCP";
18512   case X86ISD::TLSADDR:            return "X86ISD::TLSADDR";
18513   case X86ISD::TLSBASEADDR:        return "X86ISD::TLSBASEADDR";
18514   case X86ISD::TLSCALL:            return "X86ISD::TLSCALL";
18515   case X86ISD::EH_SJLJ_SETJMP:     return "X86ISD::EH_SJLJ_SETJMP";
18516   case X86ISD::EH_SJLJ_LONGJMP:    return "X86ISD::EH_SJLJ_LONGJMP";
18517   case X86ISD::EH_RETURN:          return "X86ISD::EH_RETURN";
18518   case X86ISD::TC_RETURN:          return "X86ISD::TC_RETURN";
18519   case X86ISD::FNSTCW16m:          return "X86ISD::FNSTCW16m";
18520   case X86ISD::FNSTSW16r:          return "X86ISD::FNSTSW16r";
18521   case X86ISD::LCMPXCHG_DAG:       return "X86ISD::LCMPXCHG_DAG";
18522   case X86ISD::LCMPXCHG8_DAG:      return "X86ISD::LCMPXCHG8_DAG";
18523   case X86ISD::LCMPXCHG16_DAG:     return "X86ISD::LCMPXCHG16_DAG";
18524   case X86ISD::VZEXT_MOVL:         return "X86ISD::VZEXT_MOVL";
18525   case X86ISD::VZEXT_LOAD:         return "X86ISD::VZEXT_LOAD";
18526   case X86ISD::VZEXT:              return "X86ISD::VZEXT";
18527   case X86ISD::VSEXT:              return "X86ISD::VSEXT";
18528   case X86ISD::VTRUNC:             return "X86ISD::VTRUNC";
18529   case X86ISD::VTRUNCM:            return "X86ISD::VTRUNCM";
18530   case X86ISD::VINSERT:            return "X86ISD::VINSERT";
18531   case X86ISD::VFPEXT:             return "X86ISD::VFPEXT";
18532   case X86ISD::VFPROUND:           return "X86ISD::VFPROUND";
18533   case X86ISD::CVTDQ2PD:           return "X86ISD::CVTDQ2PD";
18534   case X86ISD::VSHLDQ:             return "X86ISD::VSHLDQ";
18535   case X86ISD::VSRLDQ:             return "X86ISD::VSRLDQ";
18536   case X86ISD::VSHL:               return "X86ISD::VSHL";
18537   case X86ISD::VSRL:               return "X86ISD::VSRL";
18538   case X86ISD::VSRA:               return "X86ISD::VSRA";
18539   case X86ISD::VSHLI:              return "X86ISD::VSHLI";
18540   case X86ISD::VSRLI:              return "X86ISD::VSRLI";
18541   case X86ISD::VSRAI:              return "X86ISD::VSRAI";
18542   case X86ISD::CMPP:               return "X86ISD::CMPP";
18543   case X86ISD::PCMPEQ:             return "X86ISD::PCMPEQ";
18544   case X86ISD::PCMPGT:             return "X86ISD::PCMPGT";
18545   case X86ISD::PCMPEQM:            return "X86ISD::PCMPEQM";
18546   case X86ISD::PCMPGTM:            return "X86ISD::PCMPGTM";
18547   case X86ISD::ADD:                return "X86ISD::ADD";
18548   case X86ISD::SUB:                return "X86ISD::SUB";
18549   case X86ISD::ADC:                return "X86ISD::ADC";
18550   case X86ISD::SBB:                return "X86ISD::SBB";
18551   case X86ISD::SMUL:               return "X86ISD::SMUL";
18552   case X86ISD::UMUL:               return "X86ISD::UMUL";
18553   case X86ISD::SMUL8:              return "X86ISD::SMUL8";
18554   case X86ISD::UMUL8:              return "X86ISD::UMUL8";
18555   case X86ISD::SDIVREM8_SEXT_HREG: return "X86ISD::SDIVREM8_SEXT_HREG";
18556   case X86ISD::UDIVREM8_ZEXT_HREG: return "X86ISD::UDIVREM8_ZEXT_HREG";
18557   case X86ISD::INC:                return "X86ISD::INC";
18558   case X86ISD::DEC:                return "X86ISD::DEC";
18559   case X86ISD::OR:                 return "X86ISD::OR";
18560   case X86ISD::XOR:                return "X86ISD::XOR";
18561   case X86ISD::AND:                return "X86ISD::AND";
18562   case X86ISD::BEXTR:              return "X86ISD::BEXTR";
18563   case X86ISD::MUL_IMM:            return "X86ISD::MUL_IMM";
18564   case X86ISD::PTEST:              return "X86ISD::PTEST";
18565   case X86ISD::TESTP:              return "X86ISD::TESTP";
18566   case X86ISD::TESTM:              return "X86ISD::TESTM";
18567   case X86ISD::TESTNM:             return "X86ISD::TESTNM";
18568   case X86ISD::KORTEST:            return "X86ISD::KORTEST";
18569   case X86ISD::PACKSS:             return "X86ISD::PACKSS";
18570   case X86ISD::PACKUS:             return "X86ISD::PACKUS";
18571   case X86ISD::PALIGNR:            return "X86ISD::PALIGNR";
18572   case X86ISD::VALIGN:             return "X86ISD::VALIGN";
18573   case X86ISD::PSHUFD:             return "X86ISD::PSHUFD";
18574   case X86ISD::PSHUFHW:            return "X86ISD::PSHUFHW";
18575   case X86ISD::PSHUFLW:            return "X86ISD::PSHUFLW";
18576   case X86ISD::SHUFP:              return "X86ISD::SHUFP";
18577   case X86ISD::SHUF128:            return "X86ISD::SHUF128";
18578   case X86ISD::MOVLHPS:            return "X86ISD::MOVLHPS";
18579   case X86ISD::MOVLHPD:            return "X86ISD::MOVLHPD";
18580   case X86ISD::MOVHLPS:            return "X86ISD::MOVHLPS";
18581   case X86ISD::MOVLPS:             return "X86ISD::MOVLPS";
18582   case X86ISD::MOVLPD:             return "X86ISD::MOVLPD";
18583   case X86ISD::MOVDDUP:            return "X86ISD::MOVDDUP";
18584   case X86ISD::MOVSHDUP:           return "X86ISD::MOVSHDUP";
18585   case X86ISD::MOVSLDUP:           return "X86ISD::MOVSLDUP";
18586   case X86ISD::MOVSD:              return "X86ISD::MOVSD";
18587   case X86ISD::MOVSS:              return "X86ISD::MOVSS";
18588   case X86ISD::UNPCKL:             return "X86ISD::UNPCKL";
18589   case X86ISD::UNPCKH:             return "X86ISD::UNPCKH";
18590   case X86ISD::VBROADCAST:         return "X86ISD::VBROADCAST";
18591   case X86ISD::SUBV_BROADCAST:     return "X86ISD::SUBV_BROADCAST";
18592   case X86ISD::VEXTRACT:           return "X86ISD::VEXTRACT";
18593   case X86ISD::VPERMILPV:          return "X86ISD::VPERMILPV";
18594   case X86ISD::VPERMILPI:          return "X86ISD::VPERMILPI";
18595   case X86ISD::VPERM2X128:         return "X86ISD::VPERM2X128";
18596   case X86ISD::VPERMV:             return "X86ISD::VPERMV";
18597   case X86ISD::VPERMV3:            return "X86ISD::VPERMV3";
18598   case X86ISD::VPERMIV3:           return "X86ISD::VPERMIV3";
18599   case X86ISD::VPERMI:             return "X86ISD::VPERMI";
18600   case X86ISD::VFIXUPIMM:          return "X86ISD::VFIXUPIMM";
18601   case X86ISD::VRANGE:             return "X86ISD::VRANGE";
18602   case X86ISD::PMULUDQ:            return "X86ISD::PMULUDQ";
18603   case X86ISD::PMULDQ:             return "X86ISD::PMULDQ";
18604   case X86ISD::PSADBW:             return "X86ISD::PSADBW";
18605   case X86ISD::VASTART_SAVE_XMM_REGS: return "X86ISD::VASTART_SAVE_XMM_REGS";
18606   case X86ISD::VAARG_64:           return "X86ISD::VAARG_64";
18607   case X86ISD::WIN_ALLOCA:         return "X86ISD::WIN_ALLOCA";
18608   case X86ISD::MEMBARRIER:         return "X86ISD::MEMBARRIER";
18609   case X86ISD::MFENCE:             return "X86ISD::MFENCE";
18610   case X86ISD::SFENCE:             return "X86ISD::SFENCE";
18611   case X86ISD::LFENCE:             return "X86ISD::LFENCE";
18612   case X86ISD::SEG_ALLOCA:         return "X86ISD::SEG_ALLOCA";
18613   case X86ISD::WIN_FTOL:           return "X86ISD::WIN_FTOL";
18614   case X86ISD::SAHF:               return "X86ISD::SAHF";
18615   case X86ISD::RDRAND:             return "X86ISD::RDRAND";
18616   case X86ISD::RDSEED:             return "X86ISD::RDSEED";
18617   case X86ISD::FMADD:              return "X86ISD::FMADD";
18618   case X86ISD::FMSUB:              return "X86ISD::FMSUB";
18619   case X86ISD::FNMADD:             return "X86ISD::FNMADD";
18620   case X86ISD::FNMSUB:             return "X86ISD::FNMSUB";
18621   case X86ISD::FMADDSUB:           return "X86ISD::FMADDSUB";
18622   case X86ISD::FMSUBADD:           return "X86ISD::FMSUBADD";
18623   case X86ISD::FMADD_RND:          return "X86ISD::FMADD_RND";
18624   case X86ISD::FNMADD_RND:         return "X86ISD::FNMADD_RND";
18625   case X86ISD::FMSUB_RND:          return "X86ISD::FMSUB_RND";
18626   case X86ISD::FNMSUB_RND:         return "X86ISD::FNMSUB_RND";
18627   case X86ISD::FMADDSUB_RND:       return "X86ISD::FMADDSUB_RND";
18628   case X86ISD::FMSUBADD_RND:       return "X86ISD::FMSUBADD_RND";
18629   case X86ISD::RNDSCALE:           return "X86ISD::RNDSCALE";
18630   case X86ISD::PCMPESTRI:          return "X86ISD::PCMPESTRI";
18631   case X86ISD::PCMPISTRI:          return "X86ISD::PCMPISTRI";
18632   case X86ISD::XTEST:              return "X86ISD::XTEST";
18633   case X86ISD::COMPRESS:           return "X86ISD::COMPRESS";
18634   case X86ISD::EXPAND:             return "X86ISD::EXPAND";
18635   case X86ISD::SELECT:             return "X86ISD::SELECT";
18636   case X86ISD::ADDSUB:             return "X86ISD::ADDSUB";
18637   case X86ISD::RCP28:              return "X86ISD::RCP28";
18638   case X86ISD::EXP2:               return "X86ISD::EXP2";
18639   case X86ISD::RSQRT28:            return "X86ISD::RSQRT28";
18640   case X86ISD::FADD_RND:           return "X86ISD::FADD_RND";
18641   case X86ISD::FSUB_RND:           return "X86ISD::FSUB_RND";
18642   case X86ISD::FMUL_RND:           return "X86ISD::FMUL_RND";
18643   case X86ISD::FDIV_RND:           return "X86ISD::FDIV_RND";
18644   case X86ISD::FSQRT_RND:          return "X86ISD::FSQRT_RND";
18645   case X86ISD::FGETEXP_RND:        return "X86ISD::FGETEXP_RND";
18646   case X86ISD::SCALEF:             return "X86ISD::SCALEF";
18647   case X86ISD::ADDS:               return "X86ISD::ADDS";
18648   case X86ISD::SUBS:               return "X86ISD::SUBS";
18649   case X86ISD::AVG:                return "X86ISD::AVG";
18650   case X86ISD::MULHRS:             return "X86ISD::MULHRS";
18651   case X86ISD::SINT_TO_FP_RND:     return "X86ISD::SINT_TO_FP_RND";
18652   case X86ISD::UINT_TO_FP_RND:     return "X86ISD::UINT_TO_FP_RND";
18653   }
18654   return nullptr;
18655 }
18656
18657 // isLegalAddressingMode - Return true if the addressing mode represented
18658 // by AM is legal for this target, for a load/store of the specified type.
18659 bool X86TargetLowering::isLegalAddressingMode(const AddrMode &AM,
18660                                               Type *Ty,
18661                                               unsigned AS) const {
18662   // X86 supports extremely general addressing modes.
18663   CodeModel::Model M = getTargetMachine().getCodeModel();
18664   Reloc::Model R = getTargetMachine().getRelocationModel();
18665
18666   // X86 allows a sign-extended 32-bit immediate field as a displacement.
18667   if (!X86::isOffsetSuitableForCodeModel(AM.BaseOffs, M, AM.BaseGV != nullptr))
18668     return false;
18669
18670   if (AM.BaseGV) {
18671     unsigned GVFlags =
18672       Subtarget->ClassifyGlobalReference(AM.BaseGV, getTargetMachine());
18673
18674     // If a reference to this global requires an extra load, we can't fold it.
18675     if (isGlobalStubReference(GVFlags))
18676       return false;
18677
18678     // If BaseGV requires a register for the PIC base, we cannot also have a
18679     // BaseReg specified.
18680     if (AM.HasBaseReg && isGlobalRelativeToPICBase(GVFlags))
18681       return false;
18682
18683     // If lower 4G is not available, then we must use rip-relative addressing.
18684     if ((M != CodeModel::Small || R != Reloc::Static) &&
18685         Subtarget->is64Bit() && (AM.BaseOffs || AM.Scale > 1))
18686       return false;
18687   }
18688
18689   switch (AM.Scale) {
18690   case 0:
18691   case 1:
18692   case 2:
18693   case 4:
18694   case 8:
18695     // These scales always work.
18696     break;
18697   case 3:
18698   case 5:
18699   case 9:
18700     // These scales are formed with basereg+scalereg.  Only accept if there is
18701     // no basereg yet.
18702     if (AM.HasBaseReg)
18703       return false;
18704     break;
18705   default:  // Other stuff never works.
18706     return false;
18707   }
18708
18709   return true;
18710 }
18711
18712 bool X86TargetLowering::isVectorShiftByScalarCheap(Type *Ty) const {
18713   unsigned Bits = Ty->getScalarSizeInBits();
18714
18715   // 8-bit shifts are always expensive, but versions with a scalar amount aren't
18716   // particularly cheaper than those without.
18717   if (Bits == 8)
18718     return false;
18719
18720   // On AVX2 there are new vpsllv[dq] instructions (and other shifts), that make
18721   // variable shifts just as cheap as scalar ones.
18722   if (Subtarget->hasInt256() && (Bits == 32 || Bits == 64))
18723     return false;
18724
18725   // Otherwise, it's significantly cheaper to shift by a scalar amount than by a
18726   // fully general vector.
18727   return true;
18728 }
18729
18730 bool X86TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
18731   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18732     return false;
18733   unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
18734   unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
18735   return NumBits1 > NumBits2;
18736 }
18737
18738 bool X86TargetLowering::allowTruncateForTailCall(Type *Ty1, Type *Ty2) const {
18739   if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
18740     return false;
18741
18742   if (!isTypeLegal(EVT::getEVT(Ty1)))
18743     return false;
18744
18745   assert(Ty1->getPrimitiveSizeInBits() <= 64 && "i128 is probably not a noop");
18746
18747   // Assuming the caller doesn't have a zeroext or signext return parameter,
18748   // truncation all the way down to i1 is valid.
18749   return true;
18750 }
18751
18752 bool X86TargetLowering::isLegalICmpImmediate(int64_t Imm) const {
18753   return isInt<32>(Imm);
18754 }
18755
18756 bool X86TargetLowering::isLegalAddImmediate(int64_t Imm) const {
18757   // Can also use sub to handle negated immediates.
18758   return isInt<32>(Imm);
18759 }
18760
18761 bool X86TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
18762   if (!VT1.isInteger() || !VT2.isInteger())
18763     return false;
18764   unsigned NumBits1 = VT1.getSizeInBits();
18765   unsigned NumBits2 = VT2.getSizeInBits();
18766   return NumBits1 > NumBits2;
18767 }
18768
18769 bool X86TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
18770   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18771   return Ty1->isIntegerTy(32) && Ty2->isIntegerTy(64) && Subtarget->is64Bit();
18772 }
18773
18774 bool X86TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
18775   // x86-64 implicitly zero-extends 32-bit results in 64-bit registers.
18776   return VT1 == MVT::i32 && VT2 == MVT::i64 && Subtarget->is64Bit();
18777 }
18778
18779 bool X86TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
18780   EVT VT1 = Val.getValueType();
18781   if (isZExtFree(VT1, VT2))
18782     return true;
18783
18784   if (Val.getOpcode() != ISD::LOAD)
18785     return false;
18786
18787   if (!VT1.isSimple() || !VT1.isInteger() ||
18788       !VT2.isSimple() || !VT2.isInteger())
18789     return false;
18790
18791   switch (VT1.getSimpleVT().SimpleTy) {
18792   default: break;
18793   case MVT::i8:
18794   case MVT::i16:
18795   case MVT::i32:
18796     // X86 has 8, 16, and 32-bit zero-extending loads.
18797     return true;
18798   }
18799
18800   return false;
18801 }
18802
18803 bool X86TargetLowering::isVectorLoadExtDesirable(SDValue) const { return true; }
18804
18805 bool
18806 X86TargetLowering::isFMAFasterThanFMulAndFAdd(EVT VT) const {
18807   if (!(Subtarget->hasFMA() || Subtarget->hasFMA4() || Subtarget->hasAVX512()))
18808     return false;
18809
18810   VT = VT.getScalarType();
18811
18812   if (!VT.isSimple())
18813     return false;
18814
18815   switch (VT.getSimpleVT().SimpleTy) {
18816   case MVT::f32:
18817   case MVT::f64:
18818     return true;
18819   default:
18820     break;
18821   }
18822
18823   return false;
18824 }
18825
18826 bool X86TargetLowering::isNarrowingProfitable(EVT VT1, EVT VT2) const {
18827   // i16 instructions are longer (0x66 prefix) and potentially slower.
18828   return !(VT1 == MVT::i32 && VT2 == MVT::i16);
18829 }
18830
18831 /// isShuffleMaskLegal - Targets can use this to indicate that they only
18832 /// support *some* VECTOR_SHUFFLE operations, those with specific masks.
18833 /// By default, if a target supports the VECTOR_SHUFFLE node, all mask values
18834 /// are assumed to be legal.
18835 bool
18836 X86TargetLowering::isShuffleMaskLegal(const SmallVectorImpl<int> &M,
18837                                       EVT VT) const {
18838   if (!VT.isSimple())
18839     return false;
18840
18841   // Not for i1 vectors
18842   if (VT.getScalarType() == MVT::i1)
18843     return false;
18844
18845   // Very little shuffling can be done for 64-bit vectors right now.
18846   if (VT.getSizeInBits() == 64)
18847     return false;
18848
18849   // We only care that the types being shuffled are legal. The lowering can
18850   // handle any possible shuffle mask that results.
18851   return isTypeLegal(VT.getSimpleVT());
18852 }
18853
18854 bool
18855 X86TargetLowering::isVectorClearMaskLegal(const SmallVectorImpl<int> &Mask,
18856                                           EVT VT) const {
18857   // Just delegate to the generic legality, clear masks aren't special.
18858   return isShuffleMaskLegal(Mask, VT);
18859 }
18860
18861 //===----------------------------------------------------------------------===//
18862 //                           X86 Scheduler Hooks
18863 //===----------------------------------------------------------------------===//
18864
18865 /// Utility function to emit xbegin specifying the start of an RTM region.
18866 static MachineBasicBlock *EmitXBegin(MachineInstr *MI, MachineBasicBlock *MBB,
18867                                      const TargetInstrInfo *TII) {
18868   DebugLoc DL = MI->getDebugLoc();
18869
18870   const BasicBlock *BB = MBB->getBasicBlock();
18871   MachineFunction::iterator I = MBB;
18872   ++I;
18873
18874   // For the v = xbegin(), we generate
18875   //
18876   // thisMBB:
18877   //  xbegin sinkMBB
18878   //
18879   // mainMBB:
18880   //  eax = -1
18881   //
18882   // sinkMBB:
18883   //  v = eax
18884
18885   MachineBasicBlock *thisMBB = MBB;
18886   MachineFunction *MF = MBB->getParent();
18887   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
18888   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
18889   MF->insert(I, mainMBB);
18890   MF->insert(I, sinkMBB);
18891
18892   // Transfer the remainder of BB and its successor edges to sinkMBB.
18893   sinkMBB->splice(sinkMBB->begin(), MBB,
18894                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
18895   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
18896
18897   // thisMBB:
18898   //  xbegin sinkMBB
18899   //  # fallthrough to mainMBB
18900   //  # abortion to sinkMBB
18901   BuildMI(thisMBB, DL, TII->get(X86::XBEGIN_4)).addMBB(sinkMBB);
18902   thisMBB->addSuccessor(mainMBB);
18903   thisMBB->addSuccessor(sinkMBB);
18904
18905   // mainMBB:
18906   //  EAX = -1
18907   BuildMI(mainMBB, DL, TII->get(X86::MOV32ri), X86::EAX).addImm(-1);
18908   mainMBB->addSuccessor(sinkMBB);
18909
18910   // sinkMBB:
18911   // EAX is live into the sinkMBB
18912   sinkMBB->addLiveIn(X86::EAX);
18913   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
18914           TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18915     .addReg(X86::EAX);
18916
18917   MI->eraseFromParent();
18918   return sinkMBB;
18919 }
18920
18921 // FIXME: When we get size specific XMM0 registers, i.e. XMM0_V16I8
18922 // or XMM0_V32I8 in AVX all of this code can be replaced with that
18923 // in the .td file.
18924 static MachineBasicBlock *EmitPCMPSTRM(MachineInstr *MI, MachineBasicBlock *BB,
18925                                        const TargetInstrInfo *TII) {
18926   unsigned Opc;
18927   switch (MI->getOpcode()) {
18928   default: llvm_unreachable("illegal opcode!");
18929   case X86::PCMPISTRM128REG:  Opc = X86::PCMPISTRM128rr;  break;
18930   case X86::VPCMPISTRM128REG: Opc = X86::VPCMPISTRM128rr; break;
18931   case X86::PCMPISTRM128MEM:  Opc = X86::PCMPISTRM128rm;  break;
18932   case X86::VPCMPISTRM128MEM: Opc = X86::VPCMPISTRM128rm; break;
18933   case X86::PCMPESTRM128REG:  Opc = X86::PCMPESTRM128rr;  break;
18934   case X86::VPCMPESTRM128REG: Opc = X86::VPCMPESTRM128rr; break;
18935   case X86::PCMPESTRM128MEM:  Opc = X86::PCMPESTRM128rm;  break;
18936   case X86::VPCMPESTRM128MEM: Opc = X86::VPCMPESTRM128rm; break;
18937   }
18938
18939   DebugLoc dl = MI->getDebugLoc();
18940   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18941
18942   unsigned NumArgs = MI->getNumOperands();
18943   for (unsigned i = 1; i < NumArgs; ++i) {
18944     MachineOperand &Op = MI->getOperand(i);
18945     if (!(Op.isReg() && Op.isImplicit()))
18946       MIB.addOperand(Op);
18947   }
18948   if (MI->hasOneMemOperand())
18949     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18950
18951   BuildMI(*BB, MI, dl,
18952     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18953     .addReg(X86::XMM0);
18954
18955   MI->eraseFromParent();
18956   return BB;
18957 }
18958
18959 // FIXME: Custom handling because TableGen doesn't support multiple implicit
18960 // defs in an instruction pattern
18961 static MachineBasicBlock *EmitPCMPSTRI(MachineInstr *MI, MachineBasicBlock *BB,
18962                                        const TargetInstrInfo *TII) {
18963   unsigned Opc;
18964   switch (MI->getOpcode()) {
18965   default: llvm_unreachable("illegal opcode!");
18966   case X86::PCMPISTRIREG:  Opc = X86::PCMPISTRIrr;  break;
18967   case X86::VPCMPISTRIREG: Opc = X86::VPCMPISTRIrr; break;
18968   case X86::PCMPISTRIMEM:  Opc = X86::PCMPISTRIrm;  break;
18969   case X86::VPCMPISTRIMEM: Opc = X86::VPCMPISTRIrm; break;
18970   case X86::PCMPESTRIREG:  Opc = X86::PCMPESTRIrr;  break;
18971   case X86::VPCMPESTRIREG: Opc = X86::VPCMPESTRIrr; break;
18972   case X86::PCMPESTRIMEM:  Opc = X86::PCMPESTRIrm;  break;
18973   case X86::VPCMPESTRIMEM: Opc = X86::VPCMPESTRIrm; break;
18974   }
18975
18976   DebugLoc dl = MI->getDebugLoc();
18977   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(Opc));
18978
18979   unsigned NumArgs = MI->getNumOperands(); // remove the results
18980   for (unsigned i = 1; i < NumArgs; ++i) {
18981     MachineOperand &Op = MI->getOperand(i);
18982     if (!(Op.isReg() && Op.isImplicit()))
18983       MIB.addOperand(Op);
18984   }
18985   if (MI->hasOneMemOperand())
18986     MIB->setMemRefs(MI->memoperands_begin(), MI->memoperands_end());
18987
18988   BuildMI(*BB, MI, dl,
18989     TII->get(TargetOpcode::COPY), MI->getOperand(0).getReg())
18990     .addReg(X86::ECX);
18991
18992   MI->eraseFromParent();
18993   return BB;
18994 }
18995
18996 static MachineBasicBlock *EmitMonitor(MachineInstr *MI, MachineBasicBlock *BB,
18997                                       const X86Subtarget *Subtarget) {
18998   DebugLoc dl = MI->getDebugLoc();
18999   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19000   // Address into RAX/EAX, other two args into ECX, EDX.
19001   unsigned MemOpc = Subtarget->is64Bit() ? X86::LEA64r : X86::LEA32r;
19002   unsigned MemReg = Subtarget->is64Bit() ? X86::RAX : X86::EAX;
19003   MachineInstrBuilder MIB = BuildMI(*BB, MI, dl, TII->get(MemOpc), MemReg);
19004   for (int i = 0; i < X86::AddrNumOperands; ++i)
19005     MIB.addOperand(MI->getOperand(i));
19006
19007   unsigned ValOps = X86::AddrNumOperands;
19008   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::ECX)
19009     .addReg(MI->getOperand(ValOps).getReg());
19010   BuildMI(*BB, MI, dl, TII->get(TargetOpcode::COPY), X86::EDX)
19011     .addReg(MI->getOperand(ValOps+1).getReg());
19012
19013   // The instruction doesn't actually take any operands though.
19014   BuildMI(*BB, MI, dl, TII->get(X86::MONITORrrr));
19015
19016   MI->eraseFromParent(); // The pseudo is gone now.
19017   return BB;
19018 }
19019
19020 MachineBasicBlock *
19021 X86TargetLowering::EmitVAARG64WithCustomInserter(MachineInstr *MI,
19022                                                  MachineBasicBlock *MBB) const {
19023   // Emit va_arg instruction on X86-64.
19024
19025   // Operands to this pseudo-instruction:
19026   // 0  ) Output        : destination address (reg)
19027   // 1-5) Input         : va_list address (addr, i64mem)
19028   // 6  ) ArgSize       : Size (in bytes) of vararg type
19029   // 7  ) ArgMode       : 0=overflow only, 1=use gp_offset, 2=use fp_offset
19030   // 8  ) Align         : Alignment of type
19031   // 9  ) EFLAGS (implicit-def)
19032
19033   assert(MI->getNumOperands() == 10 && "VAARG_64 should have 10 operands!");
19034   static_assert(X86::AddrNumOperands == 5,
19035                 "VAARG_64 assumes 5 address operands");
19036
19037   unsigned DestReg = MI->getOperand(0).getReg();
19038   MachineOperand &Base = MI->getOperand(1);
19039   MachineOperand &Scale = MI->getOperand(2);
19040   MachineOperand &Index = MI->getOperand(3);
19041   MachineOperand &Disp = MI->getOperand(4);
19042   MachineOperand &Segment = MI->getOperand(5);
19043   unsigned ArgSize = MI->getOperand(6).getImm();
19044   unsigned ArgMode = MI->getOperand(7).getImm();
19045   unsigned Align = MI->getOperand(8).getImm();
19046
19047   // Memory Reference
19048   assert(MI->hasOneMemOperand() && "Expected VAARG_64 to have one memoperand");
19049   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19050   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19051
19052   // Machine Information
19053   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19054   MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
19055   const TargetRegisterClass *AddrRegClass = getRegClassFor(MVT::i64);
19056   const TargetRegisterClass *OffsetRegClass = getRegClassFor(MVT::i32);
19057   DebugLoc DL = MI->getDebugLoc();
19058
19059   // struct va_list {
19060   //   i32   gp_offset
19061   //   i32   fp_offset
19062   //   i64   overflow_area (address)
19063   //   i64   reg_save_area (address)
19064   // }
19065   // sizeof(va_list) = 24
19066   // alignment(va_list) = 8
19067
19068   unsigned TotalNumIntRegs = 6;
19069   unsigned TotalNumXMMRegs = 8;
19070   bool UseGPOffset = (ArgMode == 1);
19071   bool UseFPOffset = (ArgMode == 2);
19072   unsigned MaxOffset = TotalNumIntRegs * 8 +
19073                        (UseFPOffset ? TotalNumXMMRegs * 16 : 0);
19074
19075   /* Align ArgSize to a multiple of 8 */
19076   unsigned ArgSizeA8 = (ArgSize + 7) & ~7;
19077   bool NeedsAlign = (Align > 8);
19078
19079   MachineBasicBlock *thisMBB = MBB;
19080   MachineBasicBlock *overflowMBB;
19081   MachineBasicBlock *offsetMBB;
19082   MachineBasicBlock *endMBB;
19083
19084   unsigned OffsetDestReg = 0;    // Argument address computed by offsetMBB
19085   unsigned OverflowDestReg = 0;  // Argument address computed by overflowMBB
19086   unsigned OffsetReg = 0;
19087
19088   if (!UseGPOffset && !UseFPOffset) {
19089     // If we only pull from the overflow region, we don't create a branch.
19090     // We don't need to alter control flow.
19091     OffsetDestReg = 0; // unused
19092     OverflowDestReg = DestReg;
19093
19094     offsetMBB = nullptr;
19095     overflowMBB = thisMBB;
19096     endMBB = thisMBB;
19097   } else {
19098     // First emit code to check if gp_offset (or fp_offset) is below the bound.
19099     // If so, pull the argument from reg_save_area. (branch to offsetMBB)
19100     // If not, pull from overflow_area. (branch to overflowMBB)
19101     //
19102     //       thisMBB
19103     //         |     .
19104     //         |        .
19105     //     offsetMBB   overflowMBB
19106     //         |        .
19107     //         |     .
19108     //        endMBB
19109
19110     // Registers for the PHI in endMBB
19111     OffsetDestReg = MRI.createVirtualRegister(AddrRegClass);
19112     OverflowDestReg = MRI.createVirtualRegister(AddrRegClass);
19113
19114     const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19115     MachineFunction *MF = MBB->getParent();
19116     overflowMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19117     offsetMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19118     endMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19119
19120     MachineFunction::iterator MBBIter = MBB;
19121     ++MBBIter;
19122
19123     // Insert the new basic blocks
19124     MF->insert(MBBIter, offsetMBB);
19125     MF->insert(MBBIter, overflowMBB);
19126     MF->insert(MBBIter, endMBB);
19127
19128     // Transfer the remainder of MBB and its successor edges to endMBB.
19129     endMBB->splice(endMBB->begin(), thisMBB,
19130                    std::next(MachineBasicBlock::iterator(MI)), thisMBB->end());
19131     endMBB->transferSuccessorsAndUpdatePHIs(thisMBB);
19132
19133     // Make offsetMBB and overflowMBB successors of thisMBB
19134     thisMBB->addSuccessor(offsetMBB);
19135     thisMBB->addSuccessor(overflowMBB);
19136
19137     // endMBB is a successor of both offsetMBB and overflowMBB
19138     offsetMBB->addSuccessor(endMBB);
19139     overflowMBB->addSuccessor(endMBB);
19140
19141     // Load the offset value into a register
19142     OffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19143     BuildMI(thisMBB, DL, TII->get(X86::MOV32rm), OffsetReg)
19144       .addOperand(Base)
19145       .addOperand(Scale)
19146       .addOperand(Index)
19147       .addDisp(Disp, UseFPOffset ? 4 : 0)
19148       .addOperand(Segment)
19149       .setMemRefs(MMOBegin, MMOEnd);
19150
19151     // Check if there is enough room left to pull this argument.
19152     BuildMI(thisMBB, DL, TII->get(X86::CMP32ri))
19153       .addReg(OffsetReg)
19154       .addImm(MaxOffset + 8 - ArgSizeA8);
19155
19156     // Branch to "overflowMBB" if offset >= max
19157     // Fall through to "offsetMBB" otherwise
19158     BuildMI(thisMBB, DL, TII->get(X86::GetCondBranchFromCond(X86::COND_AE)))
19159       .addMBB(overflowMBB);
19160   }
19161
19162   // In offsetMBB, emit code to use the reg_save_area.
19163   if (offsetMBB) {
19164     assert(OffsetReg != 0);
19165
19166     // Read the reg_save_area address.
19167     unsigned RegSaveReg = MRI.createVirtualRegister(AddrRegClass);
19168     BuildMI(offsetMBB, DL, TII->get(X86::MOV64rm), RegSaveReg)
19169       .addOperand(Base)
19170       .addOperand(Scale)
19171       .addOperand(Index)
19172       .addDisp(Disp, 16)
19173       .addOperand(Segment)
19174       .setMemRefs(MMOBegin, MMOEnd);
19175
19176     // Zero-extend the offset
19177     unsigned OffsetReg64 = MRI.createVirtualRegister(AddrRegClass);
19178       BuildMI(offsetMBB, DL, TII->get(X86::SUBREG_TO_REG), OffsetReg64)
19179         .addImm(0)
19180         .addReg(OffsetReg)
19181         .addImm(X86::sub_32bit);
19182
19183     // Add the offset to the reg_save_area to get the final address.
19184     BuildMI(offsetMBB, DL, TII->get(X86::ADD64rr), OffsetDestReg)
19185       .addReg(OffsetReg64)
19186       .addReg(RegSaveReg);
19187
19188     // Compute the offset for the next argument
19189     unsigned NextOffsetReg = MRI.createVirtualRegister(OffsetRegClass);
19190     BuildMI(offsetMBB, DL, TII->get(X86::ADD32ri), NextOffsetReg)
19191       .addReg(OffsetReg)
19192       .addImm(UseFPOffset ? 16 : 8);
19193
19194     // Store it back into the va_list.
19195     BuildMI(offsetMBB, DL, TII->get(X86::MOV32mr))
19196       .addOperand(Base)
19197       .addOperand(Scale)
19198       .addOperand(Index)
19199       .addDisp(Disp, UseFPOffset ? 4 : 0)
19200       .addOperand(Segment)
19201       .addReg(NextOffsetReg)
19202       .setMemRefs(MMOBegin, MMOEnd);
19203
19204     // Jump to endMBB
19205     BuildMI(offsetMBB, DL, TII->get(X86::JMP_1))
19206       .addMBB(endMBB);
19207   }
19208
19209   //
19210   // Emit code to use overflow area
19211   //
19212
19213   // Load the overflow_area address into a register.
19214   unsigned OverflowAddrReg = MRI.createVirtualRegister(AddrRegClass);
19215   BuildMI(overflowMBB, DL, TII->get(X86::MOV64rm), OverflowAddrReg)
19216     .addOperand(Base)
19217     .addOperand(Scale)
19218     .addOperand(Index)
19219     .addDisp(Disp, 8)
19220     .addOperand(Segment)
19221     .setMemRefs(MMOBegin, MMOEnd);
19222
19223   // If we need to align it, do so. Otherwise, just copy the address
19224   // to OverflowDestReg.
19225   if (NeedsAlign) {
19226     // Align the overflow address
19227     assert((Align & (Align-1)) == 0 && "Alignment must be a power of 2");
19228     unsigned TmpReg = MRI.createVirtualRegister(AddrRegClass);
19229
19230     // aligned_addr = (addr + (align-1)) & ~(align-1)
19231     BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), TmpReg)
19232       .addReg(OverflowAddrReg)
19233       .addImm(Align-1);
19234
19235     BuildMI(overflowMBB, DL, TII->get(X86::AND64ri32), OverflowDestReg)
19236       .addReg(TmpReg)
19237       .addImm(~(uint64_t)(Align-1));
19238   } else {
19239     BuildMI(overflowMBB, DL, TII->get(TargetOpcode::COPY), OverflowDestReg)
19240       .addReg(OverflowAddrReg);
19241   }
19242
19243   // Compute the next overflow address after this argument.
19244   // (the overflow address should be kept 8-byte aligned)
19245   unsigned NextAddrReg = MRI.createVirtualRegister(AddrRegClass);
19246   BuildMI(overflowMBB, DL, TII->get(X86::ADD64ri32), NextAddrReg)
19247     .addReg(OverflowDestReg)
19248     .addImm(ArgSizeA8);
19249
19250   // Store the new overflow address.
19251   BuildMI(overflowMBB, DL, TII->get(X86::MOV64mr))
19252     .addOperand(Base)
19253     .addOperand(Scale)
19254     .addOperand(Index)
19255     .addDisp(Disp, 8)
19256     .addOperand(Segment)
19257     .addReg(NextAddrReg)
19258     .setMemRefs(MMOBegin, MMOEnd);
19259
19260   // If we branched, emit the PHI to the front of endMBB.
19261   if (offsetMBB) {
19262     BuildMI(*endMBB, endMBB->begin(), DL,
19263             TII->get(X86::PHI), DestReg)
19264       .addReg(OffsetDestReg).addMBB(offsetMBB)
19265       .addReg(OverflowDestReg).addMBB(overflowMBB);
19266   }
19267
19268   // Erase the pseudo instruction
19269   MI->eraseFromParent();
19270
19271   return endMBB;
19272 }
19273
19274 MachineBasicBlock *
19275 X86TargetLowering::EmitVAStartSaveXMMRegsWithCustomInserter(
19276                                                  MachineInstr *MI,
19277                                                  MachineBasicBlock *MBB) const {
19278   // Emit code to save XMM registers to the stack. The ABI says that the
19279   // number of registers to save is given in %al, so it's theoretically
19280   // possible to do an indirect jump trick to avoid saving all of them,
19281   // however this code takes a simpler approach and just executes all
19282   // of the stores if %al is non-zero. It's less code, and it's probably
19283   // easier on the hardware branch predictor, and stores aren't all that
19284   // expensive anyway.
19285
19286   // Create the new basic blocks. One block contains all the XMM stores,
19287   // and one block is the final destination regardless of whether any
19288   // stores were performed.
19289   const BasicBlock *LLVM_BB = MBB->getBasicBlock();
19290   MachineFunction *F = MBB->getParent();
19291   MachineFunction::iterator MBBIter = MBB;
19292   ++MBBIter;
19293   MachineBasicBlock *XMMSaveMBB = F->CreateMachineBasicBlock(LLVM_BB);
19294   MachineBasicBlock *EndMBB = F->CreateMachineBasicBlock(LLVM_BB);
19295   F->insert(MBBIter, XMMSaveMBB);
19296   F->insert(MBBIter, EndMBB);
19297
19298   // Transfer the remainder of MBB and its successor edges to EndMBB.
19299   EndMBB->splice(EndMBB->begin(), MBB,
19300                  std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19301   EndMBB->transferSuccessorsAndUpdatePHIs(MBB);
19302
19303   // The original block will now fall through to the XMM save block.
19304   MBB->addSuccessor(XMMSaveMBB);
19305   // The XMMSaveMBB will fall through to the end block.
19306   XMMSaveMBB->addSuccessor(EndMBB);
19307
19308   // Now add the instructions.
19309   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19310   DebugLoc DL = MI->getDebugLoc();
19311
19312   unsigned CountReg = MI->getOperand(0).getReg();
19313   int64_t RegSaveFrameIndex = MI->getOperand(1).getImm();
19314   int64_t VarArgsFPOffset = MI->getOperand(2).getImm();
19315
19316   if (!Subtarget->isTargetWin64()) {
19317     // If %al is 0, branch around the XMM save block.
19318     BuildMI(MBB, DL, TII->get(X86::TEST8rr)).addReg(CountReg).addReg(CountReg);
19319     BuildMI(MBB, DL, TII->get(X86::JE_1)).addMBB(EndMBB);
19320     MBB->addSuccessor(EndMBB);
19321   }
19322
19323   // Make sure the last operand is EFLAGS, which gets clobbered by the branch
19324   // that was just emitted, but clearly shouldn't be "saved".
19325   assert((MI->getNumOperands() <= 3 ||
19326           !MI->getOperand(MI->getNumOperands() - 1).isReg() ||
19327           MI->getOperand(MI->getNumOperands() - 1).getReg() == X86::EFLAGS)
19328          && "Expected last argument to be EFLAGS");
19329   unsigned MOVOpc = Subtarget->hasFp256() ? X86::VMOVAPSmr : X86::MOVAPSmr;
19330   // In the XMM save block, save all the XMM argument registers.
19331   for (int i = 3, e = MI->getNumOperands() - 1; i != e; ++i) {
19332     int64_t Offset = (i - 3) * 16 + VarArgsFPOffset;
19333     MachineMemOperand *MMO =
19334       F->getMachineMemOperand(
19335           MachinePointerInfo::getFixedStack(RegSaveFrameIndex, Offset),
19336         MachineMemOperand::MOStore,
19337         /*Size=*/16, /*Align=*/16);
19338     BuildMI(XMMSaveMBB, DL, TII->get(MOVOpc))
19339       .addFrameIndex(RegSaveFrameIndex)
19340       .addImm(/*Scale=*/1)
19341       .addReg(/*IndexReg=*/0)
19342       .addImm(/*Disp=*/Offset)
19343       .addReg(/*Segment=*/0)
19344       .addReg(MI->getOperand(i).getReg())
19345       .addMemOperand(MMO);
19346   }
19347
19348   MI->eraseFromParent();   // The pseudo instruction is gone now.
19349
19350   return EndMBB;
19351 }
19352
19353 // The EFLAGS operand of SelectItr might be missing a kill marker
19354 // because there were multiple uses of EFLAGS, and ISel didn't know
19355 // which to mark. Figure out whether SelectItr should have had a
19356 // kill marker, and set it if it should. Returns the correct kill
19357 // marker value.
19358 static bool checkAndUpdateEFLAGSKill(MachineBasicBlock::iterator SelectItr,
19359                                      MachineBasicBlock* BB,
19360                                      const TargetRegisterInfo* TRI) {
19361   // Scan forward through BB for a use/def of EFLAGS.
19362   MachineBasicBlock::iterator miI(std::next(SelectItr));
19363   for (MachineBasicBlock::iterator miE = BB->end(); miI != miE; ++miI) {
19364     const MachineInstr& mi = *miI;
19365     if (mi.readsRegister(X86::EFLAGS))
19366       return false;
19367     if (mi.definesRegister(X86::EFLAGS))
19368       break; // Should have kill-flag - update below.
19369   }
19370
19371   // If we hit the end of the block, check whether EFLAGS is live into a
19372   // successor.
19373   if (miI == BB->end()) {
19374     for (MachineBasicBlock::succ_iterator sItr = BB->succ_begin(),
19375                                           sEnd = BB->succ_end();
19376          sItr != sEnd; ++sItr) {
19377       MachineBasicBlock* succ = *sItr;
19378       if (succ->isLiveIn(X86::EFLAGS))
19379         return false;
19380     }
19381   }
19382
19383   // We found a def, or hit the end of the basic block and EFLAGS wasn't live
19384   // out. SelectMI should have a kill flag on EFLAGS.
19385   SelectItr->addRegisterKilled(X86::EFLAGS, TRI);
19386   return true;
19387 }
19388
19389 MachineBasicBlock *
19390 X86TargetLowering::EmitLoweredSelect(MachineInstr *MI,
19391                                      MachineBasicBlock *BB) const {
19392   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19393   DebugLoc DL = MI->getDebugLoc();
19394
19395   // To "insert" a SELECT_CC instruction, we actually have to insert the
19396   // diamond control-flow pattern.  The incoming instruction knows the
19397   // destination vreg to set, the condition code register to branch on, the
19398   // true/false values to select between, and a branch opcode to use.
19399   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19400   MachineFunction::iterator It = BB;
19401   ++It;
19402
19403   //  thisMBB:
19404   //  ...
19405   //   TrueVal = ...
19406   //   cmpTY ccX, r1, r2
19407   //   bCC copy1MBB
19408   //   fallthrough --> copy0MBB
19409   MachineBasicBlock *thisMBB = BB;
19410   MachineFunction *F = BB->getParent();
19411
19412   // We also lower double CMOVs:
19413   //   (CMOV (CMOV F, T, cc1), T, cc2)
19414   // to two successives branches.  For that, we look for another CMOV as the
19415   // following instruction.
19416   //
19417   // Without this, we would add a PHI between the two jumps, which ends up
19418   // creating a few copies all around. For instance, for
19419   //
19420   //    (sitofp (zext (fcmp une)))
19421   //
19422   // we would generate:
19423   //
19424   //         ucomiss %xmm1, %xmm0
19425   //         movss  <1.0f>, %xmm0
19426   //         movaps  %xmm0, %xmm1
19427   //         jne     .LBB5_2
19428   //         xorps   %xmm1, %xmm1
19429   // .LBB5_2:
19430   //         jp      .LBB5_4
19431   //         movaps  %xmm1, %xmm0
19432   // .LBB5_4:
19433   //         retq
19434   //
19435   // because this custom-inserter would have generated:
19436   //
19437   //   A
19438   //   | \
19439   //   |  B
19440   //   | /
19441   //   C
19442   //   | \
19443   //   |  D
19444   //   | /
19445   //   E
19446   //
19447   // A: X = ...; Y = ...
19448   // B: empty
19449   // C: Z = PHI [X, A], [Y, B]
19450   // D: empty
19451   // E: PHI [X, C], [Z, D]
19452   //
19453   // If we lower both CMOVs in a single step, we can instead generate:
19454   //
19455   //   A
19456   //   | \
19457   //   |  C
19458   //   | /|
19459   //   |/ |
19460   //   |  |
19461   //   |  D
19462   //   | /
19463   //   E
19464   //
19465   // A: X = ...; Y = ...
19466   // D: empty
19467   // E: PHI [X, A], [X, C], [Y, D]
19468   //
19469   // Which, in our sitofp/fcmp example, gives us something like:
19470   //
19471   //         ucomiss %xmm1, %xmm0
19472   //         movss  <1.0f>, %xmm0
19473   //         jne     .LBB5_4
19474   //         jp      .LBB5_4
19475   //         xorps   %xmm0, %xmm0
19476   // .LBB5_4:
19477   //         retq
19478   //
19479   MachineInstr *NextCMOV = nullptr;
19480   MachineBasicBlock::iterator NextMIIt =
19481       std::next(MachineBasicBlock::iterator(MI));
19482   if (NextMIIt != BB->end() && NextMIIt->getOpcode() == MI->getOpcode() &&
19483       NextMIIt->getOperand(2).getReg() == MI->getOperand(2).getReg() &&
19484       NextMIIt->getOperand(1).getReg() == MI->getOperand(0).getReg())
19485     NextCMOV = &*NextMIIt;
19486
19487   MachineBasicBlock *jcc1MBB = nullptr;
19488
19489   // If we have a double CMOV, we lower it to two successive branches to
19490   // the same block.  EFLAGS is used by both, so mark it as live in the second.
19491   if (NextCMOV) {
19492     jcc1MBB = F->CreateMachineBasicBlock(LLVM_BB);
19493     F->insert(It, jcc1MBB);
19494     jcc1MBB->addLiveIn(X86::EFLAGS);
19495   }
19496
19497   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
19498   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
19499   F->insert(It, copy0MBB);
19500   F->insert(It, sinkMBB);
19501
19502   // If the EFLAGS register isn't dead in the terminator, then claim that it's
19503   // live into the sink and copy blocks.
19504   const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
19505
19506   MachineInstr *LastEFLAGSUser = NextCMOV ? NextCMOV : MI;
19507   if (!LastEFLAGSUser->killsRegister(X86::EFLAGS) &&
19508       !checkAndUpdateEFLAGSKill(LastEFLAGSUser, BB, TRI)) {
19509     copy0MBB->addLiveIn(X86::EFLAGS);
19510     sinkMBB->addLiveIn(X86::EFLAGS);
19511   }
19512
19513   // Transfer the remainder of BB and its successor edges to sinkMBB.
19514   sinkMBB->splice(sinkMBB->begin(), BB,
19515                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
19516   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
19517
19518   // Add the true and fallthrough blocks as its successors.
19519   if (NextCMOV) {
19520     // The fallthrough block may be jcc1MBB, if we have a double CMOV.
19521     BB->addSuccessor(jcc1MBB);
19522
19523     // In that case, jcc1MBB will itself fallthrough the copy0MBB, and
19524     // jump to the sinkMBB.
19525     jcc1MBB->addSuccessor(copy0MBB);
19526     jcc1MBB->addSuccessor(sinkMBB);
19527   } else {
19528     BB->addSuccessor(copy0MBB);
19529   }
19530
19531   // The true block target of the first (or only) branch is always sinkMBB.
19532   BB->addSuccessor(sinkMBB);
19533
19534   // Create the conditional branch instruction.
19535   unsigned Opc =
19536     X86::GetCondBranchFromCond((X86::CondCode)MI->getOperand(3).getImm());
19537   BuildMI(BB, DL, TII->get(Opc)).addMBB(sinkMBB);
19538
19539   if (NextCMOV) {
19540     unsigned Opc2 = X86::GetCondBranchFromCond(
19541         (X86::CondCode)NextCMOV->getOperand(3).getImm());
19542     BuildMI(jcc1MBB, DL, TII->get(Opc2)).addMBB(sinkMBB);
19543   }
19544
19545   //  copy0MBB:
19546   //   %FalseValue = ...
19547   //   # fallthrough to sinkMBB
19548   copy0MBB->addSuccessor(sinkMBB);
19549
19550   //  sinkMBB:
19551   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
19552   //  ...
19553   MachineInstrBuilder MIB =
19554       BuildMI(*sinkMBB, sinkMBB->begin(), DL, TII->get(X86::PHI),
19555               MI->getOperand(0).getReg())
19556           .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB)
19557           .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
19558
19559   // If we have a double CMOV, the second Jcc provides the same incoming
19560   // value as the first Jcc (the True operand of the SELECT_CC/CMOV nodes).
19561   if (NextCMOV) {
19562     MIB.addReg(MI->getOperand(2).getReg()).addMBB(jcc1MBB);
19563     // Copy the PHI result to the register defined by the second CMOV.
19564     BuildMI(*sinkMBB, std::next(MachineBasicBlock::iterator(MIB.getInstr())),
19565             DL, TII->get(TargetOpcode::COPY), NextCMOV->getOperand(0).getReg())
19566         .addReg(MI->getOperand(0).getReg());
19567     NextCMOV->eraseFromParent();
19568   }
19569
19570   MI->eraseFromParent();   // The pseudo instruction is gone now.
19571   return sinkMBB;
19572 }
19573
19574 MachineBasicBlock *
19575 X86TargetLowering::EmitLoweredSegAlloca(MachineInstr *MI,
19576                                         MachineBasicBlock *BB) const {
19577   MachineFunction *MF = BB->getParent();
19578   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19579   DebugLoc DL = MI->getDebugLoc();
19580   const BasicBlock *LLVM_BB = BB->getBasicBlock();
19581
19582   assert(MF->shouldSplitStack());
19583
19584   const bool Is64Bit = Subtarget->is64Bit();
19585   const bool IsLP64 = Subtarget->isTarget64BitLP64();
19586
19587   const unsigned TlsReg = Is64Bit ? X86::FS : X86::GS;
19588   const unsigned TlsOffset = IsLP64 ? 0x70 : Is64Bit ? 0x40 : 0x30;
19589
19590   // BB:
19591   //  ... [Till the alloca]
19592   // If stacklet is not large enough, jump to mallocMBB
19593   //
19594   // bumpMBB:
19595   //  Allocate by subtracting from RSP
19596   //  Jump to continueMBB
19597   //
19598   // mallocMBB:
19599   //  Allocate by call to runtime
19600   //
19601   // continueMBB:
19602   //  ...
19603   //  [rest of original BB]
19604   //
19605
19606   MachineBasicBlock *mallocMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19607   MachineBasicBlock *bumpMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19608   MachineBasicBlock *continueMBB = MF->CreateMachineBasicBlock(LLVM_BB);
19609
19610   MachineRegisterInfo &MRI = MF->getRegInfo();
19611   const TargetRegisterClass *AddrRegClass =
19612     getRegClassFor(getPointerTy());
19613
19614   unsigned mallocPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19615     bumpSPPtrVReg = MRI.createVirtualRegister(AddrRegClass),
19616     tmpSPVReg = MRI.createVirtualRegister(AddrRegClass),
19617     SPLimitVReg = MRI.createVirtualRegister(AddrRegClass),
19618     sizeVReg = MI->getOperand(1).getReg(),
19619     physSPReg = IsLP64 || Subtarget->isTargetNaCl64() ? X86::RSP : X86::ESP;
19620
19621   MachineFunction::iterator MBBIter = BB;
19622   ++MBBIter;
19623
19624   MF->insert(MBBIter, bumpMBB);
19625   MF->insert(MBBIter, mallocMBB);
19626   MF->insert(MBBIter, continueMBB);
19627
19628   continueMBB->splice(continueMBB->begin(), BB,
19629                       std::next(MachineBasicBlock::iterator(MI)), BB->end());
19630   continueMBB->transferSuccessorsAndUpdatePHIs(BB);
19631
19632   // Add code to the main basic block to check if the stack limit has been hit,
19633   // and if so, jump to mallocMBB otherwise to bumpMBB.
19634   BuildMI(BB, DL, TII->get(TargetOpcode::COPY), tmpSPVReg).addReg(physSPReg);
19635   BuildMI(BB, DL, TII->get(IsLP64 ? X86::SUB64rr:X86::SUB32rr), SPLimitVReg)
19636     .addReg(tmpSPVReg).addReg(sizeVReg);
19637   BuildMI(BB, DL, TII->get(IsLP64 ? X86::CMP64mr:X86::CMP32mr))
19638     .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg)
19639     .addReg(SPLimitVReg);
19640   BuildMI(BB, DL, TII->get(X86::JG_1)).addMBB(mallocMBB);
19641
19642   // bumpMBB simply decreases the stack pointer, since we know the current
19643   // stacklet has enough space.
19644   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), physSPReg)
19645     .addReg(SPLimitVReg);
19646   BuildMI(bumpMBB, DL, TII->get(TargetOpcode::COPY), bumpSPPtrVReg)
19647     .addReg(SPLimitVReg);
19648   BuildMI(bumpMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19649
19650   // Calls into a routine in libgcc to allocate more space from the heap.
19651   const uint32_t *RegMask =
19652       Subtarget->getRegisterInfo()->getCallPreservedMask(*MF, CallingConv::C);
19653   if (IsLP64) {
19654     BuildMI(mallocMBB, DL, TII->get(X86::MOV64rr), X86::RDI)
19655       .addReg(sizeVReg);
19656     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19657       .addExternalSymbol("__morestack_allocate_stack_space")
19658       .addRegMask(RegMask)
19659       .addReg(X86::RDI, RegState::Implicit)
19660       .addReg(X86::RAX, RegState::ImplicitDefine);
19661   } else if (Is64Bit) {
19662     BuildMI(mallocMBB, DL, TII->get(X86::MOV32rr), X86::EDI)
19663       .addReg(sizeVReg);
19664     BuildMI(mallocMBB, DL, TII->get(X86::CALL64pcrel32))
19665       .addExternalSymbol("__morestack_allocate_stack_space")
19666       .addRegMask(RegMask)
19667       .addReg(X86::EDI, RegState::Implicit)
19668       .addReg(X86::EAX, RegState::ImplicitDefine);
19669   } else {
19670     BuildMI(mallocMBB, DL, TII->get(X86::SUB32ri), physSPReg).addReg(physSPReg)
19671       .addImm(12);
19672     BuildMI(mallocMBB, DL, TII->get(X86::PUSH32r)).addReg(sizeVReg);
19673     BuildMI(mallocMBB, DL, TII->get(X86::CALLpcrel32))
19674       .addExternalSymbol("__morestack_allocate_stack_space")
19675       .addRegMask(RegMask)
19676       .addReg(X86::EAX, RegState::ImplicitDefine);
19677   }
19678
19679   if (!Is64Bit)
19680     BuildMI(mallocMBB, DL, TII->get(X86::ADD32ri), physSPReg).addReg(physSPReg)
19681       .addImm(16);
19682
19683   BuildMI(mallocMBB, DL, TII->get(TargetOpcode::COPY), mallocPtrVReg)
19684     .addReg(IsLP64 ? X86::RAX : X86::EAX);
19685   BuildMI(mallocMBB, DL, TII->get(X86::JMP_1)).addMBB(continueMBB);
19686
19687   // Set up the CFG correctly.
19688   BB->addSuccessor(bumpMBB);
19689   BB->addSuccessor(mallocMBB);
19690   mallocMBB->addSuccessor(continueMBB);
19691   bumpMBB->addSuccessor(continueMBB);
19692
19693   // Take care of the PHI nodes.
19694   BuildMI(*continueMBB, continueMBB->begin(), DL, TII->get(X86::PHI),
19695           MI->getOperand(0).getReg())
19696     .addReg(mallocPtrVReg).addMBB(mallocMBB)
19697     .addReg(bumpSPPtrVReg).addMBB(bumpMBB);
19698
19699   // Delete the original pseudo instruction.
19700   MI->eraseFromParent();
19701
19702   // And we're done.
19703   return continueMBB;
19704 }
19705
19706 MachineBasicBlock *
19707 X86TargetLowering::EmitLoweredWinAlloca(MachineInstr *MI,
19708                                         MachineBasicBlock *BB) const {
19709   DebugLoc DL = MI->getDebugLoc();
19710
19711   assert(!Subtarget->isTargetMachO());
19712
19713   Subtarget->getFrameLowering()->emitStackProbeCall(*BB->getParent(), *BB, MI,
19714                                                     DL);
19715
19716   MI->eraseFromParent();   // The pseudo instruction is gone now.
19717   return BB;
19718 }
19719
19720 MachineBasicBlock *
19721 X86TargetLowering::EmitLoweredTLSCall(MachineInstr *MI,
19722                                       MachineBasicBlock *BB) const {
19723   // This is pretty easy.  We're taking the value that we received from
19724   // our load from the relocation, sticking it in either RDI (x86-64)
19725   // or EAX and doing an indirect call.  The return value will then
19726   // be in the normal return register.
19727   MachineFunction *F = BB->getParent();
19728   const X86InstrInfo *TII = Subtarget->getInstrInfo();
19729   DebugLoc DL = MI->getDebugLoc();
19730
19731   assert(Subtarget->isTargetDarwin() && "Darwin only instr emitted?");
19732   assert(MI->getOperand(3).isGlobal() && "This should be a global");
19733
19734   // Get a register mask for the lowered call.
19735   // FIXME: The 32-bit calls have non-standard calling conventions. Use a
19736   // proper register mask.
19737   const uint32_t *RegMask =
19738       Subtarget->getRegisterInfo()->getCallPreservedMask(*F, CallingConv::C);
19739   if (Subtarget->is64Bit()) {
19740     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19741                                       TII->get(X86::MOV64rm), X86::RDI)
19742     .addReg(X86::RIP)
19743     .addImm(0).addReg(0)
19744     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19745                       MI->getOperand(3).getTargetFlags())
19746     .addReg(0);
19747     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL64m));
19748     addDirectMem(MIB, X86::RDI);
19749     MIB.addReg(X86::RAX, RegState::ImplicitDefine).addRegMask(RegMask);
19750   } else if (F->getTarget().getRelocationModel() != Reloc::PIC_) {
19751     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19752                                       TII->get(X86::MOV32rm), X86::EAX)
19753     .addReg(0)
19754     .addImm(0).addReg(0)
19755     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19756                       MI->getOperand(3).getTargetFlags())
19757     .addReg(0);
19758     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19759     addDirectMem(MIB, X86::EAX);
19760     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19761   } else {
19762     MachineInstrBuilder MIB = BuildMI(*BB, MI, DL,
19763                                       TII->get(X86::MOV32rm), X86::EAX)
19764     .addReg(TII->getGlobalBaseReg(F))
19765     .addImm(0).addReg(0)
19766     .addGlobalAddress(MI->getOperand(3).getGlobal(), 0,
19767                       MI->getOperand(3).getTargetFlags())
19768     .addReg(0);
19769     MIB = BuildMI(*BB, MI, DL, TII->get(X86::CALL32m));
19770     addDirectMem(MIB, X86::EAX);
19771     MIB.addReg(X86::EAX, RegState::ImplicitDefine).addRegMask(RegMask);
19772   }
19773
19774   MI->eraseFromParent(); // The pseudo instruction is gone now.
19775   return BB;
19776 }
19777
19778 MachineBasicBlock *
19779 X86TargetLowering::emitEHSjLjSetJmp(MachineInstr *MI,
19780                                     MachineBasicBlock *MBB) const {
19781   DebugLoc DL = MI->getDebugLoc();
19782   MachineFunction *MF = MBB->getParent();
19783   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19784   MachineRegisterInfo &MRI = MF->getRegInfo();
19785
19786   const BasicBlock *BB = MBB->getBasicBlock();
19787   MachineFunction::iterator I = MBB;
19788   ++I;
19789
19790   // Memory Reference
19791   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19792   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19793
19794   unsigned DstReg;
19795   unsigned MemOpndSlot = 0;
19796
19797   unsigned CurOp = 0;
19798
19799   DstReg = MI->getOperand(CurOp++).getReg();
19800   const TargetRegisterClass *RC = MRI.getRegClass(DstReg);
19801   assert(RC->hasType(MVT::i32) && "Invalid destination!");
19802   unsigned mainDstReg = MRI.createVirtualRegister(RC);
19803   unsigned restoreDstReg = MRI.createVirtualRegister(RC);
19804
19805   MemOpndSlot = CurOp;
19806
19807   MVT PVT = getPointerTy();
19808   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19809          "Invalid Pointer Size!");
19810
19811   // For v = setjmp(buf), we generate
19812   //
19813   // thisMBB:
19814   //  buf[LabelOffset] = restoreMBB
19815   //  SjLjSetup restoreMBB
19816   //
19817   // mainMBB:
19818   //  v_main = 0
19819   //
19820   // sinkMBB:
19821   //  v = phi(main, restore)
19822   //
19823   // restoreMBB:
19824   //  if base pointer being used, load it from frame
19825   //  v_restore = 1
19826
19827   MachineBasicBlock *thisMBB = MBB;
19828   MachineBasicBlock *mainMBB = MF->CreateMachineBasicBlock(BB);
19829   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(BB);
19830   MachineBasicBlock *restoreMBB = MF->CreateMachineBasicBlock(BB);
19831   MF->insert(I, mainMBB);
19832   MF->insert(I, sinkMBB);
19833   MF->push_back(restoreMBB);
19834
19835   MachineInstrBuilder MIB;
19836
19837   // Transfer the remainder of BB and its successor edges to sinkMBB.
19838   sinkMBB->splice(sinkMBB->begin(), MBB,
19839                   std::next(MachineBasicBlock::iterator(MI)), MBB->end());
19840   sinkMBB->transferSuccessorsAndUpdatePHIs(MBB);
19841
19842   // thisMBB:
19843   unsigned PtrStoreOpc = 0;
19844   unsigned LabelReg = 0;
19845   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19846   Reloc::Model RM = MF->getTarget().getRelocationModel();
19847   bool UseImmLabel = (MF->getTarget().getCodeModel() == CodeModel::Small) &&
19848                      (RM == Reloc::Static || RM == Reloc::DynamicNoPIC);
19849
19850   // Prepare IP either in reg or imm.
19851   if (!UseImmLabel) {
19852     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mr : X86::MOV32mr;
19853     const TargetRegisterClass *PtrRC = getRegClassFor(PVT);
19854     LabelReg = MRI.createVirtualRegister(PtrRC);
19855     if (Subtarget->is64Bit()) {
19856       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA64r), LabelReg)
19857               .addReg(X86::RIP)
19858               .addImm(0)
19859               .addReg(0)
19860               .addMBB(restoreMBB)
19861               .addReg(0);
19862     } else {
19863       const X86InstrInfo *XII = static_cast<const X86InstrInfo*>(TII);
19864       MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::LEA32r), LabelReg)
19865               .addReg(XII->getGlobalBaseReg(MF))
19866               .addImm(0)
19867               .addReg(0)
19868               .addMBB(restoreMBB, Subtarget->ClassifyBlockAddressReference())
19869               .addReg(0);
19870     }
19871   } else
19872     PtrStoreOpc = (PVT == MVT::i64) ? X86::MOV64mi32 : X86::MOV32mi;
19873   // Store IP
19874   MIB = BuildMI(*thisMBB, MI, DL, TII->get(PtrStoreOpc));
19875   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19876     if (i == X86::AddrDisp)
19877       MIB.addDisp(MI->getOperand(MemOpndSlot + i), LabelOffset);
19878     else
19879       MIB.addOperand(MI->getOperand(MemOpndSlot + i));
19880   }
19881   if (!UseImmLabel)
19882     MIB.addReg(LabelReg);
19883   else
19884     MIB.addMBB(restoreMBB);
19885   MIB.setMemRefs(MMOBegin, MMOEnd);
19886   // Setup
19887   MIB = BuildMI(*thisMBB, MI, DL, TII->get(X86::EH_SjLj_Setup))
19888           .addMBB(restoreMBB);
19889
19890   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19891   MIB.addRegMask(RegInfo->getNoPreservedMask());
19892   thisMBB->addSuccessor(mainMBB);
19893   thisMBB->addSuccessor(restoreMBB);
19894
19895   // mainMBB:
19896   //  EAX = 0
19897   BuildMI(mainMBB, DL, TII->get(X86::MOV32r0), mainDstReg);
19898   mainMBB->addSuccessor(sinkMBB);
19899
19900   // sinkMBB:
19901   BuildMI(*sinkMBB, sinkMBB->begin(), DL,
19902           TII->get(X86::PHI), DstReg)
19903     .addReg(mainDstReg).addMBB(mainMBB)
19904     .addReg(restoreDstReg).addMBB(restoreMBB);
19905
19906   // restoreMBB:
19907   if (RegInfo->hasBasePointer(*MF)) {
19908     const bool Uses64BitFramePtr =
19909         Subtarget->isTarget64BitLP64() || Subtarget->isTargetNaCl64();
19910     X86MachineFunctionInfo *X86FI = MF->getInfo<X86MachineFunctionInfo>();
19911     X86FI->setRestoreBasePointer(MF);
19912     unsigned FramePtr = RegInfo->getFrameRegister(*MF);
19913     unsigned BasePtr = RegInfo->getBaseRegister();
19914     unsigned Opm = Uses64BitFramePtr ? X86::MOV64rm : X86::MOV32rm;
19915     addRegOffset(BuildMI(restoreMBB, DL, TII->get(Opm), BasePtr),
19916                  FramePtr, true, X86FI->getRestoreBasePointerOffset())
19917       .setMIFlag(MachineInstr::FrameSetup);
19918   }
19919   BuildMI(restoreMBB, DL, TII->get(X86::MOV32ri), restoreDstReg).addImm(1);
19920   BuildMI(restoreMBB, DL, TII->get(X86::JMP_1)).addMBB(sinkMBB);
19921   restoreMBB->addSuccessor(sinkMBB);
19922
19923   MI->eraseFromParent();
19924   return sinkMBB;
19925 }
19926
19927 MachineBasicBlock *
19928 X86TargetLowering::emitEHSjLjLongJmp(MachineInstr *MI,
19929                                      MachineBasicBlock *MBB) const {
19930   DebugLoc DL = MI->getDebugLoc();
19931   MachineFunction *MF = MBB->getParent();
19932   const TargetInstrInfo *TII = Subtarget->getInstrInfo();
19933   MachineRegisterInfo &MRI = MF->getRegInfo();
19934
19935   // Memory Reference
19936   MachineInstr::mmo_iterator MMOBegin = MI->memoperands_begin();
19937   MachineInstr::mmo_iterator MMOEnd = MI->memoperands_end();
19938
19939   MVT PVT = getPointerTy();
19940   assert((PVT == MVT::i64 || PVT == MVT::i32) &&
19941          "Invalid Pointer Size!");
19942
19943   const TargetRegisterClass *RC =
19944     (PVT == MVT::i64) ? &X86::GR64RegClass : &X86::GR32RegClass;
19945   unsigned Tmp = MRI.createVirtualRegister(RC);
19946   // Since FP is only updated here but NOT referenced, it's treated as GPR.
19947   const X86RegisterInfo *RegInfo = Subtarget->getRegisterInfo();
19948   unsigned FP = (PVT == MVT::i64) ? X86::RBP : X86::EBP;
19949   unsigned SP = RegInfo->getStackRegister();
19950
19951   MachineInstrBuilder MIB;
19952
19953   const int64_t LabelOffset = 1 * PVT.getStoreSize();
19954   const int64_t SPOffset = 2 * PVT.getStoreSize();
19955
19956   unsigned PtrLoadOpc = (PVT == MVT::i64) ? X86::MOV64rm : X86::MOV32rm;
19957   unsigned IJmpOpc = (PVT == MVT::i64) ? X86::JMP64r : X86::JMP32r;
19958
19959   // Reload FP
19960   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), FP);
19961   for (unsigned i = 0; i < X86::AddrNumOperands; ++i)
19962     MIB.addOperand(MI->getOperand(i));
19963   MIB.setMemRefs(MMOBegin, MMOEnd);
19964   // Reload IP
19965   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), Tmp);
19966   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19967     if (i == X86::AddrDisp)
19968       MIB.addDisp(MI->getOperand(i), LabelOffset);
19969     else
19970       MIB.addOperand(MI->getOperand(i));
19971   }
19972   MIB.setMemRefs(MMOBegin, MMOEnd);
19973   // Reload SP
19974   MIB = BuildMI(*MBB, MI, DL, TII->get(PtrLoadOpc), SP);
19975   for (unsigned i = 0; i < X86::AddrNumOperands; ++i) {
19976     if (i == X86::AddrDisp)
19977       MIB.addDisp(MI->getOperand(i), SPOffset);
19978     else
19979       MIB.addOperand(MI->getOperand(i));
19980   }
19981   MIB.setMemRefs(MMOBegin, MMOEnd);
19982   // Jump
19983   BuildMI(*MBB, MI, DL, TII->get(IJmpOpc)).addReg(Tmp);
19984
19985   MI->eraseFromParent();
19986   return MBB;
19987 }
19988
19989 // Replace 213-type (isel default) FMA3 instructions with 231-type for
19990 // accumulator loops. Writing back to the accumulator allows the coalescer
19991 // to remove extra copies in the loop.
19992 // FIXME: Do this on AVX512.  We don't support 231 variants yet (PR23937).
19993 MachineBasicBlock *
19994 X86TargetLowering::emitFMA3Instr(MachineInstr *MI,
19995                                  MachineBasicBlock *MBB) const {
19996   MachineOperand &AddendOp = MI->getOperand(3);
19997
19998   // Bail out early if the addend isn't a register - we can't switch these.
19999   if (!AddendOp.isReg())
20000     return MBB;
20001
20002   MachineFunction &MF = *MBB->getParent();
20003   MachineRegisterInfo &MRI = MF.getRegInfo();
20004
20005   // Check whether the addend is defined by a PHI:
20006   assert(MRI.hasOneDef(AddendOp.getReg()) && "Multiple defs in SSA?");
20007   MachineInstr &AddendDef = *MRI.def_instr_begin(AddendOp.getReg());
20008   if (!AddendDef.isPHI())
20009     return MBB;
20010
20011   // Look for the following pattern:
20012   // loop:
20013   //   %addend = phi [%entry, 0], [%loop, %result]
20014   //   ...
20015   //   %result<tied1> = FMA213 %m2<tied0>, %m1, %addend
20016
20017   // Replace with:
20018   //   loop:
20019   //   %addend = phi [%entry, 0], [%loop, %result]
20020   //   ...
20021   //   %result<tied1> = FMA231 %addend<tied0>, %m1, %m2
20022
20023   for (unsigned i = 1, e = AddendDef.getNumOperands(); i < e; i += 2) {
20024     assert(AddendDef.getOperand(i).isReg());
20025     MachineOperand PHISrcOp = AddendDef.getOperand(i);
20026     MachineInstr &PHISrcInst = *MRI.def_instr_begin(PHISrcOp.getReg());
20027     if (&PHISrcInst == MI) {
20028       // Found a matching instruction.
20029       unsigned NewFMAOpc = 0;
20030       switch (MI->getOpcode()) {
20031         case X86::VFMADDPDr213r: NewFMAOpc = X86::VFMADDPDr231r; break;
20032         case X86::VFMADDPSr213r: NewFMAOpc = X86::VFMADDPSr231r; break;
20033         case X86::VFMADDSDr213r: NewFMAOpc = X86::VFMADDSDr231r; break;
20034         case X86::VFMADDSSr213r: NewFMAOpc = X86::VFMADDSSr231r; break;
20035         case X86::VFMSUBPDr213r: NewFMAOpc = X86::VFMSUBPDr231r; break;
20036         case X86::VFMSUBPSr213r: NewFMAOpc = X86::VFMSUBPSr231r; break;
20037         case X86::VFMSUBSDr213r: NewFMAOpc = X86::VFMSUBSDr231r; break;
20038         case X86::VFMSUBSSr213r: NewFMAOpc = X86::VFMSUBSSr231r; break;
20039         case X86::VFNMADDPDr213r: NewFMAOpc = X86::VFNMADDPDr231r; break;
20040         case X86::VFNMADDPSr213r: NewFMAOpc = X86::VFNMADDPSr231r; break;
20041         case X86::VFNMADDSDr213r: NewFMAOpc = X86::VFNMADDSDr231r; break;
20042         case X86::VFNMADDSSr213r: NewFMAOpc = X86::VFNMADDSSr231r; break;
20043         case X86::VFNMSUBPDr213r: NewFMAOpc = X86::VFNMSUBPDr231r; break;
20044         case X86::VFNMSUBPSr213r: NewFMAOpc = X86::VFNMSUBPSr231r; break;
20045         case X86::VFNMSUBSDr213r: NewFMAOpc = X86::VFNMSUBSDr231r; break;
20046         case X86::VFNMSUBSSr213r: NewFMAOpc = X86::VFNMSUBSSr231r; break;
20047         case X86::VFMADDSUBPDr213r: NewFMAOpc = X86::VFMADDSUBPDr231r; break;
20048         case X86::VFMADDSUBPSr213r: NewFMAOpc = X86::VFMADDSUBPSr231r; break;
20049         case X86::VFMSUBADDPDr213r: NewFMAOpc = X86::VFMSUBADDPDr231r; break;
20050         case X86::VFMSUBADDPSr213r: NewFMAOpc = X86::VFMSUBADDPSr231r; break;
20051
20052         case X86::VFMADDPDr213rY: NewFMAOpc = X86::VFMADDPDr231rY; break;
20053         case X86::VFMADDPSr213rY: NewFMAOpc = X86::VFMADDPSr231rY; break;
20054         case X86::VFMSUBPDr213rY: NewFMAOpc = X86::VFMSUBPDr231rY; break;
20055         case X86::VFMSUBPSr213rY: NewFMAOpc = X86::VFMSUBPSr231rY; break;
20056         case X86::VFNMADDPDr213rY: NewFMAOpc = X86::VFNMADDPDr231rY; break;
20057         case X86::VFNMADDPSr213rY: NewFMAOpc = X86::VFNMADDPSr231rY; break;
20058         case X86::VFNMSUBPDr213rY: NewFMAOpc = X86::VFNMSUBPDr231rY; break;
20059         case X86::VFNMSUBPSr213rY: NewFMAOpc = X86::VFNMSUBPSr231rY; break;
20060         case X86::VFMADDSUBPDr213rY: NewFMAOpc = X86::VFMADDSUBPDr231rY; break;
20061         case X86::VFMADDSUBPSr213rY: NewFMAOpc = X86::VFMADDSUBPSr231rY; break;
20062         case X86::VFMSUBADDPDr213rY: NewFMAOpc = X86::VFMSUBADDPDr231rY; break;
20063         case X86::VFMSUBADDPSr213rY: NewFMAOpc = X86::VFMSUBADDPSr231rY; break;
20064         default: llvm_unreachable("Unrecognized FMA variant.");
20065       }
20066
20067       const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
20068       MachineInstrBuilder MIB =
20069         BuildMI(MF, MI->getDebugLoc(), TII.get(NewFMAOpc))
20070         .addOperand(MI->getOperand(0))
20071         .addOperand(MI->getOperand(3))
20072         .addOperand(MI->getOperand(2))
20073         .addOperand(MI->getOperand(1));
20074       MBB->insert(MachineBasicBlock::iterator(MI), MIB);
20075       MI->eraseFromParent();
20076     }
20077   }
20078
20079   return MBB;
20080 }
20081
20082 MachineBasicBlock *
20083 X86TargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
20084                                                MachineBasicBlock *BB) const {
20085   switch (MI->getOpcode()) {
20086   default: llvm_unreachable("Unexpected instr type to insert");
20087   case X86::TAILJMPd64:
20088   case X86::TAILJMPr64:
20089   case X86::TAILJMPm64:
20090   case X86::TAILJMPd64_REX:
20091   case X86::TAILJMPr64_REX:
20092   case X86::TAILJMPm64_REX:
20093     llvm_unreachable("TAILJMP64 would not be touched here.");
20094   case X86::TCRETURNdi64:
20095   case X86::TCRETURNri64:
20096   case X86::TCRETURNmi64:
20097     return BB;
20098   case X86::WIN_ALLOCA:
20099     return EmitLoweredWinAlloca(MI, BB);
20100   case X86::SEG_ALLOCA_32:
20101   case X86::SEG_ALLOCA_64:
20102     return EmitLoweredSegAlloca(MI, BB);
20103   case X86::TLSCall_32:
20104   case X86::TLSCall_64:
20105     return EmitLoweredTLSCall(MI, BB);
20106   case X86::CMOV_GR8:
20107   case X86::CMOV_FR32:
20108   case X86::CMOV_FR64:
20109   case X86::CMOV_V4F32:
20110   case X86::CMOV_V2F64:
20111   case X86::CMOV_V2I64:
20112   case X86::CMOV_V8F32:
20113   case X86::CMOV_V4F64:
20114   case X86::CMOV_V4I64:
20115   case X86::CMOV_V16F32:
20116   case X86::CMOV_V8F64:
20117   case X86::CMOV_V8I64:
20118   case X86::CMOV_GR16:
20119   case X86::CMOV_GR32:
20120   case X86::CMOV_RFP32:
20121   case X86::CMOV_RFP64:
20122   case X86::CMOV_RFP80:
20123   case X86::CMOV_V8I1:
20124   case X86::CMOV_V16I1:
20125   case X86::CMOV_V32I1:
20126   case X86::CMOV_V64I1:
20127     return EmitLoweredSelect(MI, BB);
20128
20129   case X86::FP32_TO_INT16_IN_MEM:
20130   case X86::FP32_TO_INT32_IN_MEM:
20131   case X86::FP32_TO_INT64_IN_MEM:
20132   case X86::FP64_TO_INT16_IN_MEM:
20133   case X86::FP64_TO_INT32_IN_MEM:
20134   case X86::FP64_TO_INT64_IN_MEM:
20135   case X86::FP80_TO_INT16_IN_MEM:
20136   case X86::FP80_TO_INT32_IN_MEM:
20137   case X86::FP80_TO_INT64_IN_MEM: {
20138     MachineFunction *F = BB->getParent();
20139     const TargetInstrInfo *TII = Subtarget->getInstrInfo();
20140     DebugLoc DL = MI->getDebugLoc();
20141
20142     // Change the floating point control register to use "round towards zero"
20143     // mode when truncating to an integer value.
20144     int CWFrameIdx = F->getFrameInfo()->CreateStackObject(2, 2, false);
20145     addFrameReference(BuildMI(*BB, MI, DL,
20146                               TII->get(X86::FNSTCW16m)), CWFrameIdx);
20147
20148     // Load the old value of the high byte of the control word...
20149     unsigned OldCW =
20150       F->getRegInfo().createVirtualRegister(&X86::GR16RegClass);
20151     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16rm), OldCW),
20152                       CWFrameIdx);
20153
20154     // Set the high part to be round to zero...
20155     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mi)), CWFrameIdx)
20156       .addImm(0xC7F);
20157
20158     // Reload the modified control word now...
20159     addFrameReference(BuildMI(*BB, MI, DL,
20160                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20161
20162     // Restore the memory image of control word to original value
20163     addFrameReference(BuildMI(*BB, MI, DL, TII->get(X86::MOV16mr)), CWFrameIdx)
20164       .addReg(OldCW);
20165
20166     // Get the X86 opcode to use.
20167     unsigned Opc;
20168     switch (MI->getOpcode()) {
20169     default: llvm_unreachable("illegal opcode!");
20170     case X86::FP32_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m32; break;
20171     case X86::FP32_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m32; break;
20172     case X86::FP32_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m32; break;
20173     case X86::FP64_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m64; break;
20174     case X86::FP64_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m64; break;
20175     case X86::FP64_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m64; break;
20176     case X86::FP80_TO_INT16_IN_MEM: Opc = X86::IST_Fp16m80; break;
20177     case X86::FP80_TO_INT32_IN_MEM: Opc = X86::IST_Fp32m80; break;
20178     case X86::FP80_TO_INT64_IN_MEM: Opc = X86::IST_Fp64m80; break;
20179     }
20180
20181     X86AddressMode AM;
20182     MachineOperand &Op = MI->getOperand(0);
20183     if (Op.isReg()) {
20184       AM.BaseType = X86AddressMode::RegBase;
20185       AM.Base.Reg = Op.getReg();
20186     } else {
20187       AM.BaseType = X86AddressMode::FrameIndexBase;
20188       AM.Base.FrameIndex = Op.getIndex();
20189     }
20190     Op = MI->getOperand(1);
20191     if (Op.isImm())
20192       AM.Scale = Op.getImm();
20193     Op = MI->getOperand(2);
20194     if (Op.isImm())
20195       AM.IndexReg = Op.getImm();
20196     Op = MI->getOperand(3);
20197     if (Op.isGlobal()) {
20198       AM.GV = Op.getGlobal();
20199     } else {
20200       AM.Disp = Op.getImm();
20201     }
20202     addFullAddress(BuildMI(*BB, MI, DL, TII->get(Opc)), AM)
20203                       .addReg(MI->getOperand(X86::AddrNumOperands).getReg());
20204
20205     // Reload the original control word now.
20206     addFrameReference(BuildMI(*BB, MI, DL,
20207                               TII->get(X86::FLDCW16m)), CWFrameIdx);
20208
20209     MI->eraseFromParent();   // The pseudo instruction is gone now.
20210     return BB;
20211   }
20212     // String/text processing lowering.
20213   case X86::PCMPISTRM128REG:
20214   case X86::VPCMPISTRM128REG:
20215   case X86::PCMPISTRM128MEM:
20216   case X86::VPCMPISTRM128MEM:
20217   case X86::PCMPESTRM128REG:
20218   case X86::VPCMPESTRM128REG:
20219   case X86::PCMPESTRM128MEM:
20220   case X86::VPCMPESTRM128MEM:
20221     assert(Subtarget->hasSSE42() &&
20222            "Target must have SSE4.2 or AVX features enabled");
20223     return EmitPCMPSTRM(MI, BB, Subtarget->getInstrInfo());
20224
20225   // String/text processing lowering.
20226   case X86::PCMPISTRIREG:
20227   case X86::VPCMPISTRIREG:
20228   case X86::PCMPISTRIMEM:
20229   case X86::VPCMPISTRIMEM:
20230   case X86::PCMPESTRIREG:
20231   case X86::VPCMPESTRIREG:
20232   case X86::PCMPESTRIMEM:
20233   case X86::VPCMPESTRIMEM:
20234     assert(Subtarget->hasSSE42() &&
20235            "Target must have SSE4.2 or AVX features enabled");
20236     return EmitPCMPSTRI(MI, BB, Subtarget->getInstrInfo());
20237
20238   // Thread synchronization.
20239   case X86::MONITOR:
20240     return EmitMonitor(MI, BB, Subtarget);
20241
20242   // xbegin
20243   case X86::XBEGIN:
20244     return EmitXBegin(MI, BB, Subtarget->getInstrInfo());
20245
20246   case X86::VASTART_SAVE_XMM_REGS:
20247     return EmitVAStartSaveXMMRegsWithCustomInserter(MI, BB);
20248
20249   case X86::VAARG_64:
20250     return EmitVAARG64WithCustomInserter(MI, BB);
20251
20252   case X86::EH_SjLj_SetJmp32:
20253   case X86::EH_SjLj_SetJmp64:
20254     return emitEHSjLjSetJmp(MI, BB);
20255
20256   case X86::EH_SjLj_LongJmp32:
20257   case X86::EH_SjLj_LongJmp64:
20258     return emitEHSjLjLongJmp(MI, BB);
20259
20260   case TargetOpcode::STATEPOINT:
20261     // As an implementation detail, STATEPOINT shares the STACKMAP format at
20262     // this point in the process.  We diverge later.
20263     return emitPatchPoint(MI, BB);
20264
20265   case TargetOpcode::STACKMAP:
20266   case TargetOpcode::PATCHPOINT:
20267     return emitPatchPoint(MI, BB);
20268
20269   case X86::VFMADDPDr213r:
20270   case X86::VFMADDPSr213r:
20271   case X86::VFMADDSDr213r:
20272   case X86::VFMADDSSr213r:
20273   case X86::VFMSUBPDr213r:
20274   case X86::VFMSUBPSr213r:
20275   case X86::VFMSUBSDr213r:
20276   case X86::VFMSUBSSr213r:
20277   case X86::VFNMADDPDr213r:
20278   case X86::VFNMADDPSr213r:
20279   case X86::VFNMADDSDr213r:
20280   case X86::VFNMADDSSr213r:
20281   case X86::VFNMSUBPDr213r:
20282   case X86::VFNMSUBPSr213r:
20283   case X86::VFNMSUBSDr213r:
20284   case X86::VFNMSUBSSr213r:
20285   case X86::VFMADDSUBPDr213r:
20286   case X86::VFMADDSUBPSr213r:
20287   case X86::VFMSUBADDPDr213r:
20288   case X86::VFMSUBADDPSr213r:
20289   case X86::VFMADDPDr213rY:
20290   case X86::VFMADDPSr213rY:
20291   case X86::VFMSUBPDr213rY:
20292   case X86::VFMSUBPSr213rY:
20293   case X86::VFNMADDPDr213rY:
20294   case X86::VFNMADDPSr213rY:
20295   case X86::VFNMSUBPDr213rY:
20296   case X86::VFNMSUBPSr213rY:
20297   case X86::VFMADDSUBPDr213rY:
20298   case X86::VFMADDSUBPSr213rY:
20299   case X86::VFMSUBADDPDr213rY:
20300   case X86::VFMSUBADDPSr213rY:
20301     return emitFMA3Instr(MI, BB);
20302   }
20303 }
20304
20305 //===----------------------------------------------------------------------===//
20306 //                           X86 Optimization Hooks
20307 //===----------------------------------------------------------------------===//
20308
20309 void X86TargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
20310                                                       APInt &KnownZero,
20311                                                       APInt &KnownOne,
20312                                                       const SelectionDAG &DAG,
20313                                                       unsigned Depth) const {
20314   unsigned BitWidth = KnownZero.getBitWidth();
20315   unsigned Opc = Op.getOpcode();
20316   assert((Opc >= ISD::BUILTIN_OP_END ||
20317           Opc == ISD::INTRINSIC_WO_CHAIN ||
20318           Opc == ISD::INTRINSIC_W_CHAIN ||
20319           Opc == ISD::INTRINSIC_VOID) &&
20320          "Should use MaskedValueIsZero if you don't know whether Op"
20321          " is a target node!");
20322
20323   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
20324   switch (Opc) {
20325   default: break;
20326   case X86ISD::ADD:
20327   case X86ISD::SUB:
20328   case X86ISD::ADC:
20329   case X86ISD::SBB:
20330   case X86ISD::SMUL:
20331   case X86ISD::UMUL:
20332   case X86ISD::INC:
20333   case X86ISD::DEC:
20334   case X86ISD::OR:
20335   case X86ISD::XOR:
20336   case X86ISD::AND:
20337     // These nodes' second result is a boolean.
20338     if (Op.getResNo() == 0)
20339       break;
20340     // Fallthrough
20341   case X86ISD::SETCC:
20342     KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
20343     break;
20344   case ISD::INTRINSIC_WO_CHAIN: {
20345     unsigned IntId = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
20346     unsigned NumLoBits = 0;
20347     switch (IntId) {
20348     default: break;
20349     case Intrinsic::x86_sse_movmsk_ps:
20350     case Intrinsic::x86_avx_movmsk_ps_256:
20351     case Intrinsic::x86_sse2_movmsk_pd:
20352     case Intrinsic::x86_avx_movmsk_pd_256:
20353     case Intrinsic::x86_mmx_pmovmskb:
20354     case Intrinsic::x86_sse2_pmovmskb_128:
20355     case Intrinsic::x86_avx2_pmovmskb: {
20356       // High bits of movmskp{s|d}, pmovmskb are known zero.
20357       switch (IntId) {
20358         default: llvm_unreachable("Impossible intrinsic");  // Can't reach here.
20359         case Intrinsic::x86_sse_movmsk_ps:      NumLoBits = 4; break;
20360         case Intrinsic::x86_avx_movmsk_ps_256:  NumLoBits = 8; break;
20361         case Intrinsic::x86_sse2_movmsk_pd:     NumLoBits = 2; break;
20362         case Intrinsic::x86_avx_movmsk_pd_256:  NumLoBits = 4; break;
20363         case Intrinsic::x86_mmx_pmovmskb:       NumLoBits = 8; break;
20364         case Intrinsic::x86_sse2_pmovmskb_128:  NumLoBits = 16; break;
20365         case Intrinsic::x86_avx2_pmovmskb:      NumLoBits = 32; break;
20366       }
20367       KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - NumLoBits);
20368       break;
20369     }
20370     }
20371     break;
20372   }
20373   }
20374 }
20375
20376 unsigned X86TargetLowering::ComputeNumSignBitsForTargetNode(
20377   SDValue Op,
20378   const SelectionDAG &,
20379   unsigned Depth) const {
20380   // SETCC_CARRY sets the dest to ~0 for true or 0 for false.
20381   if (Op.getOpcode() == X86ISD::SETCC_CARRY)
20382     return Op.getValueType().getScalarType().getSizeInBits();
20383
20384   // Fallback case.
20385   return 1;
20386 }
20387
20388 /// isGAPlusOffset - Returns true (and the GlobalValue and the offset) if the
20389 /// node is a GlobalAddress + offset.
20390 bool X86TargetLowering::isGAPlusOffset(SDNode *N,
20391                                        const GlobalValue* &GA,
20392                                        int64_t &Offset) const {
20393   if (N->getOpcode() == X86ISD::Wrapper) {
20394     if (isa<GlobalAddressSDNode>(N->getOperand(0))) {
20395       GA = cast<GlobalAddressSDNode>(N->getOperand(0))->getGlobal();
20396       Offset = cast<GlobalAddressSDNode>(N->getOperand(0))->getOffset();
20397       return true;
20398     }
20399   }
20400   return TargetLowering::isGAPlusOffset(N, GA, Offset);
20401 }
20402
20403 /// isShuffleHigh128VectorInsertLow - Checks whether the shuffle node is the
20404 /// same as extracting the high 128-bit part of 256-bit vector and then
20405 /// inserting the result into the low part of a new 256-bit vector
20406 static bool isShuffleHigh128VectorInsertLow(ShuffleVectorSDNode *SVOp) {
20407   EVT VT = SVOp->getValueType(0);
20408   unsigned NumElems = VT.getVectorNumElements();
20409
20410   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20411   for (unsigned i = 0, j = NumElems/2; i != NumElems/2; ++i, ++j)
20412     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20413         SVOp->getMaskElt(j) >= 0)
20414       return false;
20415
20416   return true;
20417 }
20418
20419 /// isShuffleLow128VectorInsertHigh - Checks whether the shuffle node is the
20420 /// same as extracting the low 128-bit part of 256-bit vector and then
20421 /// inserting the result into the high part of a new 256-bit vector
20422 static bool isShuffleLow128VectorInsertHigh(ShuffleVectorSDNode *SVOp) {
20423   EVT VT = SVOp->getValueType(0);
20424   unsigned NumElems = VT.getVectorNumElements();
20425
20426   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20427   for (unsigned i = NumElems/2, j = 0; i != NumElems; ++i, ++j)
20428     if (!isUndefOrEqual(SVOp->getMaskElt(i), j) ||
20429         SVOp->getMaskElt(j) >= 0)
20430       return false;
20431
20432   return true;
20433 }
20434
20435 /// PerformShuffleCombine256 - Performs shuffle combines for 256-bit vectors.
20436 static SDValue PerformShuffleCombine256(SDNode *N, SelectionDAG &DAG,
20437                                         TargetLowering::DAGCombinerInfo &DCI,
20438                                         const X86Subtarget* Subtarget) {
20439   SDLoc dl(N);
20440   ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
20441   SDValue V1 = SVOp->getOperand(0);
20442   SDValue V2 = SVOp->getOperand(1);
20443   EVT VT = SVOp->getValueType(0);
20444   unsigned NumElems = VT.getVectorNumElements();
20445
20446   if (V1.getOpcode() == ISD::CONCAT_VECTORS &&
20447       V2.getOpcode() == ISD::CONCAT_VECTORS) {
20448     //
20449     //                   0,0,0,...
20450     //                      |
20451     //    V      UNDEF    BUILD_VECTOR    UNDEF
20452     //     \      /           \           /
20453     //  CONCAT_VECTOR         CONCAT_VECTOR
20454     //         \                  /
20455     //          \                /
20456     //          RESULT: V + zero extended
20457     //
20458     if (V2.getOperand(0).getOpcode() != ISD::BUILD_VECTOR ||
20459         V2.getOperand(1).getOpcode() != ISD::UNDEF ||
20460         V1.getOperand(1).getOpcode() != ISD::UNDEF)
20461       return SDValue();
20462
20463     if (!ISD::isBuildVectorAllZeros(V2.getOperand(0).getNode()))
20464       return SDValue();
20465
20466     // To match the shuffle mask, the first half of the mask should
20467     // be exactly the first vector, and all the rest a splat with the
20468     // first element of the second one.
20469     for (unsigned i = 0; i != NumElems/2; ++i)
20470       if (!isUndefOrEqual(SVOp->getMaskElt(i), i) ||
20471           !isUndefOrEqual(SVOp->getMaskElt(i+NumElems/2), NumElems))
20472         return SDValue();
20473
20474     // If V1 is coming from a vector load then just fold to a VZEXT_LOAD.
20475     if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(V1.getOperand(0))) {
20476       if (Ld->hasNUsesOfValue(1, 0)) {
20477         SDVTList Tys = DAG.getVTList(MVT::v4i64, MVT::Other);
20478         SDValue Ops[] = { Ld->getChain(), Ld->getBasePtr() };
20479         SDValue ResNode =
20480           DAG.getMemIntrinsicNode(X86ISD::VZEXT_LOAD, dl, Tys, Ops,
20481                                   Ld->getMemoryVT(),
20482                                   Ld->getPointerInfo(),
20483                                   Ld->getAlignment(),
20484                                   false/*isVolatile*/, true/*ReadMem*/,
20485                                   false/*WriteMem*/);
20486
20487         // Make sure the newly-created LOAD is in the same position as Ld in
20488         // terms of dependency. We create a TokenFactor for Ld and ResNode,
20489         // and update uses of Ld's output chain to use the TokenFactor.
20490         if (Ld->hasAnyUseOfValue(1)) {
20491           SDValue NewChain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
20492                              SDValue(Ld, 1), SDValue(ResNode.getNode(), 1));
20493           DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), NewChain);
20494           DAG.UpdateNodeOperands(NewChain.getNode(), SDValue(Ld, 1),
20495                                  SDValue(ResNode.getNode(), 1));
20496         }
20497
20498         return DAG.getBitcast(VT, ResNode);
20499       }
20500     }
20501
20502     // Emit a zeroed vector and insert the desired subvector on its
20503     // first half.
20504     SDValue Zeros = getZeroVector(VT, Subtarget, DAG, dl);
20505     SDValue InsV = Insert128BitVector(Zeros, V1.getOperand(0), 0, DAG, dl);
20506     return DCI.CombineTo(N, InsV);
20507   }
20508
20509   //===--------------------------------------------------------------------===//
20510   // Combine some shuffles into subvector extracts and inserts:
20511   //
20512
20513   // vector_shuffle <4, 5, 6, 7, u, u, u, u> or <2, 3, u, u>
20514   if (isShuffleHigh128VectorInsertLow(SVOp)) {
20515     SDValue V = Extract128BitVector(V1, NumElems/2, DAG, dl);
20516     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, 0, DAG, dl);
20517     return DCI.CombineTo(N, InsV);
20518   }
20519
20520   // vector_shuffle <u, u, u, u, 0, 1, 2, 3> or <u, u, 0, 1>
20521   if (isShuffleLow128VectorInsertHigh(SVOp)) {
20522     SDValue V = Extract128BitVector(V1, 0, DAG, dl);
20523     SDValue InsV = Insert128BitVector(DAG.getUNDEF(VT), V, NumElems/2, DAG, dl);
20524     return DCI.CombineTo(N, InsV);
20525   }
20526
20527   return SDValue();
20528 }
20529
20530 /// \brief Combine an arbitrary chain of shuffles into a single instruction if
20531 /// possible.
20532 ///
20533 /// This is the leaf of the recursive combinine below. When we have found some
20534 /// chain of single-use x86 shuffle instructions and accumulated the combined
20535 /// shuffle mask represented by them, this will try to pattern match that mask
20536 /// into either a single instruction if there is a special purpose instruction
20537 /// for this operation, or into a PSHUFB instruction which is a fully general
20538 /// instruction but should only be used to replace chains over a certain depth.
20539 static bool combineX86ShuffleChain(SDValue Op, SDValue Root, ArrayRef<int> Mask,
20540                                    int Depth, bool HasPSHUFB, SelectionDAG &DAG,
20541                                    TargetLowering::DAGCombinerInfo &DCI,
20542                                    const X86Subtarget *Subtarget) {
20543   assert(!Mask.empty() && "Cannot combine an empty shuffle mask!");
20544
20545   // Find the operand that enters the chain. Note that multiple uses are OK
20546   // here, we're not going to remove the operand we find.
20547   SDValue Input = Op.getOperand(0);
20548   while (Input.getOpcode() == ISD::BITCAST)
20549     Input = Input.getOperand(0);
20550
20551   MVT VT = Input.getSimpleValueType();
20552   MVT RootVT = Root.getSimpleValueType();
20553   SDLoc DL(Root);
20554
20555   // Just remove no-op shuffle masks.
20556   if (Mask.size() == 1) {
20557     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Input),
20558                   /*AddTo*/ true);
20559     return true;
20560   }
20561
20562   // Use the float domain if the operand type is a floating point type.
20563   bool FloatDomain = VT.isFloatingPoint();
20564
20565   // For floating point shuffles, we don't have free copies in the shuffle
20566   // instructions or the ability to load as part of the instruction, so
20567   // canonicalize their shuffles to UNPCK or MOV variants.
20568   //
20569   // Note that even with AVX we prefer the PSHUFD form of shuffle for integer
20570   // vectors because it can have a load folded into it that UNPCK cannot. This
20571   // doesn't preclude something switching to the shorter encoding post-RA.
20572   //
20573   // FIXME: Should teach these routines about AVX vector widths.
20574   if (FloatDomain && VT.getSizeInBits() == 128) {
20575     if (Mask.equals({0, 0}) || Mask.equals({1, 1})) {
20576       bool Lo = Mask.equals({0, 0});
20577       unsigned Shuffle;
20578       MVT ShuffleVT;
20579       // Check if we have SSE3 which will let us use MOVDDUP. That instruction
20580       // is no slower than UNPCKLPD but has the option to fold the input operand
20581       // into even an unaligned memory load.
20582       if (Lo && Subtarget->hasSSE3()) {
20583         Shuffle = X86ISD::MOVDDUP;
20584         ShuffleVT = MVT::v2f64;
20585       } else {
20586         // We have MOVLHPS and MOVHLPS throughout SSE and they encode smaller
20587         // than the UNPCK variants.
20588         Shuffle = Lo ? X86ISD::MOVLHPS : X86ISD::MOVHLPS;
20589         ShuffleVT = MVT::v4f32;
20590       }
20591       if (Depth == 1 && Root->getOpcode() == Shuffle)
20592         return false; // Nothing to do!
20593       Op = DAG.getBitcast(ShuffleVT, Input);
20594       DCI.AddToWorklist(Op.getNode());
20595       if (Shuffle == X86ISD::MOVDDUP)
20596         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20597       else
20598         Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20599       DCI.AddToWorklist(Op.getNode());
20600       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20601                     /*AddTo*/ true);
20602       return true;
20603     }
20604     if (Subtarget->hasSSE3() &&
20605         (Mask.equals({0, 0, 2, 2}) || Mask.equals({1, 1, 3, 3}))) {
20606       bool Lo = Mask.equals({0, 0, 2, 2});
20607       unsigned Shuffle = Lo ? X86ISD::MOVSLDUP : X86ISD::MOVSHDUP;
20608       MVT ShuffleVT = MVT::v4f32;
20609       if (Depth == 1 && Root->getOpcode() == Shuffle)
20610         return false; // Nothing to do!
20611       Op = DAG.getBitcast(ShuffleVT, Input);
20612       DCI.AddToWorklist(Op.getNode());
20613       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op);
20614       DCI.AddToWorklist(Op.getNode());
20615       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20616                     /*AddTo*/ true);
20617       return true;
20618     }
20619     if (Mask.equals({0, 0, 1, 1}) || Mask.equals({2, 2, 3, 3})) {
20620       bool Lo = Mask.equals({0, 0, 1, 1});
20621       unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20622       MVT ShuffleVT = MVT::v4f32;
20623       if (Depth == 1 && Root->getOpcode() == Shuffle)
20624         return false; // Nothing to do!
20625       Op = DAG.getBitcast(ShuffleVT, Input);
20626       DCI.AddToWorklist(Op.getNode());
20627       Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20628       DCI.AddToWorklist(Op.getNode());
20629       DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20630                     /*AddTo*/ true);
20631       return true;
20632     }
20633   }
20634
20635   // We always canonicalize the 8 x i16 and 16 x i8 shuffles into their UNPCK
20636   // variants as none of these have single-instruction variants that are
20637   // superior to the UNPCK formulation.
20638   if (!FloatDomain && VT.getSizeInBits() == 128 &&
20639       (Mask.equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
20640        Mask.equals({4, 4, 5, 5, 6, 6, 7, 7}) ||
20641        Mask.equals({0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}) ||
20642        Mask.equals(
20643            {8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, 14, 14, 15, 15}))) {
20644     bool Lo = Mask[0] == 0;
20645     unsigned Shuffle = Lo ? X86ISD::UNPCKL : X86ISD::UNPCKH;
20646     if (Depth == 1 && Root->getOpcode() == Shuffle)
20647       return false; // Nothing to do!
20648     MVT ShuffleVT;
20649     switch (Mask.size()) {
20650     case 8:
20651       ShuffleVT = MVT::v8i16;
20652       break;
20653     case 16:
20654       ShuffleVT = MVT::v16i8;
20655       break;
20656     default:
20657       llvm_unreachable("Impossible mask size!");
20658     };
20659     Op = DAG.getBitcast(ShuffleVT, Input);
20660     DCI.AddToWorklist(Op.getNode());
20661     Op = DAG.getNode(Shuffle, DL, ShuffleVT, Op, Op);
20662     DCI.AddToWorklist(Op.getNode());
20663     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20664                   /*AddTo*/ true);
20665     return true;
20666   }
20667
20668   // Don't try to re-form single instruction chains under any circumstances now
20669   // that we've done encoding canonicalization for them.
20670   if (Depth < 2)
20671     return false;
20672
20673   // If we have 3 or more shuffle instructions or a chain involving PSHUFB, we
20674   // can replace them with a single PSHUFB instruction profitably. Intel's
20675   // manuals suggest only using PSHUFB if doing so replacing 5 instructions, but
20676   // in practice PSHUFB tends to be *very* fast so we're more aggressive.
20677   if ((Depth >= 3 || HasPSHUFB) && Subtarget->hasSSSE3()) {
20678     SmallVector<SDValue, 16> PSHUFBMask;
20679     int NumBytes = VT.getSizeInBits() / 8;
20680     int Ratio = NumBytes / Mask.size();
20681     for (int i = 0; i < NumBytes; ++i) {
20682       if (Mask[i / Ratio] == SM_SentinelUndef) {
20683         PSHUFBMask.push_back(DAG.getUNDEF(MVT::i8));
20684         continue;
20685       }
20686       int M = Mask[i / Ratio] != SM_SentinelZero
20687                   ? Ratio * Mask[i / Ratio] + i % Ratio
20688                   : 255;
20689       PSHUFBMask.push_back(DAG.getConstant(M, DL, MVT::i8));
20690     }
20691     MVT ByteVT = MVT::getVectorVT(MVT::i8, NumBytes);
20692     Op = DAG.getBitcast(ByteVT, Input);
20693     DCI.AddToWorklist(Op.getNode());
20694     SDValue PSHUFBMaskOp =
20695         DAG.getNode(ISD::BUILD_VECTOR, DL, ByteVT, PSHUFBMask);
20696     DCI.AddToWorklist(PSHUFBMaskOp.getNode());
20697     Op = DAG.getNode(X86ISD::PSHUFB, DL, ByteVT, Op, PSHUFBMaskOp);
20698     DCI.AddToWorklist(Op.getNode());
20699     DCI.CombineTo(Root.getNode(), DAG.getBitcast(RootVT, Op),
20700                   /*AddTo*/ true);
20701     return true;
20702   }
20703
20704   // Failed to find any combines.
20705   return false;
20706 }
20707
20708 /// \brief Fully generic combining of x86 shuffle instructions.
20709 ///
20710 /// This should be the last combine run over the x86 shuffle instructions. Once
20711 /// they have been fully optimized, this will recursively consider all chains
20712 /// of single-use shuffle instructions, build a generic model of the cumulative
20713 /// shuffle operation, and check for simpler instructions which implement this
20714 /// operation. We use this primarily for two purposes:
20715 ///
20716 /// 1) Collapse generic shuffles to specialized single instructions when
20717 ///    equivalent. In most cases, this is just an encoding size win, but
20718 ///    sometimes we will collapse multiple generic shuffles into a single
20719 ///    special-purpose shuffle.
20720 /// 2) Look for sequences of shuffle instructions with 3 or more total
20721 ///    instructions, and replace them with the slightly more expensive SSSE3
20722 ///    PSHUFB instruction if available. We do this as the last combining step
20723 ///    to ensure we avoid using PSHUFB if we can implement the shuffle with
20724 ///    a suitable short sequence of other instructions. The PHUFB will either
20725 ///    use a register or have to read from memory and so is slightly (but only
20726 ///    slightly) more expensive than the other shuffle instructions.
20727 ///
20728 /// Because this is inherently a quadratic operation (for each shuffle in
20729 /// a chain, we recurse up the chain), the depth is limited to 8 instructions.
20730 /// This should never be an issue in practice as the shuffle lowering doesn't
20731 /// produce sequences of more than 8 instructions.
20732 ///
20733 /// FIXME: We will currently miss some cases where the redundant shuffling
20734 /// would simplify under the threshold for PSHUFB formation because of
20735 /// combine-ordering. To fix this, we should do the redundant instruction
20736 /// combining in this recursive walk.
20737 static bool combineX86ShufflesRecursively(SDValue Op, SDValue Root,
20738                                           ArrayRef<int> RootMask,
20739                                           int Depth, bool HasPSHUFB,
20740                                           SelectionDAG &DAG,
20741                                           TargetLowering::DAGCombinerInfo &DCI,
20742                                           const X86Subtarget *Subtarget) {
20743   // Bound the depth of our recursive combine because this is ultimately
20744   // quadratic in nature.
20745   if (Depth > 8)
20746     return false;
20747
20748   // Directly rip through bitcasts to find the underlying operand.
20749   while (Op.getOpcode() == ISD::BITCAST && Op.getOperand(0).hasOneUse())
20750     Op = Op.getOperand(0);
20751
20752   MVT VT = Op.getSimpleValueType();
20753   if (!VT.isVector())
20754     return false; // Bail if we hit a non-vector.
20755
20756   assert(Root.getSimpleValueType().isVector() &&
20757          "Shuffles operate on vector types!");
20758   assert(VT.getSizeInBits() == Root.getSimpleValueType().getSizeInBits() &&
20759          "Can only combine shuffles of the same vector register size.");
20760
20761   if (!isTargetShuffle(Op.getOpcode()))
20762     return false;
20763   SmallVector<int, 16> OpMask;
20764   bool IsUnary;
20765   bool HaveMask = getTargetShuffleMask(Op.getNode(), VT, OpMask, IsUnary);
20766   // We only can combine unary shuffles which we can decode the mask for.
20767   if (!HaveMask || !IsUnary)
20768     return false;
20769
20770   assert(VT.getVectorNumElements() == OpMask.size() &&
20771          "Different mask size from vector size!");
20772   assert(((RootMask.size() > OpMask.size() &&
20773            RootMask.size() % OpMask.size() == 0) ||
20774           (OpMask.size() > RootMask.size() &&
20775            OpMask.size() % RootMask.size() == 0) ||
20776           OpMask.size() == RootMask.size()) &&
20777          "The smaller number of elements must divide the larger.");
20778   int RootRatio = std::max<int>(1, OpMask.size() / RootMask.size());
20779   int OpRatio = std::max<int>(1, RootMask.size() / OpMask.size());
20780   assert(((RootRatio == 1 && OpRatio == 1) ||
20781           (RootRatio == 1) != (OpRatio == 1)) &&
20782          "Must not have a ratio for both incoming and op masks!");
20783
20784   SmallVector<int, 16> Mask;
20785   Mask.reserve(std::max(OpMask.size(), RootMask.size()));
20786
20787   // Merge this shuffle operation's mask into our accumulated mask. Note that
20788   // this shuffle's mask will be the first applied to the input, followed by the
20789   // root mask to get us all the way to the root value arrangement. The reason
20790   // for this order is that we are recursing up the operation chain.
20791   for (int i = 0, e = std::max(OpMask.size(), RootMask.size()); i < e; ++i) {
20792     int RootIdx = i / RootRatio;
20793     if (RootMask[RootIdx] < 0) {
20794       // This is a zero or undef lane, we're done.
20795       Mask.push_back(RootMask[RootIdx]);
20796       continue;
20797     }
20798
20799     int RootMaskedIdx = RootMask[RootIdx] * RootRatio + i % RootRatio;
20800     int OpIdx = RootMaskedIdx / OpRatio;
20801     if (OpMask[OpIdx] < 0) {
20802       // The incoming lanes are zero or undef, it doesn't matter which ones we
20803       // are using.
20804       Mask.push_back(OpMask[OpIdx]);
20805       continue;
20806     }
20807
20808     // Ok, we have non-zero lanes, map them through.
20809     Mask.push_back(OpMask[OpIdx] * OpRatio +
20810                    RootMaskedIdx % OpRatio);
20811   }
20812
20813   // See if we can recurse into the operand to combine more things.
20814   switch (Op.getOpcode()) {
20815     case X86ISD::PSHUFB:
20816       HasPSHUFB = true;
20817     case X86ISD::PSHUFD:
20818     case X86ISD::PSHUFHW:
20819     case X86ISD::PSHUFLW:
20820       if (Op.getOperand(0).hasOneUse() &&
20821           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20822                                         HasPSHUFB, DAG, DCI, Subtarget))
20823         return true;
20824       break;
20825
20826     case X86ISD::UNPCKL:
20827     case X86ISD::UNPCKH:
20828       assert(Op.getOperand(0) == Op.getOperand(1) && "We only combine unary shuffles!");
20829       // We can't check for single use, we have to check that this shuffle is the only user.
20830       if (Op->isOnlyUserOf(Op.getOperand(0).getNode()) &&
20831           combineX86ShufflesRecursively(Op.getOperand(0), Root, Mask, Depth + 1,
20832                                         HasPSHUFB, DAG, DCI, Subtarget))
20833           return true;
20834       break;
20835   }
20836
20837   // Minor canonicalization of the accumulated shuffle mask to make it easier
20838   // to match below. All this does is detect masks with squential pairs of
20839   // elements, and shrink them to the half-width mask. It does this in a loop
20840   // so it will reduce the size of the mask to the minimal width mask which
20841   // performs an equivalent shuffle.
20842   SmallVector<int, 16> WidenedMask;
20843   while (Mask.size() > 1 && canWidenShuffleElements(Mask, WidenedMask)) {
20844     Mask = std::move(WidenedMask);
20845     WidenedMask.clear();
20846   }
20847
20848   return combineX86ShuffleChain(Op, Root, Mask, Depth, HasPSHUFB, DAG, DCI,
20849                                 Subtarget);
20850 }
20851
20852 /// \brief Get the PSHUF-style mask from PSHUF node.
20853 ///
20854 /// This is a very minor wrapper around getTargetShuffleMask to easy forming v4
20855 /// PSHUF-style masks that can be reused with such instructions.
20856 static SmallVector<int, 4> getPSHUFShuffleMask(SDValue N) {
20857   MVT VT = N.getSimpleValueType();
20858   SmallVector<int, 4> Mask;
20859   bool IsUnary;
20860   bool HaveMask = getTargetShuffleMask(N.getNode(), VT, Mask, IsUnary);
20861   (void)HaveMask;
20862   assert(HaveMask);
20863
20864   // If we have more than 128-bits, only the low 128-bits of shuffle mask
20865   // matter. Check that the upper masks are repeats and remove them.
20866   if (VT.getSizeInBits() > 128) {
20867     int LaneElts = 128 / VT.getScalarSizeInBits();
20868 #ifndef NDEBUG
20869     for (int i = 1, NumLanes = VT.getSizeInBits() / 128; i < NumLanes; ++i)
20870       for (int j = 0; j < LaneElts; ++j)
20871         assert(Mask[j] == Mask[i * LaneElts + j] - (LaneElts * i) &&
20872                "Mask doesn't repeat in high 128-bit lanes!");
20873 #endif
20874     Mask.resize(LaneElts);
20875   }
20876
20877   switch (N.getOpcode()) {
20878   case X86ISD::PSHUFD:
20879     return Mask;
20880   case X86ISD::PSHUFLW:
20881     Mask.resize(4);
20882     return Mask;
20883   case X86ISD::PSHUFHW:
20884     Mask.erase(Mask.begin(), Mask.begin() + 4);
20885     for (int &M : Mask)
20886       M -= 4;
20887     return Mask;
20888   default:
20889     llvm_unreachable("No valid shuffle instruction found!");
20890   }
20891 }
20892
20893 /// \brief Search for a combinable shuffle across a chain ending in pshufd.
20894 ///
20895 /// We walk up the chain and look for a combinable shuffle, skipping over
20896 /// shuffles that we could hoist this shuffle's transformation past without
20897 /// altering anything.
20898 static SDValue
20899 combineRedundantDWordShuffle(SDValue N, MutableArrayRef<int> Mask,
20900                              SelectionDAG &DAG,
20901                              TargetLowering::DAGCombinerInfo &DCI) {
20902   assert(N.getOpcode() == X86ISD::PSHUFD &&
20903          "Called with something other than an x86 128-bit half shuffle!");
20904   SDLoc DL(N);
20905
20906   // Walk up a single-use chain looking for a combinable shuffle. Keep a stack
20907   // of the shuffles in the chain so that we can form a fresh chain to replace
20908   // this one.
20909   SmallVector<SDValue, 8> Chain;
20910   SDValue V = N.getOperand(0);
20911   for (; V.hasOneUse(); V = V.getOperand(0)) {
20912     switch (V.getOpcode()) {
20913     default:
20914       return SDValue(); // Nothing combined!
20915
20916     case ISD::BITCAST:
20917       // Skip bitcasts as we always know the type for the target specific
20918       // instructions.
20919       continue;
20920
20921     case X86ISD::PSHUFD:
20922       // Found another dword shuffle.
20923       break;
20924
20925     case X86ISD::PSHUFLW:
20926       // Check that the low words (being shuffled) are the identity in the
20927       // dword shuffle, and the high words are self-contained.
20928       if (Mask[0] != 0 || Mask[1] != 1 ||
20929           !(Mask[2] >= 2 && Mask[2] < 4 && Mask[3] >= 2 && Mask[3] < 4))
20930         return SDValue();
20931
20932       Chain.push_back(V);
20933       continue;
20934
20935     case X86ISD::PSHUFHW:
20936       // Check that the high words (being shuffled) are the identity in the
20937       // dword shuffle, and the low words are self-contained.
20938       if (Mask[2] != 2 || Mask[3] != 3 ||
20939           !(Mask[0] >= 0 && Mask[0] < 2 && Mask[1] >= 0 && Mask[1] < 2))
20940         return SDValue();
20941
20942       Chain.push_back(V);
20943       continue;
20944
20945     case X86ISD::UNPCKL:
20946     case X86ISD::UNPCKH:
20947       // For either i8 -> i16 or i16 -> i32 unpacks, we can combine a dword
20948       // shuffle into a preceding word shuffle.
20949       if (V.getSimpleValueType().getScalarType() != MVT::i8 &&
20950           V.getSimpleValueType().getScalarType() != MVT::i16)
20951         return SDValue();
20952
20953       // Search for a half-shuffle which we can combine with.
20954       unsigned CombineOp =
20955           V.getOpcode() == X86ISD::UNPCKL ? X86ISD::PSHUFLW : X86ISD::PSHUFHW;
20956       if (V.getOperand(0) != V.getOperand(1) ||
20957           !V->isOnlyUserOf(V.getOperand(0).getNode()))
20958         return SDValue();
20959       Chain.push_back(V);
20960       V = V.getOperand(0);
20961       do {
20962         switch (V.getOpcode()) {
20963         default:
20964           return SDValue(); // Nothing to combine.
20965
20966         case X86ISD::PSHUFLW:
20967         case X86ISD::PSHUFHW:
20968           if (V.getOpcode() == CombineOp)
20969             break;
20970
20971           Chain.push_back(V);
20972
20973           // Fallthrough!
20974         case ISD::BITCAST:
20975           V = V.getOperand(0);
20976           continue;
20977         }
20978         break;
20979       } while (V.hasOneUse());
20980       break;
20981     }
20982     // Break out of the loop if we break out of the switch.
20983     break;
20984   }
20985
20986   if (!V.hasOneUse())
20987     // We fell out of the loop without finding a viable combining instruction.
20988     return SDValue();
20989
20990   // Merge this node's mask and our incoming mask.
20991   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
20992   for (int &M : Mask)
20993     M = VMask[M];
20994   V = DAG.getNode(V.getOpcode(), DL, V.getValueType(), V.getOperand(0),
20995                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
20996
20997   // Rebuild the chain around this new shuffle.
20998   while (!Chain.empty()) {
20999     SDValue W = Chain.pop_back_val();
21000
21001     if (V.getValueType() != W.getOperand(0).getValueType())
21002       V = DAG.getBitcast(W.getOperand(0).getValueType(), V);
21003
21004     switch (W.getOpcode()) {
21005     default:
21006       llvm_unreachable("Only PSHUF and UNPCK instructions get here!");
21007
21008     case X86ISD::UNPCKL:
21009     case X86ISD::UNPCKH:
21010       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, V);
21011       break;
21012
21013     case X86ISD::PSHUFD:
21014     case X86ISD::PSHUFLW:
21015     case X86ISD::PSHUFHW:
21016       V = DAG.getNode(W.getOpcode(), DL, W.getValueType(), V, W.getOperand(1));
21017       break;
21018     }
21019   }
21020   if (V.getValueType() != N.getValueType())
21021     V = DAG.getBitcast(N.getValueType(), V);
21022
21023   // Return the new chain to replace N.
21024   return V;
21025 }
21026
21027 /// \brief Search for a combinable shuffle across a chain ending in pshuflw or pshufhw.
21028 ///
21029 /// We walk up the chain, skipping shuffles of the other half and looking
21030 /// through shuffles which switch halves trying to find a shuffle of the same
21031 /// pair of dwords.
21032 static bool combineRedundantHalfShuffle(SDValue N, MutableArrayRef<int> Mask,
21033                                         SelectionDAG &DAG,
21034                                         TargetLowering::DAGCombinerInfo &DCI) {
21035   assert(
21036       (N.getOpcode() == X86ISD::PSHUFLW || N.getOpcode() == X86ISD::PSHUFHW) &&
21037       "Called with something other than an x86 128-bit half shuffle!");
21038   SDLoc DL(N);
21039   unsigned CombineOpcode = N.getOpcode();
21040
21041   // Walk up a single-use chain looking for a combinable shuffle.
21042   SDValue V = N.getOperand(0);
21043   for (; V.hasOneUse(); V = V.getOperand(0)) {
21044     switch (V.getOpcode()) {
21045     default:
21046       return false; // Nothing combined!
21047
21048     case ISD::BITCAST:
21049       // Skip bitcasts as we always know the type for the target specific
21050       // instructions.
21051       continue;
21052
21053     case X86ISD::PSHUFLW:
21054     case X86ISD::PSHUFHW:
21055       if (V.getOpcode() == CombineOpcode)
21056         break;
21057
21058       // Other-half shuffles are no-ops.
21059       continue;
21060     }
21061     // Break out of the loop if we break out of the switch.
21062     break;
21063   }
21064
21065   if (!V.hasOneUse())
21066     // We fell out of the loop without finding a viable combining instruction.
21067     return false;
21068
21069   // Combine away the bottom node as its shuffle will be accumulated into
21070   // a preceding shuffle.
21071   DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21072
21073   // Record the old value.
21074   SDValue Old = V;
21075
21076   // Merge this node's mask and our incoming mask (adjusted to account for all
21077   // the pshufd instructions encountered).
21078   SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21079   for (int &M : Mask)
21080     M = VMask[M];
21081   V = DAG.getNode(V.getOpcode(), DL, MVT::v8i16, V.getOperand(0),
21082                   getV4X86ShuffleImm8ForMask(Mask, DL, DAG));
21083
21084   // Check that the shuffles didn't cancel each other out. If not, we need to
21085   // combine to the new one.
21086   if (Old != V)
21087     // Replace the combinable shuffle with the combined one, updating all users
21088     // so that we re-evaluate the chain here.
21089     DCI.CombineTo(Old.getNode(), V, /*AddTo*/ true);
21090
21091   return true;
21092 }
21093
21094 /// \brief Try to combine x86 target specific shuffles.
21095 static SDValue PerformTargetShuffleCombine(SDValue N, SelectionDAG &DAG,
21096                                            TargetLowering::DAGCombinerInfo &DCI,
21097                                            const X86Subtarget *Subtarget) {
21098   SDLoc DL(N);
21099   MVT VT = N.getSimpleValueType();
21100   SmallVector<int, 4> Mask;
21101
21102   switch (N.getOpcode()) {
21103   case X86ISD::PSHUFD:
21104   case X86ISD::PSHUFLW:
21105   case X86ISD::PSHUFHW:
21106     Mask = getPSHUFShuffleMask(N);
21107     assert(Mask.size() == 4);
21108     break;
21109   default:
21110     return SDValue();
21111   }
21112
21113   // Nuke no-op shuffles that show up after combining.
21114   if (isNoopShuffleMask(Mask))
21115     return DCI.CombineTo(N.getNode(), N.getOperand(0), /*AddTo*/ true);
21116
21117   // Look for simplifications involving one or two shuffle instructions.
21118   SDValue V = N.getOperand(0);
21119   switch (N.getOpcode()) {
21120   default:
21121     break;
21122   case X86ISD::PSHUFLW:
21123   case X86ISD::PSHUFHW:
21124     assert(VT.getScalarType() == MVT::i16 && "Bad word shuffle type!");
21125
21126     if (combineRedundantHalfShuffle(N, Mask, DAG, DCI))
21127       return SDValue(); // We combined away this shuffle, so we're done.
21128
21129     // See if this reduces to a PSHUFD which is no more expensive and can
21130     // combine with more operations. Note that it has to at least flip the
21131     // dwords as otherwise it would have been removed as a no-op.
21132     if (makeArrayRef(Mask).equals({2, 3, 0, 1})) {
21133       int DMask[] = {0, 1, 2, 3};
21134       int DOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 2;
21135       DMask[DOffset + 0] = DOffset + 1;
21136       DMask[DOffset + 1] = DOffset + 0;
21137       MVT DVT = MVT::getVectorVT(MVT::i32, VT.getVectorNumElements() / 2);
21138       V = DAG.getBitcast(DVT, V);
21139       DCI.AddToWorklist(V.getNode());
21140       V = DAG.getNode(X86ISD::PSHUFD, DL, DVT, V,
21141                       getV4X86ShuffleImm8ForMask(DMask, DL, DAG));
21142       DCI.AddToWorklist(V.getNode());
21143       return DAG.getBitcast(VT, V);
21144     }
21145
21146     // Look for shuffle patterns which can be implemented as a single unpack.
21147     // FIXME: This doesn't handle the location of the PSHUFD generically, and
21148     // only works when we have a PSHUFD followed by two half-shuffles.
21149     if (Mask[0] == Mask[1] && Mask[2] == Mask[3] &&
21150         (V.getOpcode() == X86ISD::PSHUFLW ||
21151          V.getOpcode() == X86ISD::PSHUFHW) &&
21152         V.getOpcode() != N.getOpcode() &&
21153         V.hasOneUse()) {
21154       SDValue D = V.getOperand(0);
21155       while (D.getOpcode() == ISD::BITCAST && D.hasOneUse())
21156         D = D.getOperand(0);
21157       if (D.getOpcode() == X86ISD::PSHUFD && D.hasOneUse()) {
21158         SmallVector<int, 4> VMask = getPSHUFShuffleMask(V);
21159         SmallVector<int, 4> DMask = getPSHUFShuffleMask(D);
21160         int NOffset = N.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21161         int VOffset = V.getOpcode() == X86ISD::PSHUFLW ? 0 : 4;
21162         int WordMask[8];
21163         for (int i = 0; i < 4; ++i) {
21164           WordMask[i + NOffset] = Mask[i] + NOffset;
21165           WordMask[i + VOffset] = VMask[i] + VOffset;
21166         }
21167         // Map the word mask through the DWord mask.
21168         int MappedMask[8];
21169         for (int i = 0; i < 8; ++i)
21170           MappedMask[i] = 2 * DMask[WordMask[i] / 2] + WordMask[i] % 2;
21171         if (makeArrayRef(MappedMask).equals({0, 0, 1, 1, 2, 2, 3, 3}) ||
21172             makeArrayRef(MappedMask).equals({4, 4, 5, 5, 6, 6, 7, 7})) {
21173           // We can replace all three shuffles with an unpack.
21174           V = DAG.getBitcast(VT, D.getOperand(0));
21175           DCI.AddToWorklist(V.getNode());
21176           return DAG.getNode(MappedMask[0] == 0 ? X86ISD::UNPCKL
21177                                                 : X86ISD::UNPCKH,
21178                              DL, VT, V, V);
21179         }
21180       }
21181     }
21182
21183     break;
21184
21185   case X86ISD::PSHUFD:
21186     if (SDValue NewN = combineRedundantDWordShuffle(N, Mask, DAG, DCI))
21187       return NewN;
21188
21189     break;
21190   }
21191
21192   return SDValue();
21193 }
21194
21195 /// \brief Try to combine a shuffle into a target-specific add-sub node.
21196 ///
21197 /// We combine this directly on the abstract vector shuffle nodes so it is
21198 /// easier to generically match. We also insert dummy vector shuffle nodes for
21199 /// the operands which explicitly discard the lanes which are unused by this
21200 /// operation to try to flow through the rest of the combiner the fact that
21201 /// they're unused.
21202 static SDValue combineShuffleToAddSub(SDNode *N, SelectionDAG &DAG) {
21203   SDLoc DL(N);
21204   EVT VT = N->getValueType(0);
21205
21206   // We only handle target-independent shuffles.
21207   // FIXME: It would be easy and harmless to use the target shuffle mask
21208   // extraction tool to support more.
21209   if (N->getOpcode() != ISD::VECTOR_SHUFFLE)
21210     return SDValue();
21211
21212   auto *SVN = cast<ShuffleVectorSDNode>(N);
21213   ArrayRef<int> Mask = SVN->getMask();
21214   SDValue V1 = N->getOperand(0);
21215   SDValue V2 = N->getOperand(1);
21216
21217   // We require the first shuffle operand to be the SUB node, and the second to
21218   // be the ADD node.
21219   // FIXME: We should support the commuted patterns.
21220   if (V1->getOpcode() != ISD::FSUB || V2->getOpcode() != ISD::FADD)
21221     return SDValue();
21222
21223   // If there are other uses of these operations we can't fold them.
21224   if (!V1->hasOneUse() || !V2->hasOneUse())
21225     return SDValue();
21226
21227   // Ensure that both operations have the same operands. Note that we can
21228   // commute the FADD operands.
21229   SDValue LHS = V1->getOperand(0), RHS = V1->getOperand(1);
21230   if ((V2->getOperand(0) != LHS || V2->getOperand(1) != RHS) &&
21231       (V2->getOperand(0) != RHS || V2->getOperand(1) != LHS))
21232     return SDValue();
21233
21234   // We're looking for blends between FADD and FSUB nodes. We insist on these
21235   // nodes being lined up in a specific expected pattern.
21236   if (!(isShuffleEquivalent(V1, V2, Mask, {0, 3}) ||
21237         isShuffleEquivalent(V1, V2, Mask, {0, 5, 2, 7}) ||
21238         isShuffleEquivalent(V1, V2, Mask, {0, 9, 2, 11, 4, 13, 6, 15})))
21239     return SDValue();
21240
21241   // Only specific types are legal at this point, assert so we notice if and
21242   // when these change.
21243   assert((VT == MVT::v4f32 || VT == MVT::v2f64 || VT == MVT::v8f32 ||
21244           VT == MVT::v4f64) &&
21245          "Unknown vector type encountered!");
21246
21247   return DAG.getNode(X86ISD::ADDSUB, DL, VT, LHS, RHS);
21248 }
21249
21250 /// PerformShuffleCombine - Performs several different shuffle combines.
21251 static SDValue PerformShuffleCombine(SDNode *N, SelectionDAG &DAG,
21252                                      TargetLowering::DAGCombinerInfo &DCI,
21253                                      const X86Subtarget *Subtarget) {
21254   SDLoc dl(N);
21255   SDValue N0 = N->getOperand(0);
21256   SDValue N1 = N->getOperand(1);
21257   EVT VT = N->getValueType(0);
21258
21259   // Don't create instructions with illegal types after legalize types has run.
21260   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21261   if (!DCI.isBeforeLegalize() && !TLI.isTypeLegal(VT.getVectorElementType()))
21262     return SDValue();
21263
21264   // If we have legalized the vector types, look for blends of FADD and FSUB
21265   // nodes that we can fuse into an ADDSUB node.
21266   if (TLI.isTypeLegal(VT) && Subtarget->hasSSE3())
21267     if (SDValue AddSub = combineShuffleToAddSub(N, DAG))
21268       return AddSub;
21269
21270   // Combine 256-bit vector shuffles. This is only profitable when in AVX mode
21271   if (Subtarget->hasFp256() && VT.is256BitVector() &&
21272       N->getOpcode() == ISD::VECTOR_SHUFFLE)
21273     return PerformShuffleCombine256(N, DAG, DCI, Subtarget);
21274
21275   // During Type Legalization, when promoting illegal vector types,
21276   // the backend might introduce new shuffle dag nodes and bitcasts.
21277   //
21278   // This code performs the following transformation:
21279   // fold: (shuffle (bitcast (BINOP A, B)), Undef, <Mask>) ->
21280   //       (shuffle (BINOP (bitcast A), (bitcast B)), Undef, <Mask>)
21281   //
21282   // We do this only if both the bitcast and the BINOP dag nodes have
21283   // one use. Also, perform this transformation only if the new binary
21284   // operation is legal. This is to avoid introducing dag nodes that
21285   // potentially need to be further expanded (or custom lowered) into a
21286   // less optimal sequence of dag nodes.
21287   if (!DCI.isBeforeLegalize() && DCI.isBeforeLegalizeOps() &&
21288       N1.getOpcode() == ISD::UNDEF && N0.hasOneUse() &&
21289       N0.getOpcode() == ISD::BITCAST) {
21290     SDValue BC0 = N0.getOperand(0);
21291     EVT SVT = BC0.getValueType();
21292     unsigned Opcode = BC0.getOpcode();
21293     unsigned NumElts = VT.getVectorNumElements();
21294
21295     if (BC0.hasOneUse() && SVT.isVector() &&
21296         SVT.getVectorNumElements() * 2 == NumElts &&
21297         TLI.isOperationLegal(Opcode, VT)) {
21298       bool CanFold = false;
21299       switch (Opcode) {
21300       default : break;
21301       case ISD::ADD :
21302       case ISD::FADD :
21303       case ISD::SUB :
21304       case ISD::FSUB :
21305       case ISD::MUL :
21306       case ISD::FMUL :
21307         CanFold = true;
21308       }
21309
21310       unsigned SVTNumElts = SVT.getVectorNumElements();
21311       ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(N);
21312       for (unsigned i = 0, e = SVTNumElts; i != e && CanFold; ++i)
21313         CanFold = SVOp->getMaskElt(i) == (int)(i * 2);
21314       for (unsigned i = SVTNumElts, e = NumElts; i != e && CanFold; ++i)
21315         CanFold = SVOp->getMaskElt(i) < 0;
21316
21317       if (CanFold) {
21318         SDValue BC00 = DAG.getBitcast(VT, BC0.getOperand(0));
21319         SDValue BC01 = DAG.getBitcast(VT, BC0.getOperand(1));
21320         SDValue NewBinOp = DAG.getNode(BC0.getOpcode(), dl, VT, BC00, BC01);
21321         return DAG.getVectorShuffle(VT, dl, NewBinOp, N1, &SVOp->getMask()[0]);
21322       }
21323     }
21324   }
21325
21326   // Combine a vector_shuffle that is equal to build_vector load1, load2, load3,
21327   // load4, <0, 1, 2, 3> into a 128-bit load if the load addresses are
21328   // consecutive, non-overlapping, and in the right order.
21329   SmallVector<SDValue, 16> Elts;
21330   for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
21331     Elts.push_back(getShuffleScalarElt(N, i, DAG, 0));
21332
21333   if (SDValue LD = EltsFromConsecutiveLoads(VT, Elts, dl, DAG, true))
21334     return LD;
21335
21336   if (isTargetShuffle(N->getOpcode())) {
21337     SDValue Shuffle =
21338         PerformTargetShuffleCombine(SDValue(N, 0), DAG, DCI, Subtarget);
21339     if (Shuffle.getNode())
21340       return Shuffle;
21341
21342     // Try recursively combining arbitrary sequences of x86 shuffle
21343     // instructions into higher-order shuffles. We do this after combining
21344     // specific PSHUF instruction sequences into their minimal form so that we
21345     // can evaluate how many specialized shuffle instructions are involved in
21346     // a particular chain.
21347     SmallVector<int, 1> NonceMask; // Just a placeholder.
21348     NonceMask.push_back(0);
21349     if (combineX86ShufflesRecursively(SDValue(N, 0), SDValue(N, 0), NonceMask,
21350                                       /*Depth*/ 1, /*HasPSHUFB*/ false, DAG,
21351                                       DCI, Subtarget))
21352       return SDValue(); // This routine will use CombineTo to replace N.
21353   }
21354
21355   return SDValue();
21356 }
21357
21358 /// XFormVExtractWithShuffleIntoLoad - Check if a vector extract from a target
21359 /// specific shuffle of a load can be folded into a single element load.
21360 /// Similar handling for VECTOR_SHUFFLE is performed by DAGCombiner, but
21361 /// shuffles have been custom lowered so we need to handle those here.
21362 static SDValue XFormVExtractWithShuffleIntoLoad(SDNode *N, SelectionDAG &DAG,
21363                                          TargetLowering::DAGCombinerInfo &DCI) {
21364   if (DCI.isBeforeLegalizeOps())
21365     return SDValue();
21366
21367   SDValue InVec = N->getOperand(0);
21368   SDValue EltNo = N->getOperand(1);
21369
21370   if (!isa<ConstantSDNode>(EltNo))
21371     return SDValue();
21372
21373   EVT OriginalVT = InVec.getValueType();
21374
21375   if (InVec.getOpcode() == ISD::BITCAST) {
21376     // Don't duplicate a load with other uses.
21377     if (!InVec.hasOneUse())
21378       return SDValue();
21379     EVT BCVT = InVec.getOperand(0).getValueType();
21380     if (!BCVT.isVector() ||
21381         BCVT.getVectorNumElements() != OriginalVT.getVectorNumElements())
21382       return SDValue();
21383     InVec = InVec.getOperand(0);
21384   }
21385
21386   EVT CurrentVT = InVec.getValueType();
21387
21388   if (!isTargetShuffle(InVec.getOpcode()))
21389     return SDValue();
21390
21391   // Don't duplicate a load with other uses.
21392   if (!InVec.hasOneUse())
21393     return SDValue();
21394
21395   SmallVector<int, 16> ShuffleMask;
21396   bool UnaryShuffle;
21397   if (!getTargetShuffleMask(InVec.getNode(), CurrentVT.getSimpleVT(),
21398                             ShuffleMask, UnaryShuffle))
21399     return SDValue();
21400
21401   // Select the input vector, guarding against out of range extract vector.
21402   unsigned NumElems = CurrentVT.getVectorNumElements();
21403   int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
21404   int Idx = (Elt > (int)NumElems) ? -1 : ShuffleMask[Elt];
21405   SDValue LdNode = (Idx < (int)NumElems) ? InVec.getOperand(0)
21406                                          : InVec.getOperand(1);
21407
21408   // If inputs to shuffle are the same for both ops, then allow 2 uses
21409   unsigned AllowedUses = InVec.getNumOperands() > 1 &&
21410                          InVec.getOperand(0) == InVec.getOperand(1) ? 2 : 1;
21411
21412   if (LdNode.getOpcode() == ISD::BITCAST) {
21413     // Don't duplicate a load with other uses.
21414     if (!LdNode.getNode()->hasNUsesOfValue(AllowedUses, 0))
21415       return SDValue();
21416
21417     AllowedUses = 1; // only allow 1 load use if we have a bitcast
21418     LdNode = LdNode.getOperand(0);
21419   }
21420
21421   if (!ISD::isNormalLoad(LdNode.getNode()))
21422     return SDValue();
21423
21424   LoadSDNode *LN0 = cast<LoadSDNode>(LdNode);
21425
21426   if (!LN0 ||!LN0->hasNUsesOfValue(AllowedUses, 0) || LN0->isVolatile())
21427     return SDValue();
21428
21429   EVT EltVT = N->getValueType(0);
21430   // If there's a bitcast before the shuffle, check if the load type and
21431   // alignment is valid.
21432   unsigned Align = LN0->getAlignment();
21433   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21434   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
21435       EltVT.getTypeForEVT(*DAG.getContext()));
21436
21437   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, EltVT))
21438     return SDValue();
21439
21440   // All checks match so transform back to vector_shuffle so that DAG combiner
21441   // can finish the job
21442   SDLoc dl(N);
21443
21444   // Create shuffle node taking into account the case that its a unary shuffle
21445   SDValue Shuffle = (UnaryShuffle) ? DAG.getUNDEF(CurrentVT)
21446                                    : InVec.getOperand(1);
21447   Shuffle = DAG.getVectorShuffle(CurrentVT, dl,
21448                                  InVec.getOperand(0), Shuffle,
21449                                  &ShuffleMask[0]);
21450   Shuffle = DAG.getBitcast(OriginalVT, Shuffle);
21451   return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0), Shuffle,
21452                      EltNo);
21453 }
21454
21455 /// \brief Detect bitcasts between i32 to x86mmx low word. Since MMX types are
21456 /// special and don't usually play with other vector types, it's better to
21457 /// handle them early to be sure we emit efficient code by avoiding
21458 /// store-load conversions.
21459 static SDValue PerformBITCASTCombine(SDNode *N, SelectionDAG &DAG) {
21460   if (N->getValueType(0) != MVT::x86mmx ||
21461       N->getOperand(0)->getOpcode() != ISD::BUILD_VECTOR ||
21462       N->getOperand(0)->getValueType(0) != MVT::v2i32)
21463     return SDValue();
21464
21465   SDValue V = N->getOperand(0);
21466   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V.getOperand(1));
21467   if (C && C->getZExtValue() == 0 && V.getOperand(0).getValueType() == MVT::i32)
21468     return DAG.getNode(X86ISD::MMX_MOVW2D, SDLoc(V.getOperand(0)),
21469                        N->getValueType(0), V.getOperand(0));
21470
21471   return SDValue();
21472 }
21473
21474 /// PerformEXTRACT_VECTOR_ELTCombine - Detect vector gather/scatter index
21475 /// generation and convert it from being a bunch of shuffles and extracts
21476 /// into a somewhat faster sequence. For i686, the best sequence is apparently
21477 /// storing the value and loading scalars back, while for x64 we should
21478 /// use 64-bit extracts and shifts.
21479 static SDValue PerformEXTRACT_VECTOR_ELTCombine(SDNode *N, SelectionDAG &DAG,
21480                                          TargetLowering::DAGCombinerInfo &DCI) {
21481   if (SDValue NewOp = XFormVExtractWithShuffleIntoLoad(N, DAG, DCI))
21482     return NewOp;
21483
21484   SDValue InputVector = N->getOperand(0);
21485   SDLoc dl(InputVector);
21486   // Detect mmx to i32 conversion through a v2i32 elt extract.
21487   if (InputVector.getOpcode() == ISD::BITCAST && InputVector.hasOneUse() &&
21488       N->getValueType(0) == MVT::i32 &&
21489       InputVector.getValueType() == MVT::v2i32) {
21490
21491     // The bitcast source is a direct mmx result.
21492     SDValue MMXSrc = InputVector.getNode()->getOperand(0);
21493     if (MMXSrc.getValueType() == MVT::x86mmx)
21494       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21495                          N->getValueType(0),
21496                          InputVector.getNode()->getOperand(0));
21497
21498     // The mmx is indirect: (i64 extract_elt (v1i64 bitcast (x86mmx ...))).
21499     SDValue MMXSrcOp = MMXSrc.getOperand(0);
21500     if (MMXSrc.getOpcode() == ISD::EXTRACT_VECTOR_ELT && MMXSrc.hasOneUse() &&
21501         MMXSrc.getValueType() == MVT::i64 && MMXSrcOp.hasOneUse() &&
21502         MMXSrcOp.getOpcode() == ISD::BITCAST &&
21503         MMXSrcOp.getValueType() == MVT::v1i64 &&
21504         MMXSrcOp.getOperand(0).getValueType() == MVT::x86mmx)
21505       return DAG.getNode(X86ISD::MMX_MOVD2W, SDLoc(InputVector),
21506                          N->getValueType(0),
21507                          MMXSrcOp.getOperand(0));
21508   }
21509
21510   EVT VT = N->getValueType(0);
21511
21512   if (VT == MVT::i1 && dyn_cast<ConstantSDNode>(N->getOperand(1)) &&
21513       InputVector.getOpcode() == ISD::BITCAST &&
21514       dyn_cast<ConstantSDNode>(InputVector.getOperand(0))) {
21515     uint64_t ExtractedElt =
21516           cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
21517     uint64_t InputValue =
21518           cast<ConstantSDNode>(InputVector.getOperand(0))->getZExtValue();
21519     uint64_t Res = (InputValue >> ExtractedElt) & 1;
21520     return DAG.getConstant(Res, dl, MVT::i1);
21521   }
21522   // Only operate on vectors of 4 elements, where the alternative shuffling
21523   // gets to be more expensive.
21524   if (InputVector.getValueType() != MVT::v4i32)
21525     return SDValue();
21526
21527   // Check whether every use of InputVector is an EXTRACT_VECTOR_ELT with a
21528   // single use which is a sign-extend or zero-extend, and all elements are
21529   // used.
21530   SmallVector<SDNode *, 4> Uses;
21531   unsigned ExtractedElements = 0;
21532   for (SDNode::use_iterator UI = InputVector.getNode()->use_begin(),
21533        UE = InputVector.getNode()->use_end(); UI != UE; ++UI) {
21534     if (UI.getUse().getResNo() != InputVector.getResNo())
21535       return SDValue();
21536
21537     SDNode *Extract = *UI;
21538     if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT)
21539       return SDValue();
21540
21541     if (Extract->getValueType(0) != MVT::i32)
21542       return SDValue();
21543     if (!Extract->hasOneUse())
21544       return SDValue();
21545     if (Extract->use_begin()->getOpcode() != ISD::SIGN_EXTEND &&
21546         Extract->use_begin()->getOpcode() != ISD::ZERO_EXTEND)
21547       return SDValue();
21548     if (!isa<ConstantSDNode>(Extract->getOperand(1)))
21549       return SDValue();
21550
21551     // Record which element was extracted.
21552     ExtractedElements |=
21553       1 << cast<ConstantSDNode>(Extract->getOperand(1))->getZExtValue();
21554
21555     Uses.push_back(Extract);
21556   }
21557
21558   // If not all the elements were used, this may not be worthwhile.
21559   if (ExtractedElements != 15)
21560     return SDValue();
21561
21562   // Ok, we've now decided to do the transformation.
21563   // If 64-bit shifts are legal, use the extract-shift sequence,
21564   // otherwise bounce the vector off the cache.
21565   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21566   SDValue Vals[4];
21567
21568   if (TLI.isOperationLegal(ISD::SRA, MVT::i64)) {
21569     SDValue Cst = DAG.getBitcast(MVT::v2i64, InputVector);
21570     EVT VecIdxTy = DAG.getTargetLoweringInfo().getVectorIdxTy();
21571     SDValue BottomHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21572       DAG.getConstant(0, dl, VecIdxTy));
21573     SDValue TopHalf = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::i64, Cst,
21574       DAG.getConstant(1, dl, VecIdxTy));
21575
21576     SDValue ShAmt = DAG.getConstant(32, dl,
21577       DAG.getTargetLoweringInfo().getShiftAmountTy(MVT::i64));
21578     Vals[0] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, BottomHalf);
21579     Vals[1] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21580       DAG.getNode(ISD::SRA, dl, MVT::i64, BottomHalf, ShAmt));
21581     Vals[2] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, TopHalf);
21582     Vals[3] = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32,
21583       DAG.getNode(ISD::SRA, dl, MVT::i64, TopHalf, ShAmt));
21584   } else {
21585     // Store the value to a temporary stack slot.
21586     SDValue StackPtr = DAG.CreateStackTemporary(InputVector.getValueType());
21587     SDValue Ch = DAG.getStore(DAG.getEntryNode(), dl, InputVector, StackPtr,
21588       MachinePointerInfo(), false, false, 0);
21589
21590     EVT ElementType = InputVector.getValueType().getVectorElementType();
21591     unsigned EltSize = ElementType.getSizeInBits() / 8;
21592
21593     // Replace each use (extract) with a load of the appropriate element.
21594     for (unsigned i = 0; i < 4; ++i) {
21595       uint64_t Offset = EltSize * i;
21596       SDValue OffsetVal = DAG.getConstant(Offset, dl, TLI.getPointerTy());
21597
21598       SDValue ScalarAddr = DAG.getNode(ISD::ADD, dl, TLI.getPointerTy(),
21599                                        StackPtr, OffsetVal);
21600
21601       // Load the scalar.
21602       Vals[i] = DAG.getLoad(ElementType, dl, Ch,
21603                             ScalarAddr, MachinePointerInfo(),
21604                             false, false, false, 0);
21605
21606     }
21607   }
21608
21609   // Replace the extracts
21610   for (SmallVectorImpl<SDNode *>::iterator UI = Uses.begin(),
21611     UE = Uses.end(); UI != UE; ++UI) {
21612     SDNode *Extract = *UI;
21613
21614     SDValue Idx = Extract->getOperand(1);
21615     uint64_t IdxVal = cast<ConstantSDNode>(Idx)->getZExtValue();
21616     DAG.ReplaceAllUsesOfValueWith(SDValue(Extract, 0), Vals[IdxVal]);
21617   }
21618
21619   // The replacement was made in place; don't return anything.
21620   return SDValue();
21621 }
21622
21623 /// \brief Matches a VSELECT onto min/max or return 0 if the node doesn't match.
21624 static std::pair<unsigned, bool>
21625 matchIntegerMINMAX(SDValue Cond, EVT VT, SDValue LHS, SDValue RHS,
21626                    SelectionDAG &DAG, const X86Subtarget *Subtarget) {
21627   if (!VT.isVector())
21628     return std::make_pair(0, false);
21629
21630   bool NeedSplit = false;
21631   switch (VT.getSimpleVT().SimpleTy) {
21632   default: return std::make_pair(0, false);
21633   case MVT::v4i64:
21634   case MVT::v2i64:
21635     if (!Subtarget->hasVLX())
21636       return std::make_pair(0, false);
21637     break;
21638   case MVT::v64i8:
21639   case MVT::v32i16:
21640     if (!Subtarget->hasBWI())
21641       return std::make_pair(0, false);
21642     break;
21643   case MVT::v16i32:
21644   case MVT::v8i64:
21645     if (!Subtarget->hasAVX512())
21646       return std::make_pair(0, false);
21647     break;
21648   case MVT::v32i8:
21649   case MVT::v16i16:
21650   case MVT::v8i32:
21651     if (!Subtarget->hasAVX2())
21652       NeedSplit = true;
21653     if (!Subtarget->hasAVX())
21654       return std::make_pair(0, false);
21655     break;
21656   case MVT::v16i8:
21657   case MVT::v8i16:
21658   case MVT::v4i32:
21659     if (!Subtarget->hasSSE2())
21660       return std::make_pair(0, false);
21661   }
21662
21663   // SSE2 has only a small subset of the operations.
21664   bool hasUnsigned = Subtarget->hasSSE41() ||
21665                      (Subtarget->hasSSE2() && VT == MVT::v16i8);
21666   bool hasSigned = Subtarget->hasSSE41() ||
21667                    (Subtarget->hasSSE2() && VT == MVT::v8i16);
21668
21669   ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21670
21671   unsigned Opc = 0;
21672   // Check for x CC y ? x : y.
21673   if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21674       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21675     switch (CC) {
21676     default: break;
21677     case ISD::SETULT:
21678     case ISD::SETULE:
21679       Opc = hasUnsigned ? ISD::UMIN : 0u; break;
21680     case ISD::SETUGT:
21681     case ISD::SETUGE:
21682       Opc = hasUnsigned ? ISD::UMAX : 0u; break;
21683     case ISD::SETLT:
21684     case ISD::SETLE:
21685       Opc = hasSigned ? ISD::SMIN : 0u; break;
21686     case ISD::SETGT:
21687     case ISD::SETGE:
21688       Opc = hasSigned ? ISD::SMAX : 0u; break;
21689     }
21690   // Check for x CC y ? y : x -- a min/max with reversed arms.
21691   } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21692              DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21693     switch (CC) {
21694     default: break;
21695     case ISD::SETULT:
21696     case ISD::SETULE:
21697       Opc = hasUnsigned ? ISD::UMAX : 0u; break;
21698     case ISD::SETUGT:
21699     case ISD::SETUGE:
21700       Opc = hasUnsigned ? ISD::UMIN : 0u; break;
21701     case ISD::SETLT:
21702     case ISD::SETLE:
21703       Opc = hasSigned ? ISD::SMAX : 0u; break;
21704     case ISD::SETGT:
21705     case ISD::SETGE:
21706       Opc = hasSigned ? ISD::SMIN : 0u; break;
21707     }
21708   }
21709
21710   return std::make_pair(Opc, NeedSplit);
21711 }
21712
21713 static SDValue
21714 transformVSELECTtoBlendVECTOR_SHUFFLE(SDNode *N, SelectionDAG &DAG,
21715                                       const X86Subtarget *Subtarget) {
21716   SDLoc dl(N);
21717   SDValue Cond = N->getOperand(0);
21718   SDValue LHS = N->getOperand(1);
21719   SDValue RHS = N->getOperand(2);
21720
21721   if (Cond.getOpcode() == ISD::SIGN_EXTEND) {
21722     SDValue CondSrc = Cond->getOperand(0);
21723     if (CondSrc->getOpcode() == ISD::SIGN_EXTEND_INREG)
21724       Cond = CondSrc->getOperand(0);
21725   }
21726
21727   if (!ISD::isBuildVectorOfConstantSDNodes(Cond.getNode()))
21728     return SDValue();
21729
21730   // A vselect where all conditions and data are constants can be optimized into
21731   // a single vector load by SelectionDAGLegalize::ExpandBUILD_VECTOR().
21732   if (ISD::isBuildVectorOfConstantSDNodes(LHS.getNode()) &&
21733       ISD::isBuildVectorOfConstantSDNodes(RHS.getNode()))
21734     return SDValue();
21735
21736   unsigned MaskValue = 0;
21737   if (!BUILD_VECTORtoBlendMask(cast<BuildVectorSDNode>(Cond), MaskValue))
21738     return SDValue();
21739
21740   MVT VT = N->getSimpleValueType(0);
21741   unsigned NumElems = VT.getVectorNumElements();
21742   SmallVector<int, 8> ShuffleMask(NumElems, -1);
21743   for (unsigned i = 0; i < NumElems; ++i) {
21744     // Be sure we emit undef where we can.
21745     if (Cond.getOperand(i)->getOpcode() == ISD::UNDEF)
21746       ShuffleMask[i] = -1;
21747     else
21748       ShuffleMask[i] = i + NumElems * ((MaskValue >> i) & 1);
21749   }
21750
21751   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21752   if (!TLI.isShuffleMaskLegal(ShuffleMask, VT))
21753     return SDValue();
21754   return DAG.getVectorShuffle(VT, dl, LHS, RHS, &ShuffleMask[0]);
21755 }
21756
21757 /// PerformSELECTCombine - Do target-specific dag combines on SELECT and VSELECT
21758 /// nodes.
21759 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
21760                                     TargetLowering::DAGCombinerInfo &DCI,
21761                                     const X86Subtarget *Subtarget) {
21762   SDLoc DL(N);
21763   SDValue Cond = N->getOperand(0);
21764   // Get the LHS/RHS of the select.
21765   SDValue LHS = N->getOperand(1);
21766   SDValue RHS = N->getOperand(2);
21767   EVT VT = LHS.getValueType();
21768   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
21769
21770   // If we have SSE[12] support, try to form min/max nodes. SSE min/max
21771   // instructions match the semantics of the common C idiom x<y?x:y but not
21772   // x<=y?x:y, because of how they handle negative zero (which can be
21773   // ignored in unsafe-math mode).
21774   // We also try to create v2f32 min/max nodes, which we later widen to v4f32.
21775   if (Cond.getOpcode() == ISD::SETCC && VT.isFloatingPoint() &&
21776       VT != MVT::f80 && (TLI.isTypeLegal(VT) || VT == MVT::v2f32) &&
21777       (Subtarget->hasSSE2() ||
21778        (Subtarget->hasSSE1() && VT.getScalarType() == MVT::f32))) {
21779     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
21780
21781     unsigned Opcode = 0;
21782     // Check for x CC y ? x : y.
21783     if (DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
21784         DAG.isEqualTo(RHS, Cond.getOperand(1))) {
21785       switch (CC) {
21786       default: break;
21787       case ISD::SETULT:
21788         // Converting this to a min would handle NaNs incorrectly, and swapping
21789         // the operands would cause it to handle comparisons between positive
21790         // and negative zero incorrectly.
21791         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21792           if (!DAG.getTarget().Options.UnsafeFPMath &&
21793               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21794             break;
21795           std::swap(LHS, RHS);
21796         }
21797         Opcode = X86ISD::FMIN;
21798         break;
21799       case ISD::SETOLE:
21800         // Converting this to a min would handle comparisons between positive
21801         // and negative zero incorrectly.
21802         if (!DAG.getTarget().Options.UnsafeFPMath &&
21803             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21804           break;
21805         Opcode = X86ISD::FMIN;
21806         break;
21807       case ISD::SETULE:
21808         // Converting this to a min would handle both negative zeros and NaNs
21809         // incorrectly, but we can swap the operands to fix both.
21810         std::swap(LHS, RHS);
21811       case ISD::SETOLT:
21812       case ISD::SETLT:
21813       case ISD::SETLE:
21814         Opcode = X86ISD::FMIN;
21815         break;
21816
21817       case ISD::SETOGE:
21818         // Converting this to a max would handle comparisons between positive
21819         // and negative zero incorrectly.
21820         if (!DAG.getTarget().Options.UnsafeFPMath &&
21821             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS))
21822           break;
21823         Opcode = X86ISD::FMAX;
21824         break;
21825       case ISD::SETUGT:
21826         // Converting this to a max would handle NaNs incorrectly, and swapping
21827         // the operands would cause it to handle comparisons between positive
21828         // and negative zero incorrectly.
21829         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)) {
21830           if (!DAG.getTarget().Options.UnsafeFPMath &&
21831               !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS)))
21832             break;
21833           std::swap(LHS, RHS);
21834         }
21835         Opcode = X86ISD::FMAX;
21836         break;
21837       case ISD::SETUGE:
21838         // Converting this to a max would handle both negative zeros and NaNs
21839         // incorrectly, but we can swap the operands to fix both.
21840         std::swap(LHS, RHS);
21841       case ISD::SETOGT:
21842       case ISD::SETGT:
21843       case ISD::SETGE:
21844         Opcode = X86ISD::FMAX;
21845         break;
21846       }
21847     // Check for x CC y ? y : x -- a min/max with reversed arms.
21848     } else if (DAG.isEqualTo(LHS, Cond.getOperand(1)) &&
21849                DAG.isEqualTo(RHS, Cond.getOperand(0))) {
21850       switch (CC) {
21851       default: break;
21852       case ISD::SETOGE:
21853         // Converting this to a min would handle comparisons between positive
21854         // and negative zero incorrectly, and swapping the operands would
21855         // cause it to handle NaNs incorrectly.
21856         if (!DAG.getTarget().Options.UnsafeFPMath &&
21857             !(DAG.isKnownNeverZero(LHS) || DAG.isKnownNeverZero(RHS))) {
21858           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21859             break;
21860           std::swap(LHS, RHS);
21861         }
21862         Opcode = X86ISD::FMIN;
21863         break;
21864       case ISD::SETUGT:
21865         // Converting this to a min would handle NaNs incorrectly.
21866         if (!DAG.getTarget().Options.UnsafeFPMath &&
21867             (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS)))
21868           break;
21869         Opcode = X86ISD::FMIN;
21870         break;
21871       case ISD::SETUGE:
21872         // Converting this to a min would handle both negative zeros and NaNs
21873         // incorrectly, but we can swap the operands to fix both.
21874         std::swap(LHS, RHS);
21875       case ISD::SETOGT:
21876       case ISD::SETGT:
21877       case ISD::SETGE:
21878         Opcode = X86ISD::FMIN;
21879         break;
21880
21881       case ISD::SETULT:
21882         // Converting this to a max would handle NaNs incorrectly.
21883         if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21884           break;
21885         Opcode = X86ISD::FMAX;
21886         break;
21887       case ISD::SETOLE:
21888         // Converting this to a max would handle comparisons between positive
21889         // and negative zero incorrectly, and swapping the operands would
21890         // cause it to handle NaNs incorrectly.
21891         if (!DAG.getTarget().Options.UnsafeFPMath &&
21892             !DAG.isKnownNeverZero(LHS) && !DAG.isKnownNeverZero(RHS)) {
21893           if (!DAG.isKnownNeverNaN(LHS) || !DAG.isKnownNeverNaN(RHS))
21894             break;
21895           std::swap(LHS, RHS);
21896         }
21897         Opcode = X86ISD::FMAX;
21898         break;
21899       case ISD::SETULE:
21900         // Converting this to a max would handle both negative zeros and NaNs
21901         // incorrectly, but we can swap the operands to fix both.
21902         std::swap(LHS, RHS);
21903       case ISD::SETOLT:
21904       case ISD::SETLT:
21905       case ISD::SETLE:
21906         Opcode = X86ISD::FMAX;
21907         break;
21908       }
21909     }
21910
21911     if (Opcode)
21912       return DAG.getNode(Opcode, DL, N->getValueType(0), LHS, RHS);
21913   }
21914
21915   EVT CondVT = Cond.getValueType();
21916   if (Subtarget->hasAVX512() && VT.isVector() && CondVT.isVector() &&
21917       CondVT.getVectorElementType() == MVT::i1) {
21918     // v16i8 (select v16i1, v16i8, v16i8) does not have a proper
21919     // lowering on KNL. In this case we convert it to
21920     // v16i8 (select v16i8, v16i8, v16i8) and use AVX instruction.
21921     // The same situation for all 128 and 256-bit vectors of i8 and i16.
21922     // Since SKX these selects have a proper lowering.
21923     EVT OpVT = LHS.getValueType();
21924     if ((OpVT.is128BitVector() || OpVT.is256BitVector()) &&
21925         (OpVT.getVectorElementType() == MVT::i8 ||
21926          OpVT.getVectorElementType() == MVT::i16) &&
21927         !(Subtarget->hasBWI() && Subtarget->hasVLX())) {
21928       Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, OpVT, Cond);
21929       DCI.AddToWorklist(Cond.getNode());
21930       return DAG.getNode(N->getOpcode(), DL, OpVT, Cond, LHS, RHS);
21931     }
21932   }
21933   // If this is a select between two integer constants, try to do some
21934   // optimizations.
21935   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(LHS)) {
21936     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(RHS))
21937       // Don't do this for crazy integer types.
21938       if (DAG.getTargetLoweringInfo().isTypeLegal(LHS.getValueType())) {
21939         // If this is efficiently invertible, canonicalize the LHSC/RHSC values
21940         // so that TrueC (the true value) is larger than FalseC.
21941         bool NeedsCondInvert = false;
21942
21943         if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue()) &&
21944             // Efficiently invertible.
21945             (Cond.getOpcode() == ISD::SETCC ||  // setcc -> invertible.
21946              (Cond.getOpcode() == ISD::XOR &&   // xor(X, C) -> invertible.
21947               isa<ConstantSDNode>(Cond.getOperand(1))))) {
21948           NeedsCondInvert = true;
21949           std::swap(TrueC, FalseC);
21950         }
21951
21952         // Optimize C ? 8 : 0 -> zext(C) << 3.  Likewise for any pow2/0.
21953         if (FalseC->getAPIntValue() == 0 &&
21954             TrueC->getAPIntValue().isPowerOf2()) {
21955           if (NeedsCondInvert) // Invert the condition if needed.
21956             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21957                                DAG.getConstant(1, DL, Cond.getValueType()));
21958
21959           // Zero extend the condition if needed.
21960           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, LHS.getValueType(), Cond);
21961
21962           unsigned ShAmt = TrueC->getAPIntValue().logBase2();
21963           return DAG.getNode(ISD::SHL, DL, LHS.getValueType(), Cond,
21964                              DAG.getConstant(ShAmt, DL, MVT::i8));
21965         }
21966
21967         // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.
21968         if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
21969           if (NeedsCondInvert) // Invert the condition if needed.
21970             Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
21971                                DAG.getConstant(1, DL, Cond.getValueType()));
21972
21973           // Zero extend the condition if needed.
21974           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
21975                              FalseC->getValueType(0), Cond);
21976           return DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
21977                              SDValue(FalseC, 0));
21978         }
21979
21980         // Optimize cases that will turn into an LEA instruction.  This requires
21981         // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
21982         if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
21983           uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
21984           if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
21985
21986           bool isFastMultiplier = false;
21987           if (Diff < 10) {
21988             switch ((unsigned char)Diff) {
21989               default: break;
21990               case 1:  // result = add base, cond
21991               case 2:  // result = lea base(    , cond*2)
21992               case 3:  // result = lea base(cond, cond*2)
21993               case 4:  // result = lea base(    , cond*4)
21994               case 5:  // result = lea base(cond, cond*4)
21995               case 8:  // result = lea base(    , cond*8)
21996               case 9:  // result = lea base(cond, cond*8)
21997                 isFastMultiplier = true;
21998                 break;
21999             }
22000           }
22001
22002           if (isFastMultiplier) {
22003             APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22004             if (NeedsCondInvert) // Invert the condition if needed.
22005               Cond = DAG.getNode(ISD::XOR, DL, Cond.getValueType(), Cond,
22006                                  DAG.getConstant(1, DL, Cond.getValueType()));
22007
22008             // Zero extend the condition if needed.
22009             Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22010                                Cond);
22011             // Scale the condition by the difference.
22012             if (Diff != 1)
22013               Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22014                                  DAG.getConstant(Diff, DL,
22015                                                  Cond.getValueType()));
22016
22017             // Add the base if non-zero.
22018             if (FalseC->getAPIntValue() != 0)
22019               Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22020                                  SDValue(FalseC, 0));
22021             return Cond;
22022           }
22023         }
22024       }
22025   }
22026
22027   // Canonicalize max and min:
22028   // (x > y) ? x : y -> (x >= y) ? x : y
22029   // (x < y) ? x : y -> (x <= y) ? x : y
22030   // This allows use of COND_S / COND_NS (see TranslateX86CC) which eliminates
22031   // the need for an extra compare
22032   // against zero. e.g.
22033   // (x - y) > 0 : (x - y) ? 0 -> (x - y) >= 0 : (x - y) ? 0
22034   // subl   %esi, %edi
22035   // testl  %edi, %edi
22036   // movl   $0, %eax
22037   // cmovgl %edi, %eax
22038   // =>
22039   // xorl   %eax, %eax
22040   // subl   %esi, $edi
22041   // cmovsl %eax, %edi
22042   if (N->getOpcode() == ISD::SELECT && Cond.getOpcode() == ISD::SETCC &&
22043       DAG.isEqualTo(LHS, Cond.getOperand(0)) &&
22044       DAG.isEqualTo(RHS, Cond.getOperand(1))) {
22045     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22046     switch (CC) {
22047     default: break;
22048     case ISD::SETLT:
22049     case ISD::SETGT: {
22050       ISD::CondCode NewCC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGE;
22051       Cond = DAG.getSetCC(SDLoc(Cond), Cond.getValueType(),
22052                           Cond.getOperand(0), Cond.getOperand(1), NewCC);
22053       return DAG.getNode(ISD::SELECT, DL, VT, Cond, LHS, RHS);
22054     }
22055     }
22056   }
22057
22058   // Early exit check
22059   if (!TLI.isTypeLegal(VT))
22060     return SDValue();
22061
22062   // Match VSELECTs into subs with unsigned saturation.
22063   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC &&
22064       // psubus is available in SSE2 and AVX2 for i8 and i16 vectors.
22065       ((Subtarget->hasSSE2() && (VT == MVT::v16i8 || VT == MVT::v8i16)) ||
22066        (Subtarget->hasAVX2() && (VT == MVT::v32i8 || VT == MVT::v16i16)))) {
22067     ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
22068
22069     // Check if one of the arms of the VSELECT is a zero vector. If it's on the
22070     // left side invert the predicate to simplify logic below.
22071     SDValue Other;
22072     if (ISD::isBuildVectorAllZeros(LHS.getNode())) {
22073       Other = RHS;
22074       CC = ISD::getSetCCInverse(CC, true);
22075     } else if (ISD::isBuildVectorAllZeros(RHS.getNode())) {
22076       Other = LHS;
22077     }
22078
22079     if (Other.getNode() && Other->getNumOperands() == 2 &&
22080         DAG.isEqualTo(Other->getOperand(0), Cond.getOperand(0))) {
22081       SDValue OpLHS = Other->getOperand(0), OpRHS = Other->getOperand(1);
22082       SDValue CondRHS = Cond->getOperand(1);
22083
22084       // Look for a general sub with unsigned saturation first.
22085       // x >= y ? x-y : 0 --> subus x, y
22086       // x >  y ? x-y : 0 --> subus x, y
22087       if ((CC == ISD::SETUGE || CC == ISD::SETUGT) &&
22088           Other->getOpcode() == ISD::SUB && DAG.isEqualTo(OpRHS, CondRHS))
22089         return DAG.getNode(X86ISD::SUBUS, DL, VT, OpLHS, OpRHS);
22090
22091       if (auto *OpRHSBV = dyn_cast<BuildVectorSDNode>(OpRHS))
22092         if (auto *OpRHSConst = OpRHSBV->getConstantSplatNode()) {
22093           if (auto *CondRHSBV = dyn_cast<BuildVectorSDNode>(CondRHS))
22094             if (auto *CondRHSConst = CondRHSBV->getConstantSplatNode())
22095               // If the RHS is a constant we have to reverse the const
22096               // canonicalization.
22097               // x > C-1 ? x+-C : 0 --> subus x, C
22098               if (CC == ISD::SETUGT && Other->getOpcode() == ISD::ADD &&
22099                   CondRHSConst->getAPIntValue() ==
22100                       (-OpRHSConst->getAPIntValue() - 1))
22101                 return DAG.getNode(
22102                     X86ISD::SUBUS, DL, VT, OpLHS,
22103                     DAG.getConstant(-OpRHSConst->getAPIntValue(), DL, VT));
22104
22105           // Another special case: If C was a sign bit, the sub has been
22106           // canonicalized into a xor.
22107           // FIXME: Would it be better to use computeKnownBits to determine
22108           //        whether it's safe to decanonicalize the xor?
22109           // x s< 0 ? x^C : 0 --> subus x, C
22110           if (CC == ISD::SETLT && Other->getOpcode() == ISD::XOR &&
22111               ISD::isBuildVectorAllZeros(CondRHS.getNode()) &&
22112               OpRHSConst->getAPIntValue().isSignBit())
22113             // Note that we have to rebuild the RHS constant here to ensure we
22114             // don't rely on particular values of undef lanes.
22115             return DAG.getNode(
22116                 X86ISD::SUBUS, DL, VT, OpLHS,
22117                 DAG.getConstant(OpRHSConst->getAPIntValue(), DL, VT));
22118         }
22119     }
22120   }
22121
22122   // Try to match a min/max vector operation.
22123   if (N->getOpcode() == ISD::VSELECT && Cond.getOpcode() == ISD::SETCC) {
22124     std::pair<unsigned, bool> ret = matchIntegerMINMAX(Cond, VT, LHS, RHS, DAG, Subtarget);
22125     unsigned Opc = ret.first;
22126     bool NeedSplit = ret.second;
22127
22128     if (Opc && NeedSplit) {
22129       unsigned NumElems = VT.getVectorNumElements();
22130       // Extract the LHS vectors
22131       SDValue LHS1 = Extract128BitVector(LHS, 0, DAG, DL);
22132       SDValue LHS2 = Extract128BitVector(LHS, NumElems/2, DAG, DL);
22133
22134       // Extract the RHS vectors
22135       SDValue RHS1 = Extract128BitVector(RHS, 0, DAG, DL);
22136       SDValue RHS2 = Extract128BitVector(RHS, NumElems/2, DAG, DL);
22137
22138       // Create min/max for each subvector
22139       LHS = DAG.getNode(Opc, DL, LHS1.getValueType(), LHS1, RHS1);
22140       RHS = DAG.getNode(Opc, DL, LHS2.getValueType(), LHS2, RHS2);
22141
22142       // Merge the result
22143       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, LHS, RHS);
22144     } else if (Opc)
22145       return DAG.getNode(Opc, DL, VT, LHS, RHS);
22146   }
22147
22148   // Simplify vector selection if condition value type matches vselect
22149   // operand type
22150   if (N->getOpcode() == ISD::VSELECT && CondVT == VT) {
22151     assert(Cond.getValueType().isVector() &&
22152            "vector select expects a vector selector!");
22153
22154     bool TValIsAllOnes = ISD::isBuildVectorAllOnes(LHS.getNode());
22155     bool FValIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
22156
22157     // Try invert the condition if true value is not all 1s and false value
22158     // is not all 0s.
22159     if (!TValIsAllOnes && !FValIsAllZeros &&
22160         // Check if the selector will be produced by CMPP*/PCMP*
22161         Cond.getOpcode() == ISD::SETCC &&
22162         // Check if SETCC has already been promoted
22163         TLI.getSetCCResultType(*DAG.getContext(), VT) == CondVT) {
22164       bool TValIsAllZeros = ISD::isBuildVectorAllZeros(LHS.getNode());
22165       bool FValIsAllOnes = ISD::isBuildVectorAllOnes(RHS.getNode());
22166
22167       if (TValIsAllZeros || FValIsAllOnes) {
22168         SDValue CC = Cond.getOperand(2);
22169         ISD::CondCode NewCC =
22170           ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
22171                                Cond.getOperand(0).getValueType().isInteger());
22172         Cond = DAG.getSetCC(DL, CondVT, Cond.getOperand(0), Cond.getOperand(1), NewCC);
22173         std::swap(LHS, RHS);
22174         TValIsAllOnes = FValIsAllOnes;
22175         FValIsAllZeros = TValIsAllZeros;
22176       }
22177     }
22178
22179     if (TValIsAllOnes || FValIsAllZeros) {
22180       SDValue Ret;
22181
22182       if (TValIsAllOnes && FValIsAllZeros)
22183         Ret = Cond;
22184       else if (TValIsAllOnes)
22185         Ret =
22186             DAG.getNode(ISD::OR, DL, CondVT, Cond, DAG.getBitcast(CondVT, RHS));
22187       else if (FValIsAllZeros)
22188         Ret = DAG.getNode(ISD::AND, DL, CondVT, Cond,
22189                           DAG.getBitcast(CondVT, LHS));
22190
22191       return DAG.getBitcast(VT, Ret);
22192     }
22193   }
22194
22195   // We should generate an X86ISD::BLENDI from a vselect if its argument
22196   // is a sign_extend_inreg of an any_extend of a BUILD_VECTOR of
22197   // constants. This specific pattern gets generated when we split a
22198   // selector for a 512 bit vector in a machine without AVX512 (but with
22199   // 256-bit vectors), during legalization:
22200   //
22201   // (vselect (sign_extend (any_extend (BUILD_VECTOR)) i1) LHS RHS)
22202   //
22203   // Iff we find this pattern and the build_vectors are built from
22204   // constants, we translate the vselect into a shuffle_vector that we
22205   // know will be matched by LowerVECTOR_SHUFFLEtoBlend.
22206   if ((N->getOpcode() == ISD::VSELECT ||
22207        N->getOpcode() == X86ISD::SHRUNKBLEND) &&
22208       !DCI.isBeforeLegalize() && !VT.is512BitVector()) {
22209     SDValue Shuffle = transformVSELECTtoBlendVECTOR_SHUFFLE(N, DAG, Subtarget);
22210     if (Shuffle.getNode())
22211       return Shuffle;
22212   }
22213
22214   // If this is a *dynamic* select (non-constant condition) and we can match
22215   // this node with one of the variable blend instructions, restructure the
22216   // condition so that the blends can use the high bit of each element and use
22217   // SimplifyDemandedBits to simplify the condition operand.
22218   if (N->getOpcode() == ISD::VSELECT && DCI.isBeforeLegalizeOps() &&
22219       !DCI.isBeforeLegalize() &&
22220       !ISD::isBuildVectorOfConstantSDNodes(Cond.getNode())) {
22221     unsigned BitWidth = Cond.getValueType().getScalarType().getSizeInBits();
22222
22223     // Don't optimize vector selects that map to mask-registers.
22224     if (BitWidth == 1)
22225       return SDValue();
22226
22227     // We can only handle the cases where VSELECT is directly legal on the
22228     // subtarget. We custom lower VSELECT nodes with constant conditions and
22229     // this makes it hard to see whether a dynamic VSELECT will correctly
22230     // lower, so we both check the operation's status and explicitly handle the
22231     // cases where a *dynamic* blend will fail even though a constant-condition
22232     // blend could be custom lowered.
22233     // FIXME: We should find a better way to handle this class of problems.
22234     // Potentially, we should combine constant-condition vselect nodes
22235     // pre-legalization into shuffles and not mark as many types as custom
22236     // lowered.
22237     if (!TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
22238       return SDValue();
22239     // FIXME: We don't support i16-element blends currently. We could and
22240     // should support them by making *all* the bits in the condition be set
22241     // rather than just the high bit and using an i8-element blend.
22242     if (VT.getScalarType() == MVT::i16)
22243       return SDValue();
22244     // Dynamic blending was only available from SSE4.1 onward.
22245     if (VT.getSizeInBits() == 128 && !Subtarget->hasSSE41())
22246       return SDValue();
22247     // Byte blends are only available in AVX2
22248     if (VT.getSizeInBits() == 256 && VT.getScalarType() == MVT::i8 &&
22249         !Subtarget->hasAVX2())
22250       return SDValue();
22251
22252     assert(BitWidth >= 8 && BitWidth <= 64 && "Invalid mask size");
22253     APInt DemandedMask = APInt::getHighBitsSet(BitWidth, 1);
22254
22255     APInt KnownZero, KnownOne;
22256     TargetLowering::TargetLoweringOpt TLO(DAG, DCI.isBeforeLegalize(),
22257                                           DCI.isBeforeLegalizeOps());
22258     if (TLO.ShrinkDemandedConstant(Cond, DemandedMask) ||
22259         TLI.SimplifyDemandedBits(Cond, DemandedMask, KnownZero, KnownOne,
22260                                  TLO)) {
22261       // If we changed the computation somewhere in the DAG, this change
22262       // will affect all users of Cond.
22263       // Make sure it is fine and update all the nodes so that we do not
22264       // use the generic VSELECT anymore. Otherwise, we may perform
22265       // wrong optimizations as we messed up with the actual expectation
22266       // for the vector boolean values.
22267       if (Cond != TLO.Old) {
22268         // Check all uses of that condition operand to check whether it will be
22269         // consumed by non-BLEND instructions, which may depend on all bits are
22270         // set properly.
22271         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22272              I != E; ++I)
22273           if (I->getOpcode() != ISD::VSELECT)
22274             // TODO: Add other opcodes eventually lowered into BLEND.
22275             return SDValue();
22276
22277         // Update all the users of the condition, before committing the change,
22278         // so that the VSELECT optimizations that expect the correct vector
22279         // boolean value will not be triggered.
22280         for (SDNode::use_iterator I = Cond->use_begin(), E = Cond->use_end();
22281              I != E; ++I)
22282           DAG.ReplaceAllUsesOfValueWith(
22283               SDValue(*I, 0),
22284               DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(*I), I->getValueType(0),
22285                           Cond, I->getOperand(1), I->getOperand(2)));
22286         DCI.CommitTargetLoweringOpt(TLO);
22287         return SDValue();
22288       }
22289       // At this point, only Cond is changed. Change the condition
22290       // just for N to keep the opportunity to optimize all other
22291       // users their own way.
22292       DAG.ReplaceAllUsesOfValueWith(
22293           SDValue(N, 0),
22294           DAG.getNode(X86ISD::SHRUNKBLEND, SDLoc(N), N->getValueType(0),
22295                       TLO.New, N->getOperand(1), N->getOperand(2)));
22296       return SDValue();
22297     }
22298   }
22299
22300   return SDValue();
22301 }
22302
22303 // Check whether a boolean test is testing a boolean value generated by
22304 // X86ISD::SETCC. If so, return the operand of that SETCC and proper condition
22305 // code.
22306 //
22307 // Simplify the following patterns:
22308 // (Op (CMP (SETCC Cond EFLAGS) 1) EQ) or
22309 // (Op (CMP (SETCC Cond EFLAGS) 0) NEQ)
22310 // to (Op EFLAGS Cond)
22311 //
22312 // (Op (CMP (SETCC Cond EFLAGS) 0) EQ) or
22313 // (Op (CMP (SETCC Cond EFLAGS) 1) NEQ)
22314 // to (Op EFLAGS !Cond)
22315 //
22316 // where Op could be BRCOND or CMOV.
22317 //
22318 static SDValue checkBoolTestSetCCCombine(SDValue Cmp, X86::CondCode &CC) {
22319   // Quit if not CMP and SUB with its value result used.
22320   if (Cmp.getOpcode() != X86ISD::CMP &&
22321       (Cmp.getOpcode() != X86ISD::SUB || Cmp.getNode()->hasAnyUseOfValue(0)))
22322       return SDValue();
22323
22324   // Quit if not used as a boolean value.
22325   if (CC != X86::COND_E && CC != X86::COND_NE)
22326     return SDValue();
22327
22328   // Check CMP operands. One of them should be 0 or 1 and the other should be
22329   // an SetCC or extended from it.
22330   SDValue Op1 = Cmp.getOperand(0);
22331   SDValue Op2 = Cmp.getOperand(1);
22332
22333   SDValue SetCC;
22334   const ConstantSDNode* C = nullptr;
22335   bool needOppositeCond = (CC == X86::COND_E);
22336   bool checkAgainstTrue = false; // Is it a comparison against 1?
22337
22338   if ((C = dyn_cast<ConstantSDNode>(Op1)))
22339     SetCC = Op2;
22340   else if ((C = dyn_cast<ConstantSDNode>(Op2)))
22341     SetCC = Op1;
22342   else // Quit if all operands are not constants.
22343     return SDValue();
22344
22345   if (C->getZExtValue() == 1) {
22346     needOppositeCond = !needOppositeCond;
22347     checkAgainstTrue = true;
22348   } else if (C->getZExtValue() != 0)
22349     // Quit if the constant is neither 0 or 1.
22350     return SDValue();
22351
22352   bool truncatedToBoolWithAnd = false;
22353   // Skip (zext $x), (trunc $x), or (and $x, 1) node.
22354   while (SetCC.getOpcode() == ISD::ZERO_EXTEND ||
22355          SetCC.getOpcode() == ISD::TRUNCATE ||
22356          SetCC.getOpcode() == ISD::AND) {
22357     if (SetCC.getOpcode() == ISD::AND) {
22358       int OpIdx = -1;
22359       ConstantSDNode *CS;
22360       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(0))) &&
22361           CS->getZExtValue() == 1)
22362         OpIdx = 1;
22363       if ((CS = dyn_cast<ConstantSDNode>(SetCC.getOperand(1))) &&
22364           CS->getZExtValue() == 1)
22365         OpIdx = 0;
22366       if (OpIdx == -1)
22367         break;
22368       SetCC = SetCC.getOperand(OpIdx);
22369       truncatedToBoolWithAnd = true;
22370     } else
22371       SetCC = SetCC.getOperand(0);
22372   }
22373
22374   switch (SetCC.getOpcode()) {
22375   case X86ISD::SETCC_CARRY:
22376     // Since SETCC_CARRY gives output based on R = CF ? ~0 : 0, it's unsafe to
22377     // simplify it if the result of SETCC_CARRY is not canonicalized to 0 or 1,
22378     // i.e. it's a comparison against true but the result of SETCC_CARRY is not
22379     // truncated to i1 using 'and'.
22380     if (checkAgainstTrue && !truncatedToBoolWithAnd)
22381       break;
22382     assert(X86::CondCode(SetCC.getConstantOperandVal(0)) == X86::COND_B &&
22383            "Invalid use of SETCC_CARRY!");
22384     // FALL THROUGH
22385   case X86ISD::SETCC:
22386     // Set the condition code or opposite one if necessary.
22387     CC = X86::CondCode(SetCC.getConstantOperandVal(0));
22388     if (needOppositeCond)
22389       CC = X86::GetOppositeBranchCondition(CC);
22390     return SetCC.getOperand(1);
22391   case X86ISD::CMOV: {
22392     // Check whether false/true value has canonical one, i.e. 0 or 1.
22393     ConstantSDNode *FVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(0));
22394     ConstantSDNode *TVal = dyn_cast<ConstantSDNode>(SetCC.getOperand(1));
22395     // Quit if true value is not a constant.
22396     if (!TVal)
22397       return SDValue();
22398     // Quit if false value is not a constant.
22399     if (!FVal) {
22400       SDValue Op = SetCC.getOperand(0);
22401       // Skip 'zext' or 'trunc' node.
22402       if (Op.getOpcode() == ISD::ZERO_EXTEND ||
22403           Op.getOpcode() == ISD::TRUNCATE)
22404         Op = Op.getOperand(0);
22405       // A special case for rdrand/rdseed, where 0 is set if false cond is
22406       // found.
22407       if ((Op.getOpcode() != X86ISD::RDRAND &&
22408            Op.getOpcode() != X86ISD::RDSEED) || Op.getResNo() != 0)
22409         return SDValue();
22410     }
22411     // Quit if false value is not the constant 0 or 1.
22412     bool FValIsFalse = true;
22413     if (FVal && FVal->getZExtValue() != 0) {
22414       if (FVal->getZExtValue() != 1)
22415         return SDValue();
22416       // If FVal is 1, opposite cond is needed.
22417       needOppositeCond = !needOppositeCond;
22418       FValIsFalse = false;
22419     }
22420     // Quit if TVal is not the constant opposite of FVal.
22421     if (FValIsFalse && TVal->getZExtValue() != 1)
22422       return SDValue();
22423     if (!FValIsFalse && TVal->getZExtValue() != 0)
22424       return SDValue();
22425     CC = X86::CondCode(SetCC.getConstantOperandVal(2));
22426     if (needOppositeCond)
22427       CC = X86::GetOppositeBranchCondition(CC);
22428     return SetCC.getOperand(3);
22429   }
22430   }
22431
22432   return SDValue();
22433 }
22434
22435 /// Check whether Cond is an AND/OR of SETCCs off of the same EFLAGS.
22436 /// Match:
22437 ///   (X86or (X86setcc) (X86setcc))
22438 ///   (X86cmp (and (X86setcc) (X86setcc)), 0)
22439 static bool checkBoolTestAndOrSetCCCombine(SDValue Cond, X86::CondCode &CC0,
22440                                            X86::CondCode &CC1, SDValue &Flags,
22441                                            bool &isAnd) {
22442   if (Cond->getOpcode() == X86ISD::CMP) {
22443     ConstantSDNode *CondOp1C = dyn_cast<ConstantSDNode>(Cond->getOperand(1));
22444     if (!CondOp1C || !CondOp1C->isNullValue())
22445       return false;
22446
22447     Cond = Cond->getOperand(0);
22448   }
22449
22450   isAnd = false;
22451
22452   SDValue SetCC0, SetCC1;
22453   switch (Cond->getOpcode()) {
22454   default: return false;
22455   case ISD::AND:
22456   case X86ISD::AND:
22457     isAnd = true;
22458     // fallthru
22459   case ISD::OR:
22460   case X86ISD::OR:
22461     SetCC0 = Cond->getOperand(0);
22462     SetCC1 = Cond->getOperand(1);
22463     break;
22464   };
22465
22466   // Make sure we have SETCC nodes, using the same flags value.
22467   if (SetCC0.getOpcode() != X86ISD::SETCC ||
22468       SetCC1.getOpcode() != X86ISD::SETCC ||
22469       SetCC0->getOperand(1) != SetCC1->getOperand(1))
22470     return false;
22471
22472   CC0 = (X86::CondCode)SetCC0->getConstantOperandVal(0);
22473   CC1 = (X86::CondCode)SetCC1->getConstantOperandVal(0);
22474   Flags = SetCC0->getOperand(1);
22475   return true;
22476 }
22477
22478 /// Optimize X86ISD::CMOV [LHS, RHS, CONDCODE (e.g. X86::COND_NE), CONDVAL]
22479 static SDValue PerformCMOVCombine(SDNode *N, SelectionDAG &DAG,
22480                                   TargetLowering::DAGCombinerInfo &DCI,
22481                                   const X86Subtarget *Subtarget) {
22482   SDLoc DL(N);
22483
22484   // If the flag operand isn't dead, don't touch this CMOV.
22485   if (N->getNumValues() == 2 && !SDValue(N, 1).use_empty())
22486     return SDValue();
22487
22488   SDValue FalseOp = N->getOperand(0);
22489   SDValue TrueOp = N->getOperand(1);
22490   X86::CondCode CC = (X86::CondCode)N->getConstantOperandVal(2);
22491   SDValue Cond = N->getOperand(3);
22492
22493   if (CC == X86::COND_E || CC == X86::COND_NE) {
22494     switch (Cond.getOpcode()) {
22495     default: break;
22496     case X86ISD::BSR:
22497     case X86ISD::BSF:
22498       // If operand of BSR / BSF are proven never zero, then ZF cannot be set.
22499       if (DAG.isKnownNeverZero(Cond.getOperand(0)))
22500         return (CC == X86::COND_E) ? FalseOp : TrueOp;
22501     }
22502   }
22503
22504   SDValue Flags;
22505
22506   Flags = checkBoolTestSetCCCombine(Cond, CC);
22507   if (Flags.getNode() &&
22508       // Extra check as FCMOV only supports a subset of X86 cond.
22509       (FalseOp.getValueType() != MVT::f80 || hasFPCMov(CC))) {
22510     SDValue Ops[] = { FalseOp, TrueOp,
22511                       DAG.getConstant(CC, DL, MVT::i8), Flags };
22512     return DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22513   }
22514
22515   // If this is a select between two integer constants, try to do some
22516   // optimizations.  Note that the operands are ordered the opposite of SELECT
22517   // operands.
22518   if (ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(TrueOp)) {
22519     if (ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(FalseOp)) {
22520       // Canonicalize the TrueC/FalseC values so that TrueC (the true value) is
22521       // larger than FalseC (the false value).
22522       if (TrueC->getAPIntValue().ult(FalseC->getAPIntValue())) {
22523         CC = X86::GetOppositeBranchCondition(CC);
22524         std::swap(TrueC, FalseC);
22525         std::swap(TrueOp, FalseOp);
22526       }
22527
22528       // Optimize C ? 8 : 0 -> zext(setcc(C)) << 3.  Likewise for any pow2/0.
22529       // This is efficient for any integer data type (including i8/i16) and
22530       // shift amount.
22531       if (FalseC->getAPIntValue() == 0 && TrueC->getAPIntValue().isPowerOf2()) {
22532         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22533                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22534
22535         // Zero extend the condition if needed.
22536         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, TrueC->getValueType(0), Cond);
22537
22538         unsigned ShAmt = TrueC->getAPIntValue().logBase2();
22539         Cond = DAG.getNode(ISD::SHL, DL, Cond.getValueType(), Cond,
22540                            DAG.getConstant(ShAmt, DL, MVT::i8));
22541         if (N->getNumValues() == 2)  // Dead flag value?
22542           return DCI.CombineTo(N, Cond, SDValue());
22543         return Cond;
22544       }
22545
22546       // Optimize Cond ? cst+1 : cst -> zext(setcc(C)+cst.  This is efficient
22547       // for any integer data type, including i8/i16.
22548       if (FalseC->getAPIntValue()+1 == TrueC->getAPIntValue()) {
22549         Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22550                            DAG.getConstant(CC, DL, MVT::i8), Cond);
22551
22552         // Zero extend the condition if needed.
22553         Cond = DAG.getNode(ISD::ZERO_EXTEND, DL,
22554                            FalseC->getValueType(0), Cond);
22555         Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22556                            SDValue(FalseC, 0));
22557
22558         if (N->getNumValues() == 2)  // Dead flag value?
22559           return DCI.CombineTo(N, Cond, SDValue());
22560         return Cond;
22561       }
22562
22563       // Optimize cases that will turn into an LEA instruction.  This requires
22564       // an i32 or i64 and an efficient multiplier (1, 2, 3, 4, 5, 8, 9).
22565       if (N->getValueType(0) == MVT::i32 || N->getValueType(0) == MVT::i64) {
22566         uint64_t Diff = TrueC->getZExtValue()-FalseC->getZExtValue();
22567         if (N->getValueType(0) == MVT::i32) Diff = (unsigned)Diff;
22568
22569         bool isFastMultiplier = false;
22570         if (Diff < 10) {
22571           switch ((unsigned char)Diff) {
22572           default: break;
22573           case 1:  // result = add base, cond
22574           case 2:  // result = lea base(    , cond*2)
22575           case 3:  // result = lea base(cond, cond*2)
22576           case 4:  // result = lea base(    , cond*4)
22577           case 5:  // result = lea base(cond, cond*4)
22578           case 8:  // result = lea base(    , cond*8)
22579           case 9:  // result = lea base(cond, cond*8)
22580             isFastMultiplier = true;
22581             break;
22582           }
22583         }
22584
22585         if (isFastMultiplier) {
22586           APInt Diff = TrueC->getAPIntValue()-FalseC->getAPIntValue();
22587           Cond = DAG.getNode(X86ISD::SETCC, DL, MVT::i8,
22588                              DAG.getConstant(CC, DL, MVT::i8), Cond);
22589           // Zero extend the condition if needed.
22590           Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, FalseC->getValueType(0),
22591                              Cond);
22592           // Scale the condition by the difference.
22593           if (Diff != 1)
22594             Cond = DAG.getNode(ISD::MUL, DL, Cond.getValueType(), Cond,
22595                                DAG.getConstant(Diff, DL, Cond.getValueType()));
22596
22597           // Add the base if non-zero.
22598           if (FalseC->getAPIntValue() != 0)
22599             Cond = DAG.getNode(ISD::ADD, DL, Cond.getValueType(), Cond,
22600                                SDValue(FalseC, 0));
22601           if (N->getNumValues() == 2)  // Dead flag value?
22602             return DCI.CombineTo(N, Cond, SDValue());
22603           return Cond;
22604         }
22605       }
22606     }
22607   }
22608
22609   // Handle these cases:
22610   //   (select (x != c), e, c) -> select (x != c), e, x),
22611   //   (select (x == c), c, e) -> select (x == c), x, e)
22612   // where the c is an integer constant, and the "select" is the combination
22613   // of CMOV and CMP.
22614   //
22615   // The rationale for this change is that the conditional-move from a constant
22616   // needs two instructions, however, conditional-move from a register needs
22617   // only one instruction.
22618   //
22619   // CAVEAT: By replacing a constant with a symbolic value, it may obscure
22620   //  some instruction-combining opportunities. This opt needs to be
22621   //  postponed as late as possible.
22622   //
22623   if (!DCI.isBeforeLegalize() && !DCI.isBeforeLegalizeOps()) {
22624     // the DCI.xxxx conditions are provided to postpone the optimization as
22625     // late as possible.
22626
22627     ConstantSDNode *CmpAgainst = nullptr;
22628     if ((Cond.getOpcode() == X86ISD::CMP || Cond.getOpcode() == X86ISD::SUB) &&
22629         (CmpAgainst = dyn_cast<ConstantSDNode>(Cond.getOperand(1))) &&
22630         !isa<ConstantSDNode>(Cond.getOperand(0))) {
22631
22632       if (CC == X86::COND_NE &&
22633           CmpAgainst == dyn_cast<ConstantSDNode>(FalseOp)) {
22634         CC = X86::GetOppositeBranchCondition(CC);
22635         std::swap(TrueOp, FalseOp);
22636       }
22637
22638       if (CC == X86::COND_E &&
22639           CmpAgainst == dyn_cast<ConstantSDNode>(TrueOp)) {
22640         SDValue Ops[] = { FalseOp, Cond.getOperand(0),
22641                           DAG.getConstant(CC, DL, MVT::i8), Cond };
22642         return DAG.getNode(X86ISD::CMOV, DL, N->getVTList (), Ops);
22643       }
22644     }
22645   }
22646
22647   // Fold and/or of setcc's to double CMOV:
22648   //   (CMOV F, T, ((cc1 | cc2) != 0)) -> (CMOV (CMOV F, T, cc1), T, cc2)
22649   //   (CMOV F, T, ((cc1 & cc2) != 0)) -> (CMOV (CMOV T, F, !cc1), F, !cc2)
22650   //
22651   // This combine lets us generate:
22652   //   cmovcc1 (jcc1 if we don't have CMOV)
22653   //   cmovcc2 (same)
22654   // instead of:
22655   //   setcc1
22656   //   setcc2
22657   //   and/or
22658   //   cmovne (jne if we don't have CMOV)
22659   // When we can't use the CMOV instruction, it might increase branch
22660   // mispredicts.
22661   // When we can use CMOV, or when there is no mispredict, this improves
22662   // throughput and reduces register pressure.
22663   //
22664   if (CC == X86::COND_NE) {
22665     SDValue Flags;
22666     X86::CondCode CC0, CC1;
22667     bool isAndSetCC;
22668     if (checkBoolTestAndOrSetCCCombine(Cond, CC0, CC1, Flags, isAndSetCC)) {
22669       if (isAndSetCC) {
22670         std::swap(FalseOp, TrueOp);
22671         CC0 = X86::GetOppositeBranchCondition(CC0);
22672         CC1 = X86::GetOppositeBranchCondition(CC1);
22673       }
22674
22675       SDValue LOps[] = {FalseOp, TrueOp, DAG.getConstant(CC0, DL, MVT::i8),
22676         Flags};
22677       SDValue LCMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), LOps);
22678       SDValue Ops[] = {LCMOV, TrueOp, DAG.getConstant(CC1, DL, MVT::i8), Flags};
22679       SDValue CMOV = DAG.getNode(X86ISD::CMOV, DL, N->getVTList(), Ops);
22680       DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(CMOV.getNode(), 1));
22681       return CMOV;
22682     }
22683   }
22684
22685   return SDValue();
22686 }
22687
22688 static SDValue PerformINTRINSIC_WO_CHAINCombine(SDNode *N, SelectionDAG &DAG,
22689                                                 const X86Subtarget *Subtarget) {
22690   unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
22691   switch (IntNo) {
22692   default: return SDValue();
22693   // SSE/AVX/AVX2 blend intrinsics.
22694   case Intrinsic::x86_avx2_pblendvb:
22695     // Don't try to simplify this intrinsic if we don't have AVX2.
22696     if (!Subtarget->hasAVX2())
22697       return SDValue();
22698     // FALL-THROUGH
22699   case Intrinsic::x86_avx_blendv_pd_256:
22700   case Intrinsic::x86_avx_blendv_ps_256:
22701     // Don't try to simplify this intrinsic if we don't have AVX.
22702     if (!Subtarget->hasAVX())
22703       return SDValue();
22704     // FALL-THROUGH
22705   case Intrinsic::x86_sse41_blendvps:
22706   case Intrinsic::x86_sse41_blendvpd:
22707   case Intrinsic::x86_sse41_pblendvb: {
22708     SDValue Op0 = N->getOperand(1);
22709     SDValue Op1 = N->getOperand(2);
22710     SDValue Mask = N->getOperand(3);
22711
22712     // Don't try to simplify this intrinsic if we don't have SSE4.1.
22713     if (!Subtarget->hasSSE41())
22714       return SDValue();
22715
22716     // fold (blend A, A, Mask) -> A
22717     if (Op0 == Op1)
22718       return Op0;
22719     // fold (blend A, B, allZeros) -> A
22720     if (ISD::isBuildVectorAllZeros(Mask.getNode()))
22721       return Op0;
22722     // fold (blend A, B, allOnes) -> B
22723     if (ISD::isBuildVectorAllOnes(Mask.getNode()))
22724       return Op1;
22725
22726     // Simplify the case where the mask is a constant i32 value.
22727     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Mask)) {
22728       if (C->isNullValue())
22729         return Op0;
22730       if (C->isAllOnesValue())
22731         return Op1;
22732     }
22733
22734     return SDValue();
22735   }
22736
22737   // Packed SSE2/AVX2 arithmetic shift immediate intrinsics.
22738   case Intrinsic::x86_sse2_psrai_w:
22739   case Intrinsic::x86_sse2_psrai_d:
22740   case Intrinsic::x86_avx2_psrai_w:
22741   case Intrinsic::x86_avx2_psrai_d:
22742   case Intrinsic::x86_sse2_psra_w:
22743   case Intrinsic::x86_sse2_psra_d:
22744   case Intrinsic::x86_avx2_psra_w:
22745   case Intrinsic::x86_avx2_psra_d: {
22746     SDValue Op0 = N->getOperand(1);
22747     SDValue Op1 = N->getOperand(2);
22748     EVT VT = Op0.getValueType();
22749     assert(VT.isVector() && "Expected a vector type!");
22750
22751     if (isa<BuildVectorSDNode>(Op1))
22752       Op1 = Op1.getOperand(0);
22753
22754     if (!isa<ConstantSDNode>(Op1))
22755       return SDValue();
22756
22757     EVT SVT = VT.getVectorElementType();
22758     unsigned SVTBits = SVT.getSizeInBits();
22759
22760     ConstantSDNode *CND = cast<ConstantSDNode>(Op1);
22761     const APInt &C = APInt(SVTBits, CND->getAPIntValue().getZExtValue());
22762     uint64_t ShAmt = C.getZExtValue();
22763
22764     // Don't try to convert this shift into a ISD::SRA if the shift
22765     // count is bigger than or equal to the element size.
22766     if (ShAmt >= SVTBits)
22767       return SDValue();
22768
22769     // Trivial case: if the shift count is zero, then fold this
22770     // into the first operand.
22771     if (ShAmt == 0)
22772       return Op0;
22773
22774     // Replace this packed shift intrinsic with a target independent
22775     // shift dag node.
22776     SDLoc DL(N);
22777     SDValue Splat = DAG.getConstant(C, DL, VT);
22778     return DAG.getNode(ISD::SRA, DL, VT, Op0, Splat);
22779   }
22780   }
22781 }
22782
22783 /// PerformMulCombine - Optimize a single multiply with constant into two
22784 /// in order to implement it with two cheaper instructions, e.g.
22785 /// LEA + SHL, LEA + LEA.
22786 static SDValue PerformMulCombine(SDNode *N, SelectionDAG &DAG,
22787                                  TargetLowering::DAGCombinerInfo &DCI) {
22788   if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
22789     return SDValue();
22790
22791   EVT VT = N->getValueType(0);
22792   if (VT != MVT::i64 && VT != MVT::i32)
22793     return SDValue();
22794
22795   ConstantSDNode *C = dyn_cast<ConstantSDNode>(N->getOperand(1));
22796   if (!C)
22797     return SDValue();
22798   uint64_t MulAmt = C->getZExtValue();
22799   if (isPowerOf2_64(MulAmt) || MulAmt == 3 || MulAmt == 5 || MulAmt == 9)
22800     return SDValue();
22801
22802   uint64_t MulAmt1 = 0;
22803   uint64_t MulAmt2 = 0;
22804   if ((MulAmt % 9) == 0) {
22805     MulAmt1 = 9;
22806     MulAmt2 = MulAmt / 9;
22807   } else if ((MulAmt % 5) == 0) {
22808     MulAmt1 = 5;
22809     MulAmt2 = MulAmt / 5;
22810   } else if ((MulAmt % 3) == 0) {
22811     MulAmt1 = 3;
22812     MulAmt2 = MulAmt / 3;
22813   }
22814   if (MulAmt2 &&
22815       (isPowerOf2_64(MulAmt2) || MulAmt2 == 3 || MulAmt2 == 5 || MulAmt2 == 9)){
22816     SDLoc DL(N);
22817
22818     if (isPowerOf2_64(MulAmt2) &&
22819         !(N->hasOneUse() && N->use_begin()->getOpcode() == ISD::ADD))
22820       // If second multiplifer is pow2, issue it first. We want the multiply by
22821       // 3, 5, or 9 to be folded into the addressing mode unless the lone use
22822       // is an add.
22823       std::swap(MulAmt1, MulAmt2);
22824
22825     SDValue NewMul;
22826     if (isPowerOf2_64(MulAmt1))
22827       NewMul = DAG.getNode(ISD::SHL, DL, VT, N->getOperand(0),
22828                            DAG.getConstant(Log2_64(MulAmt1), DL, MVT::i8));
22829     else
22830       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, N->getOperand(0),
22831                            DAG.getConstant(MulAmt1, DL, VT));
22832
22833     if (isPowerOf2_64(MulAmt2))
22834       NewMul = DAG.getNode(ISD::SHL, DL, VT, NewMul,
22835                            DAG.getConstant(Log2_64(MulAmt2), DL, MVT::i8));
22836     else
22837       NewMul = DAG.getNode(X86ISD::MUL_IMM, DL, VT, NewMul,
22838                            DAG.getConstant(MulAmt2, DL, VT));
22839
22840     // Do not add new nodes to DAG combiner worklist.
22841     DCI.CombineTo(N, NewMul, false);
22842   }
22843   return SDValue();
22844 }
22845
22846 static SDValue PerformSHLCombine(SDNode *N, SelectionDAG &DAG) {
22847   SDValue N0 = N->getOperand(0);
22848   SDValue N1 = N->getOperand(1);
22849   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
22850   EVT VT = N0.getValueType();
22851
22852   // fold (shl (and (setcc_c), c1), c2) -> (and setcc_c, (c1 << c2))
22853   // since the result of setcc_c is all zero's or all ones.
22854   if (VT.isInteger() && !VT.isVector() &&
22855       N1C && N0.getOpcode() == ISD::AND &&
22856       N0.getOperand(1).getOpcode() == ISD::Constant) {
22857     SDValue N00 = N0.getOperand(0);
22858     if (N00.getOpcode() == X86ISD::SETCC_CARRY ||
22859         ((N00.getOpcode() == ISD::ANY_EXTEND ||
22860           N00.getOpcode() == ISD::ZERO_EXTEND) &&
22861          N00.getOperand(0).getOpcode() == X86ISD::SETCC_CARRY)) {
22862       APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
22863       APInt ShAmt = N1C->getAPIntValue();
22864       Mask = Mask.shl(ShAmt);
22865       if (Mask != 0) {
22866         SDLoc DL(N);
22867         return DAG.getNode(ISD::AND, DL, VT,
22868                            N00, DAG.getConstant(Mask, DL, VT));
22869       }
22870     }
22871   }
22872
22873   // Hardware support for vector shifts is sparse which makes us scalarize the
22874   // vector operations in many cases. Also, on sandybridge ADD is faster than
22875   // shl.
22876   // (shl V, 1) -> add V,V
22877   if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
22878     if (auto *N1SplatC = N1BV->getConstantSplatNode()) {
22879       assert(N0.getValueType().isVector() && "Invalid vector shift type");
22880       // We shift all of the values by one. In many cases we do not have
22881       // hardware support for this operation. This is better expressed as an ADD
22882       // of two values.
22883       if (N1SplatC->getZExtValue() == 1)
22884         return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N0);
22885     }
22886
22887   return SDValue();
22888 }
22889
22890 /// \brief Returns a vector of 0s if the node in input is a vector logical
22891 /// shift by a constant amount which is known to be bigger than or equal
22892 /// to the vector element size in bits.
22893 static SDValue performShiftToAllZeros(SDNode *N, SelectionDAG &DAG,
22894                                       const X86Subtarget *Subtarget) {
22895   EVT VT = N->getValueType(0);
22896
22897   if (VT != MVT::v2i64 && VT != MVT::v4i32 && VT != MVT::v8i16 &&
22898       (!Subtarget->hasInt256() ||
22899        (VT != MVT::v4i64 && VT != MVT::v8i32 && VT != MVT::v16i16)))
22900     return SDValue();
22901
22902   SDValue Amt = N->getOperand(1);
22903   SDLoc DL(N);
22904   if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Amt))
22905     if (auto *AmtSplat = AmtBV->getConstantSplatNode()) {
22906       APInt ShiftAmt = AmtSplat->getAPIntValue();
22907       unsigned MaxAmount = VT.getVectorElementType().getSizeInBits();
22908
22909       // SSE2/AVX2 logical shifts always return a vector of 0s
22910       // if the shift amount is bigger than or equal to
22911       // the element size. The constant shift amount will be
22912       // encoded as a 8-bit immediate.
22913       if (ShiftAmt.trunc(8).uge(MaxAmount))
22914         return getZeroVector(VT, Subtarget, DAG, DL);
22915     }
22916
22917   return SDValue();
22918 }
22919
22920 /// PerformShiftCombine - Combine shifts.
22921 static SDValue PerformShiftCombine(SDNode* N, SelectionDAG &DAG,
22922                                    TargetLowering::DAGCombinerInfo &DCI,
22923                                    const X86Subtarget *Subtarget) {
22924   if (N->getOpcode() == ISD::SHL)
22925     if (SDValue V = PerformSHLCombine(N, DAG))
22926       return V;
22927
22928   // Try to fold this logical shift into a zero vector.
22929   if (N->getOpcode() != ISD::SRA)
22930     if (SDValue V = performShiftToAllZeros(N, DAG, Subtarget))
22931       return V;
22932
22933   return SDValue();
22934 }
22935
22936 // CMPEQCombine - Recognize the distinctive  (AND (setcc ...) (setcc ..))
22937 // where both setccs reference the same FP CMP, and rewrite for CMPEQSS
22938 // and friends.  Likewise for OR -> CMPNEQSS.
22939 static SDValue CMPEQCombine(SDNode *N, SelectionDAG &DAG,
22940                             TargetLowering::DAGCombinerInfo &DCI,
22941                             const X86Subtarget *Subtarget) {
22942   unsigned opcode;
22943
22944   // SSE1 supports CMP{eq|ne}SS, and SSE2 added CMP{eq|ne}SD, but
22945   // we're requiring SSE2 for both.
22946   if (Subtarget->hasSSE2() && isAndOrOfSetCCs(SDValue(N, 0U), opcode)) {
22947     SDValue N0 = N->getOperand(0);
22948     SDValue N1 = N->getOperand(1);
22949     SDValue CMP0 = N0->getOperand(1);
22950     SDValue CMP1 = N1->getOperand(1);
22951     SDLoc DL(N);
22952
22953     // The SETCCs should both refer to the same CMP.
22954     if (CMP0.getOpcode() != X86ISD::CMP || CMP0 != CMP1)
22955       return SDValue();
22956
22957     SDValue CMP00 = CMP0->getOperand(0);
22958     SDValue CMP01 = CMP0->getOperand(1);
22959     EVT     VT    = CMP00.getValueType();
22960
22961     if (VT == MVT::f32 || VT == MVT::f64) {
22962       bool ExpectingFlags = false;
22963       // Check for any users that want flags:
22964       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
22965            !ExpectingFlags && UI != UE; ++UI)
22966         switch (UI->getOpcode()) {
22967         default:
22968         case ISD::BR_CC:
22969         case ISD::BRCOND:
22970         case ISD::SELECT:
22971           ExpectingFlags = true;
22972           break;
22973         case ISD::CopyToReg:
22974         case ISD::SIGN_EXTEND:
22975         case ISD::ZERO_EXTEND:
22976         case ISD::ANY_EXTEND:
22977           break;
22978         }
22979
22980       if (!ExpectingFlags) {
22981         enum X86::CondCode cc0 = (enum X86::CondCode)N0.getConstantOperandVal(0);
22982         enum X86::CondCode cc1 = (enum X86::CondCode)N1.getConstantOperandVal(0);
22983
22984         if (cc1 == X86::COND_E || cc1 == X86::COND_NE) {
22985           X86::CondCode tmp = cc0;
22986           cc0 = cc1;
22987           cc1 = tmp;
22988         }
22989
22990         if ((cc0 == X86::COND_E  && cc1 == X86::COND_NP) ||
22991             (cc0 == X86::COND_NE && cc1 == X86::COND_P)) {
22992           // FIXME: need symbolic constants for these magic numbers.
22993           // See X86ATTInstPrinter.cpp:printSSECC().
22994           unsigned x86cc = (cc0 == X86::COND_E) ? 0 : 4;
22995           if (Subtarget->hasAVX512()) {
22996             SDValue FSetCC = DAG.getNode(X86ISD::FSETCC, DL, MVT::i1, CMP00,
22997                                          CMP01,
22998                                          DAG.getConstant(x86cc, DL, MVT::i8));
22999             if (N->getValueType(0) != MVT::i1)
23000               return DAG.getNode(ISD::ZERO_EXTEND, DL, N->getValueType(0),
23001                                  FSetCC);
23002             return FSetCC;
23003           }
23004           SDValue OnesOrZeroesF = DAG.getNode(X86ISD::FSETCC, DL,
23005                                               CMP00.getValueType(), CMP00, CMP01,
23006                                               DAG.getConstant(x86cc, DL,
23007                                                               MVT::i8));
23008
23009           bool is64BitFP = (CMP00.getValueType() == MVT::f64);
23010           MVT IntVT = is64BitFP ? MVT::i64 : MVT::i32;
23011
23012           if (is64BitFP && !Subtarget->is64Bit()) {
23013             // On a 32-bit target, we cannot bitcast the 64-bit float to a
23014             // 64-bit integer, since that's not a legal type. Since
23015             // OnesOrZeroesF is all ones of all zeroes, we don't need all the
23016             // bits, but can do this little dance to extract the lowest 32 bits
23017             // and work with those going forward.
23018             SDValue Vector64 = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f64,
23019                                            OnesOrZeroesF);
23020             SDValue Vector32 = DAG.getBitcast(MVT::v4f32, Vector64);
23021             OnesOrZeroesF = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::f32,
23022                                         Vector32, DAG.getIntPtrConstant(0, DL));
23023             IntVT = MVT::i32;
23024           }
23025
23026           SDValue OnesOrZeroesI = DAG.getBitcast(IntVT, OnesOrZeroesF);
23027           SDValue ANDed = DAG.getNode(ISD::AND, DL, IntVT, OnesOrZeroesI,
23028                                       DAG.getConstant(1, DL, IntVT));
23029           SDValue OneBitOfTruth = DAG.getNode(ISD::TRUNCATE, DL, MVT::i8,
23030                                               ANDed);
23031           return OneBitOfTruth;
23032         }
23033       }
23034     }
23035   }
23036   return SDValue();
23037 }
23038
23039 /// CanFoldXORWithAllOnes - Test whether the XOR operand is a AllOnes vector
23040 /// so it can be folded inside ANDNP.
23041 static bool CanFoldXORWithAllOnes(const SDNode *N) {
23042   EVT VT = N->getValueType(0);
23043
23044   // Match direct AllOnes for 128 and 256-bit vectors
23045   if (ISD::isBuildVectorAllOnes(N))
23046     return true;
23047
23048   // Look through a bit convert.
23049   if (N->getOpcode() == ISD::BITCAST)
23050     N = N->getOperand(0).getNode();
23051
23052   // Sometimes the operand may come from a insert_subvector building a 256-bit
23053   // allones vector
23054   if (VT.is256BitVector() &&
23055       N->getOpcode() == ISD::INSERT_SUBVECTOR) {
23056     SDValue V1 = N->getOperand(0);
23057     SDValue V2 = N->getOperand(1);
23058
23059     if (V1.getOpcode() == ISD::INSERT_SUBVECTOR &&
23060         V1.getOperand(0).getOpcode() == ISD::UNDEF &&
23061         ISD::isBuildVectorAllOnes(V1.getOperand(1).getNode()) &&
23062         ISD::isBuildVectorAllOnes(V2.getNode()))
23063       return true;
23064   }
23065
23066   return false;
23067 }
23068
23069 // On AVX/AVX2 the type v8i1 is legalized to v8i16, which is an XMM sized
23070 // register. In most cases we actually compare or select YMM-sized registers
23071 // and mixing the two types creates horrible code. This method optimizes
23072 // some of the transition sequences.
23073 static SDValue WidenMaskArithmetic(SDNode *N, SelectionDAG &DAG,
23074                                  TargetLowering::DAGCombinerInfo &DCI,
23075                                  const X86Subtarget *Subtarget) {
23076   EVT VT = N->getValueType(0);
23077   if (!VT.is256BitVector())
23078     return SDValue();
23079
23080   assert((N->getOpcode() == ISD::ANY_EXTEND ||
23081           N->getOpcode() == ISD::ZERO_EXTEND ||
23082           N->getOpcode() == ISD::SIGN_EXTEND) && "Invalid Node");
23083
23084   SDValue Narrow = N->getOperand(0);
23085   EVT NarrowVT = Narrow->getValueType(0);
23086   if (!NarrowVT.is128BitVector())
23087     return SDValue();
23088
23089   if (Narrow->getOpcode() != ISD::XOR &&
23090       Narrow->getOpcode() != ISD::AND &&
23091       Narrow->getOpcode() != ISD::OR)
23092     return SDValue();
23093
23094   SDValue N0  = Narrow->getOperand(0);
23095   SDValue N1  = Narrow->getOperand(1);
23096   SDLoc DL(Narrow);
23097
23098   // The Left side has to be a trunc.
23099   if (N0.getOpcode() != ISD::TRUNCATE)
23100     return SDValue();
23101
23102   // The type of the truncated inputs.
23103   EVT WideVT = N0->getOperand(0)->getValueType(0);
23104   if (WideVT != VT)
23105     return SDValue();
23106
23107   // The right side has to be a 'trunc' or a constant vector.
23108   bool RHSTrunc = N1.getOpcode() == ISD::TRUNCATE;
23109   ConstantSDNode *RHSConstSplat = nullptr;
23110   if (auto *RHSBV = dyn_cast<BuildVectorSDNode>(N1))
23111     RHSConstSplat = RHSBV->getConstantSplatNode();
23112   if (!RHSTrunc && !RHSConstSplat)
23113     return SDValue();
23114
23115   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23116
23117   if (!TLI.isOperationLegalOrPromote(Narrow->getOpcode(), WideVT))
23118     return SDValue();
23119
23120   // Set N0 and N1 to hold the inputs to the new wide operation.
23121   N0 = N0->getOperand(0);
23122   if (RHSConstSplat) {
23123     N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT.getScalarType(),
23124                      SDValue(RHSConstSplat, 0));
23125     SmallVector<SDValue, 8> C(WideVT.getVectorNumElements(), N1);
23126     N1 = DAG.getNode(ISD::BUILD_VECTOR, DL, WideVT, C);
23127   } else if (RHSTrunc) {
23128     N1 = N1->getOperand(0);
23129   }
23130
23131   // Generate the wide operation.
23132   SDValue Op = DAG.getNode(Narrow->getOpcode(), DL, WideVT, N0, N1);
23133   unsigned Opcode = N->getOpcode();
23134   switch (Opcode) {
23135   case ISD::ANY_EXTEND:
23136     return Op;
23137   case ISD::ZERO_EXTEND: {
23138     unsigned InBits = NarrowVT.getScalarType().getSizeInBits();
23139     APInt Mask = APInt::getAllOnesValue(InBits);
23140     Mask = Mask.zext(VT.getScalarType().getSizeInBits());
23141     return DAG.getNode(ISD::AND, DL, VT,
23142                        Op, DAG.getConstant(Mask, DL, VT));
23143   }
23144   case ISD::SIGN_EXTEND:
23145     return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT,
23146                        Op, DAG.getValueType(NarrowVT));
23147   default:
23148     llvm_unreachable("Unexpected opcode");
23149   }
23150 }
23151
23152 static SDValue VectorZextCombine(SDNode *N, SelectionDAG &DAG,
23153                                  TargetLowering::DAGCombinerInfo &DCI,
23154                                  const X86Subtarget *Subtarget) {
23155   SDValue N0 = N->getOperand(0);
23156   SDValue N1 = N->getOperand(1);
23157   SDLoc DL(N);
23158
23159   // A vector zext_in_reg may be represented as a shuffle,
23160   // feeding into a bitcast (this represents anyext) feeding into
23161   // an and with a mask.
23162   // We'd like to try to combine that into a shuffle with zero
23163   // plus a bitcast, removing the and.
23164   if (N0.getOpcode() != ISD::BITCAST ||
23165       N0.getOperand(0).getOpcode() != ISD::VECTOR_SHUFFLE)
23166     return SDValue();
23167
23168   // The other side of the AND should be a splat of 2^C, where C
23169   // is the number of bits in the source type.
23170   if (N1.getOpcode() == ISD::BITCAST)
23171     N1 = N1.getOperand(0);
23172   if (N1.getOpcode() != ISD::BUILD_VECTOR)
23173     return SDValue();
23174   BuildVectorSDNode *Vector = cast<BuildVectorSDNode>(N1);
23175
23176   ShuffleVectorSDNode *Shuffle = cast<ShuffleVectorSDNode>(N0.getOperand(0));
23177   EVT SrcType = Shuffle->getValueType(0);
23178
23179   // We expect a single-source shuffle
23180   if (Shuffle->getOperand(1)->getOpcode() != ISD::UNDEF)
23181     return SDValue();
23182
23183   unsigned SrcSize = SrcType.getScalarSizeInBits();
23184
23185   APInt SplatValue, SplatUndef;
23186   unsigned SplatBitSize;
23187   bool HasAnyUndefs;
23188   if (!Vector->isConstantSplat(SplatValue, SplatUndef,
23189                                 SplatBitSize, HasAnyUndefs))
23190     return SDValue();
23191
23192   unsigned ResSize = N1.getValueType().getScalarSizeInBits();
23193   // Make sure the splat matches the mask we expect
23194   if (SplatBitSize > ResSize ||
23195       (SplatValue + 1).exactLogBase2() != (int)SrcSize)
23196     return SDValue();
23197
23198   // Make sure the input and output size make sense
23199   if (SrcSize >= ResSize || ResSize % SrcSize)
23200     return SDValue();
23201
23202   // We expect a shuffle of the form <0, u, u, u, 1, u, u, u...>
23203   // The number of u's between each two values depends on the ratio between
23204   // the source and dest type.
23205   unsigned ZextRatio = ResSize / SrcSize;
23206   bool IsZext = true;
23207   for (unsigned i = 0; i < SrcType.getVectorNumElements(); ++i) {
23208     if (i % ZextRatio) {
23209       if (Shuffle->getMaskElt(i) > 0) {
23210         // Expected undef
23211         IsZext = false;
23212         break;
23213       }
23214     } else {
23215       if (Shuffle->getMaskElt(i) != (int)(i / ZextRatio)) {
23216         // Expected element number
23217         IsZext = false;
23218         break;
23219       }
23220     }
23221   }
23222
23223   if (!IsZext)
23224     return SDValue();
23225
23226   // Ok, perform the transformation - replace the shuffle with
23227   // a shuffle of the form <0, k, k, k, 1, k, k, k> with zero
23228   // (instead of undef) where the k elements come from the zero vector.
23229   SmallVector<int, 8> Mask;
23230   unsigned NumElems = SrcType.getVectorNumElements();
23231   for (unsigned i = 0; i < NumElems; ++i)
23232     if (i % ZextRatio)
23233       Mask.push_back(NumElems);
23234     else
23235       Mask.push_back(i / ZextRatio);
23236
23237   SDValue NewShuffle = DAG.getVectorShuffle(Shuffle->getValueType(0), DL,
23238     Shuffle->getOperand(0), DAG.getConstant(0, DL, SrcType), Mask);
23239   return DAG.getBitcast(N0.getValueType(), NewShuffle);
23240 }
23241
23242 static SDValue PerformAndCombine(SDNode *N, SelectionDAG &DAG,
23243                                  TargetLowering::DAGCombinerInfo &DCI,
23244                                  const X86Subtarget *Subtarget) {
23245   if (DCI.isBeforeLegalizeOps())
23246     return SDValue();
23247
23248   if (SDValue Zext = VectorZextCombine(N, DAG, DCI, Subtarget))
23249     return Zext;
23250
23251   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23252     return R;
23253
23254   EVT VT = N->getValueType(0);
23255   SDValue N0 = N->getOperand(0);
23256   SDValue N1 = N->getOperand(1);
23257   SDLoc DL(N);
23258
23259   // Create BEXTR instructions
23260   // BEXTR is ((X >> imm) & (2**size-1))
23261   if (VT == MVT::i32 || VT == MVT::i64) {
23262     // Check for BEXTR.
23263     if ((Subtarget->hasBMI() || Subtarget->hasTBM()) &&
23264         (N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::SRL)) {
23265       ConstantSDNode *MaskNode = dyn_cast<ConstantSDNode>(N1);
23266       ConstantSDNode *ShiftNode = dyn_cast<ConstantSDNode>(N0.getOperand(1));
23267       if (MaskNode && ShiftNode) {
23268         uint64_t Mask = MaskNode->getZExtValue();
23269         uint64_t Shift = ShiftNode->getZExtValue();
23270         if (isMask_64(Mask)) {
23271           uint64_t MaskSize = countPopulation(Mask);
23272           if (Shift + MaskSize <= VT.getSizeInBits())
23273             return DAG.getNode(X86ISD::BEXTR, DL, VT, N0.getOperand(0),
23274                                DAG.getConstant(Shift | (MaskSize << 8), DL,
23275                                                VT));
23276         }
23277       }
23278     } // BEXTR
23279
23280     return SDValue();
23281   }
23282
23283   // Want to form ANDNP nodes:
23284   // 1) In the hopes of then easily combining them with OR and AND nodes
23285   //    to form PBLEND/PSIGN.
23286   // 2) To match ANDN packed intrinsics
23287   if (VT != MVT::v2i64 && VT != MVT::v4i64)
23288     return SDValue();
23289
23290   // Check LHS for vnot
23291   if (N0.getOpcode() == ISD::XOR &&
23292       //ISD::isBuildVectorAllOnes(N0.getOperand(1).getNode()))
23293       CanFoldXORWithAllOnes(N0.getOperand(1).getNode()))
23294     return DAG.getNode(X86ISD::ANDNP, DL, VT, N0.getOperand(0), N1);
23295
23296   // Check RHS for vnot
23297   if (N1.getOpcode() == ISD::XOR &&
23298       //ISD::isBuildVectorAllOnes(N1.getOperand(1).getNode()))
23299       CanFoldXORWithAllOnes(N1.getOperand(1).getNode()))
23300     return DAG.getNode(X86ISD::ANDNP, DL, VT, N1.getOperand(0), N0);
23301
23302   return SDValue();
23303 }
23304
23305 static SDValue PerformOrCombine(SDNode *N, SelectionDAG &DAG,
23306                                 TargetLowering::DAGCombinerInfo &DCI,
23307                                 const X86Subtarget *Subtarget) {
23308   if (DCI.isBeforeLegalizeOps())
23309     return SDValue();
23310
23311   if (SDValue R = CMPEQCombine(N, DAG, DCI, Subtarget))
23312     return R;
23313
23314   SDValue N0 = N->getOperand(0);
23315   SDValue N1 = N->getOperand(1);
23316   EVT VT = N->getValueType(0);
23317
23318   // look for psign/blend
23319   if (VT == MVT::v2i64 || VT == MVT::v4i64) {
23320     if (!Subtarget->hasSSSE3() ||
23321         (VT == MVT::v4i64 && !Subtarget->hasInt256()))
23322       return SDValue();
23323
23324     // Canonicalize pandn to RHS
23325     if (N0.getOpcode() == X86ISD::ANDNP)
23326       std::swap(N0, N1);
23327     // or (and (m, y), (pandn m, x))
23328     if (N0.getOpcode() == ISD::AND && N1.getOpcode() == X86ISD::ANDNP) {
23329       SDValue Mask = N1.getOperand(0);
23330       SDValue X    = N1.getOperand(1);
23331       SDValue Y;
23332       if (N0.getOperand(0) == Mask)
23333         Y = N0.getOperand(1);
23334       if (N0.getOperand(1) == Mask)
23335         Y = N0.getOperand(0);
23336
23337       // Check to see if the mask appeared in both the AND and ANDNP and
23338       if (!Y.getNode())
23339         return SDValue();
23340
23341       // Validate that X, Y, and Mask are BIT_CONVERTS, and see through them.
23342       // Look through mask bitcast.
23343       if (Mask.getOpcode() == ISD::BITCAST)
23344         Mask = Mask.getOperand(0);
23345       if (X.getOpcode() == ISD::BITCAST)
23346         X = X.getOperand(0);
23347       if (Y.getOpcode() == ISD::BITCAST)
23348         Y = Y.getOperand(0);
23349
23350       EVT MaskVT = Mask.getValueType();
23351
23352       // Validate that the Mask operand is a vector sra node.
23353       // FIXME: what to do for bytes, since there is a psignb/pblendvb, but
23354       // there is no psrai.b
23355       unsigned EltBits = MaskVT.getVectorElementType().getSizeInBits();
23356       unsigned SraAmt = ~0;
23357       if (Mask.getOpcode() == ISD::SRA) {
23358         if (auto *AmtBV = dyn_cast<BuildVectorSDNode>(Mask.getOperand(1)))
23359           if (auto *AmtConst = AmtBV->getConstantSplatNode())
23360             SraAmt = AmtConst->getZExtValue();
23361       } else if (Mask.getOpcode() == X86ISD::VSRAI) {
23362         SDValue SraC = Mask.getOperand(1);
23363         SraAmt  = cast<ConstantSDNode>(SraC)->getZExtValue();
23364       }
23365       if ((SraAmt + 1) != EltBits)
23366         return SDValue();
23367
23368       SDLoc DL(N);
23369
23370       // Now we know we at least have a plendvb with the mask val.  See if
23371       // we can form a psignb/w/d.
23372       // psign = x.type == y.type == mask.type && y = sub(0, x);
23373       if (Y.getOpcode() == ISD::SUB && Y.getOperand(1) == X &&
23374           ISD::isBuildVectorAllZeros(Y.getOperand(0).getNode()) &&
23375           X.getValueType() == MaskVT && Y.getValueType() == MaskVT) {
23376         assert((EltBits == 8 || EltBits == 16 || EltBits == 32) &&
23377                "Unsupported VT for PSIGN");
23378         Mask = DAG.getNode(X86ISD::PSIGN, DL, MaskVT, X, Mask.getOperand(0));
23379         return DAG.getBitcast(VT, Mask);
23380       }
23381       // PBLENDVB only available on SSE 4.1
23382       if (!Subtarget->hasSSE41())
23383         return SDValue();
23384
23385       EVT BlendVT = (VT == MVT::v4i64) ? MVT::v32i8 : MVT::v16i8;
23386
23387       X = DAG.getBitcast(BlendVT, X);
23388       Y = DAG.getBitcast(BlendVT, Y);
23389       Mask = DAG.getBitcast(BlendVT, Mask);
23390       Mask = DAG.getNode(ISD::VSELECT, DL, BlendVT, Mask, Y, X);
23391       return DAG.getBitcast(VT, Mask);
23392     }
23393   }
23394
23395   if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
23396     return SDValue();
23397
23398   // fold (or (x << c) | (y >> (64 - c))) ==> (shld64 x, y, c)
23399   MachineFunction &MF = DAG.getMachineFunction();
23400   bool OptForSize =
23401       MF.getFunction()->hasFnAttribute(Attribute::OptimizeForSize);
23402
23403   // SHLD/SHRD instructions have lower register pressure, but on some
23404   // platforms they have higher latency than the equivalent
23405   // series of shifts/or that would otherwise be generated.
23406   // Don't fold (or (x << c) | (y >> (64 - c))) if SHLD/SHRD instructions
23407   // have higher latencies and we are not optimizing for size.
23408   if (!OptForSize && Subtarget->isSHLDSlow())
23409     return SDValue();
23410
23411   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
23412     std::swap(N0, N1);
23413   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
23414     return SDValue();
23415   if (!N0.hasOneUse() || !N1.hasOneUse())
23416     return SDValue();
23417
23418   SDValue ShAmt0 = N0.getOperand(1);
23419   if (ShAmt0.getValueType() != MVT::i8)
23420     return SDValue();
23421   SDValue ShAmt1 = N1.getOperand(1);
23422   if (ShAmt1.getValueType() != MVT::i8)
23423     return SDValue();
23424   if (ShAmt0.getOpcode() == ISD::TRUNCATE)
23425     ShAmt0 = ShAmt0.getOperand(0);
23426   if (ShAmt1.getOpcode() == ISD::TRUNCATE)
23427     ShAmt1 = ShAmt1.getOperand(0);
23428
23429   SDLoc DL(N);
23430   unsigned Opc = X86ISD::SHLD;
23431   SDValue Op0 = N0.getOperand(0);
23432   SDValue Op1 = N1.getOperand(0);
23433   if (ShAmt0.getOpcode() == ISD::SUB) {
23434     Opc = X86ISD::SHRD;
23435     std::swap(Op0, Op1);
23436     std::swap(ShAmt0, ShAmt1);
23437   }
23438
23439   unsigned Bits = VT.getSizeInBits();
23440   if (ShAmt1.getOpcode() == ISD::SUB) {
23441     SDValue Sum = ShAmt1.getOperand(0);
23442     if (ConstantSDNode *SumC = dyn_cast<ConstantSDNode>(Sum)) {
23443       SDValue ShAmt1Op1 = ShAmt1.getOperand(1);
23444       if (ShAmt1Op1.getNode()->getOpcode() == ISD::TRUNCATE)
23445         ShAmt1Op1 = ShAmt1Op1.getOperand(0);
23446       if (SumC->getSExtValue() == Bits && ShAmt1Op1 == ShAmt0)
23447         return DAG.getNode(Opc, DL, VT,
23448                            Op0, Op1,
23449                            DAG.getNode(ISD::TRUNCATE, DL,
23450                                        MVT::i8, ShAmt0));
23451     }
23452   } else if (ConstantSDNode *ShAmt1C = dyn_cast<ConstantSDNode>(ShAmt1)) {
23453     ConstantSDNode *ShAmt0C = dyn_cast<ConstantSDNode>(ShAmt0);
23454     if (ShAmt0C &&
23455         ShAmt0C->getSExtValue() + ShAmt1C->getSExtValue() == Bits)
23456       return DAG.getNode(Opc, DL, VT,
23457                          N0.getOperand(0), N1.getOperand(0),
23458                          DAG.getNode(ISD::TRUNCATE, DL,
23459                                        MVT::i8, ShAmt0));
23460   }
23461
23462   return SDValue();
23463 }
23464
23465 // Generate NEG and CMOV for integer abs.
23466 static SDValue performIntegerAbsCombine(SDNode *N, SelectionDAG &DAG) {
23467   EVT VT = N->getValueType(0);
23468
23469   // Since X86 does not have CMOV for 8-bit integer, we don't convert
23470   // 8-bit integer abs to NEG and CMOV.
23471   if (VT.isInteger() && VT.getSizeInBits() == 8)
23472     return SDValue();
23473
23474   SDValue N0 = N->getOperand(0);
23475   SDValue N1 = N->getOperand(1);
23476   SDLoc DL(N);
23477
23478   // Check pattern of XOR(ADD(X,Y), Y) where Y is SRA(X, size(X)-1)
23479   // and change it to SUB and CMOV.
23480   if (VT.isInteger() && N->getOpcode() == ISD::XOR &&
23481       N0.getOpcode() == ISD::ADD &&
23482       N0.getOperand(1) == N1 &&
23483       N1.getOpcode() == ISD::SRA &&
23484       N1.getOperand(0) == N0.getOperand(0))
23485     if (ConstantSDNode *Y1C = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
23486       if (Y1C->getAPIntValue() == VT.getSizeInBits()-1) {
23487         // Generate SUB & CMOV.
23488         SDValue Neg = DAG.getNode(X86ISD::SUB, DL, DAG.getVTList(VT, MVT::i32),
23489                                   DAG.getConstant(0, DL, VT), N0.getOperand(0));
23490
23491         SDValue Ops[] = { N0.getOperand(0), Neg,
23492                           DAG.getConstant(X86::COND_GE, DL, MVT::i8),
23493                           SDValue(Neg.getNode(), 1) };
23494         return DAG.getNode(X86ISD::CMOV, DL, DAG.getVTList(VT, MVT::Glue), Ops);
23495       }
23496   return SDValue();
23497 }
23498
23499 // PerformXorCombine - Attempts to turn XOR nodes into BLSMSK nodes
23500 static SDValue PerformXorCombine(SDNode *N, SelectionDAG &DAG,
23501                                  TargetLowering::DAGCombinerInfo &DCI,
23502                                  const X86Subtarget *Subtarget) {
23503   if (DCI.isBeforeLegalizeOps())
23504     return SDValue();
23505
23506   if (Subtarget->hasCMov())
23507     if (SDValue RV = performIntegerAbsCombine(N, DAG))
23508       return RV;
23509
23510   return SDValue();
23511 }
23512
23513 /// PerformLOADCombine - Do target-specific dag combines on LOAD nodes.
23514 static SDValue PerformLOADCombine(SDNode *N, SelectionDAG &DAG,
23515                                   TargetLowering::DAGCombinerInfo &DCI,
23516                                   const X86Subtarget *Subtarget) {
23517   LoadSDNode *Ld = cast<LoadSDNode>(N);
23518   EVT RegVT = Ld->getValueType(0);
23519   EVT MemVT = Ld->getMemoryVT();
23520   SDLoc dl(Ld);
23521   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23522
23523   // For chips with slow 32-byte unaligned loads, break the 32-byte operation
23524   // into two 16-byte operations.
23525   ISD::LoadExtType Ext = Ld->getExtensionType();
23526   unsigned Alignment = Ld->getAlignment();
23527   bool IsAligned = Alignment == 0 || Alignment >= MemVT.getSizeInBits()/8;
23528   if (RegVT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23529       !DCI.isBeforeLegalizeOps() && !IsAligned && Ext == ISD::NON_EXTLOAD) {
23530     unsigned NumElems = RegVT.getVectorNumElements();
23531     if (NumElems < 2)
23532       return SDValue();
23533
23534     SDValue Ptr = Ld->getBasePtr();
23535     SDValue Increment = DAG.getConstant(16, dl, TLI.getPointerTy());
23536
23537     EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(),
23538                                   NumElems/2);
23539     SDValue Load1 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23540                                 Ld->getPointerInfo(), Ld->isVolatile(),
23541                                 Ld->isNonTemporal(), Ld->isInvariant(),
23542                                 Alignment);
23543     Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23544     SDValue Load2 = DAG.getLoad(HalfVT, dl, Ld->getChain(), Ptr,
23545                                 Ld->getPointerInfo(), Ld->isVolatile(),
23546                                 Ld->isNonTemporal(), Ld->isInvariant(),
23547                                 std::min(16U, Alignment));
23548     SDValue TF = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
23549                              Load1.getValue(1),
23550                              Load2.getValue(1));
23551
23552     SDValue NewVec = DAG.getUNDEF(RegVT);
23553     NewVec = Insert128BitVector(NewVec, Load1, 0, DAG, dl);
23554     NewVec = Insert128BitVector(NewVec, Load2, NumElems/2, DAG, dl);
23555     return DCI.CombineTo(N, NewVec, TF, true);
23556   }
23557
23558   return SDValue();
23559 }
23560
23561 /// PerformMLOADCombine - Resolve extending loads
23562 static SDValue PerformMLOADCombine(SDNode *N, SelectionDAG &DAG,
23563                                    TargetLowering::DAGCombinerInfo &DCI,
23564                                    const X86Subtarget *Subtarget) {
23565   MaskedLoadSDNode *Mld = cast<MaskedLoadSDNode>(N);
23566   if (Mld->getExtensionType() != ISD::SEXTLOAD)
23567     return SDValue();
23568
23569   EVT VT = Mld->getValueType(0);
23570   unsigned NumElems = VT.getVectorNumElements();
23571   EVT LdVT = Mld->getMemoryVT();
23572   SDLoc dl(Mld);
23573
23574   assert(LdVT != VT && "Cannot extend to the same type");
23575   unsigned ToSz = VT.getVectorElementType().getSizeInBits();
23576   unsigned FromSz = LdVT.getVectorElementType().getSizeInBits();
23577   // From, To sizes and ElemCount must be pow of two
23578   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23579     "Unexpected size for extending masked load");
23580
23581   unsigned SizeRatio  = ToSz / FromSz;
23582   assert(SizeRatio * NumElems * FromSz == VT.getSizeInBits());
23583
23584   // Create a type on which we perform the shuffle
23585   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23586           LdVT.getScalarType(), NumElems*SizeRatio);
23587   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23588
23589   // Convert Src0 value
23590   SDValue WideSrc0 = DAG.getBitcast(WideVecVT, Mld->getSrc0());
23591   if (Mld->getSrc0().getOpcode() != ISD::UNDEF) {
23592     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23593     for (unsigned i = 0; i != NumElems; ++i)
23594       ShuffleVec[i] = i * SizeRatio;
23595
23596     // Can't shuffle using an illegal type.
23597     assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23598             && "WideVecVT should be legal");
23599     WideSrc0 = DAG.getVectorShuffle(WideVecVT, dl, WideSrc0,
23600                                     DAG.getUNDEF(WideVecVT), &ShuffleVec[0]);
23601   }
23602   // Prepare the new mask
23603   SDValue NewMask;
23604   SDValue Mask = Mld->getMask();
23605   if (Mask.getValueType() == VT) {
23606     // Mask and original value have the same type
23607     NewMask = DAG.getBitcast(WideVecVT, Mask);
23608     SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23609     for (unsigned i = 0; i != NumElems; ++i)
23610       ShuffleVec[i] = i * SizeRatio;
23611     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23612       ShuffleVec[i] = NumElems*SizeRatio;
23613     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23614                                    DAG.getConstant(0, dl, WideVecVT),
23615                                    &ShuffleVec[0]);
23616   }
23617   else {
23618     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23619     unsigned WidenNumElts = NumElems*SizeRatio;
23620     unsigned MaskNumElts = VT.getVectorNumElements();
23621     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23622                                      WidenNumElts);
23623
23624     unsigned NumConcat = WidenNumElts / MaskNumElts;
23625     SmallVector<SDValue, 16> Ops(NumConcat);
23626     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23627     Ops[0] = Mask;
23628     for (unsigned i = 1; i != NumConcat; ++i)
23629       Ops[i] = ZeroVal;
23630
23631     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23632   }
23633
23634   SDValue WideLd = DAG.getMaskedLoad(WideVecVT, dl, Mld->getChain(),
23635                                      Mld->getBasePtr(), NewMask, WideSrc0,
23636                                      Mld->getMemoryVT(), Mld->getMemOperand(),
23637                                      ISD::NON_EXTLOAD);
23638   SDValue NewVec = DAG.getNode(X86ISD::VSEXT, dl, VT, WideLd);
23639   return DCI.CombineTo(N, NewVec, WideLd.getValue(1), true);
23640
23641 }
23642 /// PerformMSTORECombine - Resolve truncating stores
23643 static SDValue PerformMSTORECombine(SDNode *N, SelectionDAG &DAG,
23644                                     const X86Subtarget *Subtarget) {
23645   MaskedStoreSDNode *Mst = cast<MaskedStoreSDNode>(N);
23646   if (!Mst->isTruncatingStore())
23647     return SDValue();
23648
23649   EVT VT = Mst->getValue().getValueType();
23650   unsigned NumElems = VT.getVectorNumElements();
23651   EVT StVT = Mst->getMemoryVT();
23652   SDLoc dl(Mst);
23653
23654   assert(StVT != VT && "Cannot truncate to the same type");
23655   unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23656   unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23657
23658   // From, To sizes and ElemCount must be pow of two
23659   assert (isPowerOf2_32(NumElems * FromSz * ToSz) &&
23660     "Unexpected size for truncating masked store");
23661   // We are going to use the original vector elt for storing.
23662   // Accumulated smaller vector elements must be a multiple of the store size.
23663   assert (((NumElems * FromSz) % ToSz) == 0 &&
23664           "Unexpected ratio for truncating masked store");
23665
23666   unsigned SizeRatio  = FromSz / ToSz;
23667   assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23668
23669   // Create a type on which we perform the shuffle
23670   EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23671           StVT.getScalarType(), NumElems*SizeRatio);
23672
23673   assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23674
23675   SDValue WideVec = DAG.getBitcast(WideVecVT, Mst->getValue());
23676   SmallVector<int, 16> ShuffleVec(NumElems * SizeRatio, -1);
23677   for (unsigned i = 0; i != NumElems; ++i)
23678     ShuffleVec[i] = i * SizeRatio;
23679
23680   // Can't shuffle using an illegal type.
23681   assert (DAG.getTargetLoweringInfo().isTypeLegal(WideVecVT)
23682           && "WideVecVT should be legal");
23683
23684   SDValue TruncatedVal = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23685                                         DAG.getUNDEF(WideVecVT),
23686                                         &ShuffleVec[0]);
23687
23688   SDValue NewMask;
23689   SDValue Mask = Mst->getMask();
23690   if (Mask.getValueType() == VT) {
23691     // Mask and original value have the same type
23692     NewMask = DAG.getBitcast(WideVecVT, Mask);
23693     for (unsigned i = 0; i != NumElems; ++i)
23694       ShuffleVec[i] = i * SizeRatio;
23695     for (unsigned i = NumElems; i != NumElems*SizeRatio; ++i)
23696       ShuffleVec[i] = NumElems*SizeRatio;
23697     NewMask = DAG.getVectorShuffle(WideVecVT, dl, NewMask,
23698                                    DAG.getConstant(0, dl, WideVecVT),
23699                                    &ShuffleVec[0]);
23700   }
23701   else {
23702     assert(Mask.getValueType().getVectorElementType() == MVT::i1);
23703     unsigned WidenNumElts = NumElems*SizeRatio;
23704     unsigned MaskNumElts = VT.getVectorNumElements();
23705     EVT NewMaskVT = EVT::getVectorVT(*DAG.getContext(),  MVT::i1,
23706                                      WidenNumElts);
23707
23708     unsigned NumConcat = WidenNumElts / MaskNumElts;
23709     SmallVector<SDValue, 16> Ops(NumConcat);
23710     SDValue ZeroVal = DAG.getConstant(0, dl, Mask.getValueType());
23711     Ops[0] = Mask;
23712     for (unsigned i = 1; i != NumConcat; ++i)
23713       Ops[i] = ZeroVal;
23714
23715     NewMask = DAG.getNode(ISD::CONCAT_VECTORS, dl, NewMaskVT, Ops);
23716   }
23717
23718   return DAG.getMaskedStore(Mst->getChain(), dl, TruncatedVal, Mst->getBasePtr(),
23719                             NewMask, StVT, Mst->getMemOperand(), false);
23720 }
23721 /// PerformSTORECombine - Do target-specific dag combines on STORE nodes.
23722 static SDValue PerformSTORECombine(SDNode *N, SelectionDAG &DAG,
23723                                    const X86Subtarget *Subtarget) {
23724   StoreSDNode *St = cast<StoreSDNode>(N);
23725   EVT VT = St->getValue().getValueType();
23726   EVT StVT = St->getMemoryVT();
23727   SDLoc dl(St);
23728   SDValue StoredVal = St->getOperand(1);
23729   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23730
23731   // If we are saving a concatenation of two XMM registers and 32-byte stores
23732   // are slow, such as on Sandy Bridge, perform two 16-byte stores.
23733   unsigned Alignment = St->getAlignment();
23734   bool IsAligned = Alignment == 0 || Alignment >= VT.getSizeInBits()/8;
23735   if (VT.is256BitVector() && Subtarget->isUnalignedMem32Slow() &&
23736       StVT == VT && !IsAligned) {
23737     unsigned NumElems = VT.getVectorNumElements();
23738     if (NumElems < 2)
23739       return SDValue();
23740
23741     SDValue Value0 = Extract128BitVector(StoredVal, 0, DAG, dl);
23742     SDValue Value1 = Extract128BitVector(StoredVal, NumElems/2, DAG, dl);
23743
23744     SDValue Stride = DAG.getConstant(16, dl, TLI.getPointerTy());
23745     SDValue Ptr0 = St->getBasePtr();
23746     SDValue Ptr1 = DAG.getNode(ISD::ADD, dl, Ptr0.getValueType(), Ptr0, Stride);
23747
23748     SDValue Ch0 = DAG.getStore(St->getChain(), dl, Value0, Ptr0,
23749                                 St->getPointerInfo(), St->isVolatile(),
23750                                 St->isNonTemporal(), Alignment);
23751     SDValue Ch1 = DAG.getStore(St->getChain(), dl, Value1, Ptr1,
23752                                 St->getPointerInfo(), St->isVolatile(),
23753                                 St->isNonTemporal(),
23754                                 std::min(16U, Alignment));
23755     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Ch0, Ch1);
23756   }
23757
23758   // Optimize trunc store (of multiple scalars) to shuffle and store.
23759   // First, pack all of the elements in one place. Next, store to memory
23760   // in fewer chunks.
23761   if (St->isTruncatingStore() && VT.isVector()) {
23762     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
23763     unsigned NumElems = VT.getVectorNumElements();
23764     assert(StVT != VT && "Cannot truncate to the same type");
23765     unsigned FromSz = VT.getVectorElementType().getSizeInBits();
23766     unsigned ToSz = StVT.getVectorElementType().getSizeInBits();
23767
23768     // From, To sizes and ElemCount must be pow of two
23769     if (!isPowerOf2_32(NumElems * FromSz * ToSz)) return SDValue();
23770     // We are going to use the original vector elt for storing.
23771     // Accumulated smaller vector elements must be a multiple of the store size.
23772     if (0 != (NumElems * FromSz) % ToSz) return SDValue();
23773
23774     unsigned SizeRatio  = FromSz / ToSz;
23775
23776     assert(SizeRatio * NumElems * ToSz == VT.getSizeInBits());
23777
23778     // Create a type on which we perform the shuffle
23779     EVT WideVecVT = EVT::getVectorVT(*DAG.getContext(),
23780             StVT.getScalarType(), NumElems*SizeRatio);
23781
23782     assert(WideVecVT.getSizeInBits() == VT.getSizeInBits());
23783
23784     SDValue WideVec = DAG.getBitcast(WideVecVT, St->getValue());
23785     SmallVector<int, 8> ShuffleVec(NumElems * SizeRatio, -1);
23786     for (unsigned i = 0; i != NumElems; ++i)
23787       ShuffleVec[i] = i * SizeRatio;
23788
23789     // Can't shuffle using an illegal type.
23790     if (!TLI.isTypeLegal(WideVecVT))
23791       return SDValue();
23792
23793     SDValue Shuff = DAG.getVectorShuffle(WideVecVT, dl, WideVec,
23794                                          DAG.getUNDEF(WideVecVT),
23795                                          &ShuffleVec[0]);
23796     // At this point all of the data is stored at the bottom of the
23797     // register. We now need to save it to mem.
23798
23799     // Find the largest store unit
23800     MVT StoreType = MVT::i8;
23801     for (MVT Tp : MVT::integer_valuetypes()) {
23802       if (TLI.isTypeLegal(Tp) && Tp.getSizeInBits() <= NumElems * ToSz)
23803         StoreType = Tp;
23804     }
23805
23806     // On 32bit systems, we can't save 64bit integers. Try bitcasting to F64.
23807     if (TLI.isTypeLegal(MVT::f64) && StoreType.getSizeInBits() < 64 &&
23808         (64 <= NumElems * ToSz))
23809       StoreType = MVT::f64;
23810
23811     // Bitcast the original vector into a vector of store-size units
23812     EVT StoreVecVT = EVT::getVectorVT(*DAG.getContext(),
23813             StoreType, VT.getSizeInBits()/StoreType.getSizeInBits());
23814     assert(StoreVecVT.getSizeInBits() == VT.getSizeInBits());
23815     SDValue ShuffWide = DAG.getBitcast(StoreVecVT, Shuff);
23816     SmallVector<SDValue, 8> Chains;
23817     SDValue Increment = DAG.getConstant(StoreType.getSizeInBits()/8, dl,
23818                                         TLI.getPointerTy());
23819     SDValue Ptr = St->getBasePtr();
23820
23821     // Perform one or more big stores into memory.
23822     for (unsigned i=0, e=(ToSz*NumElems)/StoreType.getSizeInBits(); i!=e; ++i) {
23823       SDValue SubVec = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl,
23824                                    StoreType, ShuffWide,
23825                                    DAG.getIntPtrConstant(i, dl));
23826       SDValue Ch = DAG.getStore(St->getChain(), dl, SubVec, Ptr,
23827                                 St->getPointerInfo(), St->isVolatile(),
23828                                 St->isNonTemporal(), St->getAlignment());
23829       Ptr = DAG.getNode(ISD::ADD, dl, Ptr.getValueType(), Ptr, Increment);
23830       Chains.push_back(Ch);
23831     }
23832
23833     return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Chains);
23834   }
23835
23836   // Turn load->store of MMX types into GPR load/stores.  This avoids clobbering
23837   // the FP state in cases where an emms may be missing.
23838   // A preferable solution to the general problem is to figure out the right
23839   // places to insert EMMS.  This qualifies as a quick hack.
23840
23841   // Similarly, turn load->store of i64 into double load/stores in 32-bit mode.
23842   if (VT.getSizeInBits() != 64)
23843     return SDValue();
23844
23845   const Function *F = DAG.getMachineFunction().getFunction();
23846   bool NoImplicitFloatOps = F->hasFnAttribute(Attribute::NoImplicitFloat);
23847   bool F64IsLegal =
23848       !Subtarget->useSoftFloat() && !NoImplicitFloatOps && Subtarget->hasSSE2();
23849   if ((VT.isVector() ||
23850        (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit())) &&
23851       isa<LoadSDNode>(St->getValue()) &&
23852       !cast<LoadSDNode>(St->getValue())->isVolatile() &&
23853       St->getChain().hasOneUse() && !St->isVolatile()) {
23854     SDNode* LdVal = St->getValue().getNode();
23855     LoadSDNode *Ld = nullptr;
23856     int TokenFactorIndex = -1;
23857     SmallVector<SDValue, 8> Ops;
23858     SDNode* ChainVal = St->getChain().getNode();
23859     // Must be a store of a load.  We currently handle two cases:  the load
23860     // is a direct child, and it's under an intervening TokenFactor.  It is
23861     // possible to dig deeper under nested TokenFactors.
23862     if (ChainVal == LdVal)
23863       Ld = cast<LoadSDNode>(St->getChain());
23864     else if (St->getValue().hasOneUse() &&
23865              ChainVal->getOpcode() == ISD::TokenFactor) {
23866       for (unsigned i = 0, e = ChainVal->getNumOperands(); i != e; ++i) {
23867         if (ChainVal->getOperand(i).getNode() == LdVal) {
23868           TokenFactorIndex = i;
23869           Ld = cast<LoadSDNode>(St->getValue());
23870         } else
23871           Ops.push_back(ChainVal->getOperand(i));
23872       }
23873     }
23874
23875     if (!Ld || !ISD::isNormalLoad(Ld))
23876       return SDValue();
23877
23878     // If this is not the MMX case, i.e. we are just turning i64 load/store
23879     // into f64 load/store, avoid the transformation if there are multiple
23880     // uses of the loaded value.
23881     if (!VT.isVector() && !Ld->hasNUsesOfValue(1, 0))
23882       return SDValue();
23883
23884     SDLoc LdDL(Ld);
23885     SDLoc StDL(N);
23886     // If we are a 64-bit capable x86, lower to a single movq load/store pair.
23887     // Otherwise, if it's legal to use f64 SSE instructions, use f64 load/store
23888     // pair instead.
23889     if (Subtarget->is64Bit() || F64IsLegal) {
23890       EVT LdVT = Subtarget->is64Bit() ? MVT::i64 : MVT::f64;
23891       SDValue NewLd = DAG.getLoad(LdVT, LdDL, Ld->getChain(), Ld->getBasePtr(),
23892                                   Ld->getPointerInfo(), Ld->isVolatile(),
23893                                   Ld->isNonTemporal(), Ld->isInvariant(),
23894                                   Ld->getAlignment());
23895       SDValue NewChain = NewLd.getValue(1);
23896       if (TokenFactorIndex != -1) {
23897         Ops.push_back(NewChain);
23898         NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23899       }
23900       return DAG.getStore(NewChain, StDL, NewLd, St->getBasePtr(),
23901                           St->getPointerInfo(),
23902                           St->isVolatile(), St->isNonTemporal(),
23903                           St->getAlignment());
23904     }
23905
23906     // Otherwise, lower to two pairs of 32-bit loads / stores.
23907     SDValue LoAddr = Ld->getBasePtr();
23908     SDValue HiAddr = DAG.getNode(ISD::ADD, LdDL, MVT::i32, LoAddr,
23909                                  DAG.getConstant(4, LdDL, MVT::i32));
23910
23911     SDValue LoLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), LoAddr,
23912                                Ld->getPointerInfo(),
23913                                Ld->isVolatile(), Ld->isNonTemporal(),
23914                                Ld->isInvariant(), Ld->getAlignment());
23915     SDValue HiLd = DAG.getLoad(MVT::i32, LdDL, Ld->getChain(), HiAddr,
23916                                Ld->getPointerInfo().getWithOffset(4),
23917                                Ld->isVolatile(), Ld->isNonTemporal(),
23918                                Ld->isInvariant(),
23919                                MinAlign(Ld->getAlignment(), 4));
23920
23921     SDValue NewChain = LoLd.getValue(1);
23922     if (TokenFactorIndex != -1) {
23923       Ops.push_back(LoLd);
23924       Ops.push_back(HiLd);
23925       NewChain = DAG.getNode(ISD::TokenFactor, LdDL, MVT::Other, Ops);
23926     }
23927
23928     LoAddr = St->getBasePtr();
23929     HiAddr = DAG.getNode(ISD::ADD, StDL, MVT::i32, LoAddr,
23930                          DAG.getConstant(4, StDL, MVT::i32));
23931
23932     SDValue LoSt = DAG.getStore(NewChain, StDL, LoLd, LoAddr,
23933                                 St->getPointerInfo(),
23934                                 St->isVolatile(), St->isNonTemporal(),
23935                                 St->getAlignment());
23936     SDValue HiSt = DAG.getStore(NewChain, StDL, HiLd, HiAddr,
23937                                 St->getPointerInfo().getWithOffset(4),
23938                                 St->isVolatile(),
23939                                 St->isNonTemporal(),
23940                                 MinAlign(St->getAlignment(), 4));
23941     return DAG.getNode(ISD::TokenFactor, StDL, MVT::Other, LoSt, HiSt);
23942   }
23943
23944   // This is similar to the above case, but here we handle a scalar 64-bit
23945   // integer store that is extracted from a vector on a 32-bit target.
23946   // If we have SSE2, then we can treat it like a floating-point double
23947   // to get past legalization. The execution dependencies fixup pass will
23948   // choose the optimal machine instruction for the store if this really is
23949   // an integer or v2f32 rather than an f64.
23950   if (VT == MVT::i64 && F64IsLegal && !Subtarget->is64Bit() &&
23951       St->getOperand(1).getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
23952     SDValue OldExtract = St->getOperand(1);
23953     SDValue ExtOp0 = OldExtract.getOperand(0);
23954     unsigned VecSize = ExtOp0.getValueSizeInBits();
23955     EVT VecVT = EVT::getVectorVT(*DAG.getContext(), MVT::f64, VecSize / 64);
23956     SDValue BitCast = DAG.getBitcast(VecVT, ExtOp0);
23957     SDValue NewExtract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, MVT::f64,
23958                                      BitCast, OldExtract.getOperand(1));
23959     return DAG.getStore(St->getChain(), dl, NewExtract, St->getBasePtr(),
23960                         St->getPointerInfo(), St->isVolatile(),
23961                         St->isNonTemporal(), St->getAlignment());
23962   }
23963
23964   return SDValue();
23965 }
23966
23967 /// Return 'true' if this vector operation is "horizontal"
23968 /// and return the operands for the horizontal operation in LHS and RHS.  A
23969 /// horizontal operation performs the binary operation on successive elements
23970 /// of its first operand, then on successive elements of its second operand,
23971 /// returning the resulting values in a vector.  For example, if
23972 ///   A = < float a0, float a1, float a2, float a3 >
23973 /// and
23974 ///   B = < float b0, float b1, float b2, float b3 >
23975 /// then the result of doing a horizontal operation on A and B is
23976 ///   A horizontal-op B = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >.
23977 /// In short, LHS and RHS are inspected to see if LHS op RHS is of the form
23978 /// A horizontal-op B, for some already available A and B, and if so then LHS is
23979 /// set to A, RHS to B, and the routine returns 'true'.
23980 /// Note that the binary operation should have the property that if one of the
23981 /// operands is UNDEF then the result is UNDEF.
23982 static bool isHorizontalBinOp(SDValue &LHS, SDValue &RHS, bool IsCommutative) {
23983   // Look for the following pattern: if
23984   //   A = < float a0, float a1, float a2, float a3 >
23985   //   B = < float b0, float b1, float b2, float b3 >
23986   // and
23987   //   LHS = VECTOR_SHUFFLE A, B, <0, 2, 4, 6>
23988   //   RHS = VECTOR_SHUFFLE A, B, <1, 3, 5, 7>
23989   // then LHS op RHS = < a0 op a1, a2 op a3, b0 op b1, b2 op b3 >
23990   // which is A horizontal-op B.
23991
23992   // At least one of the operands should be a vector shuffle.
23993   if (LHS.getOpcode() != ISD::VECTOR_SHUFFLE &&
23994       RHS.getOpcode() != ISD::VECTOR_SHUFFLE)
23995     return false;
23996
23997   MVT VT = LHS.getSimpleValueType();
23998
23999   assert((VT.is128BitVector() || VT.is256BitVector()) &&
24000          "Unsupported vector type for horizontal add/sub");
24001
24002   // Handle 128 and 256-bit vector lengths. AVX defines horizontal add/sub to
24003   // operate independently on 128-bit lanes.
24004   unsigned NumElts = VT.getVectorNumElements();
24005   unsigned NumLanes = VT.getSizeInBits()/128;
24006   unsigned NumLaneElts = NumElts / NumLanes;
24007   assert((NumLaneElts % 2 == 0) &&
24008          "Vector type should have an even number of elements in each lane");
24009   unsigned HalfLaneElts = NumLaneElts/2;
24010
24011   // View LHS in the form
24012   //   LHS = VECTOR_SHUFFLE A, B, LMask
24013   // If LHS is not a shuffle then pretend it is the shuffle
24014   //   LHS = VECTOR_SHUFFLE LHS, undef, <0, 1, ..., N-1>
24015   // NOTE: in what follows a default initialized SDValue represents an UNDEF of
24016   // type VT.
24017   SDValue A, B;
24018   SmallVector<int, 16> LMask(NumElts);
24019   if (LHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24020     if (LHS.getOperand(0).getOpcode() != ISD::UNDEF)
24021       A = LHS.getOperand(0);
24022     if (LHS.getOperand(1).getOpcode() != ISD::UNDEF)
24023       B = LHS.getOperand(1);
24024     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(LHS.getNode())->getMask();
24025     std::copy(Mask.begin(), Mask.end(), LMask.begin());
24026   } else {
24027     if (LHS.getOpcode() != ISD::UNDEF)
24028       A = LHS;
24029     for (unsigned i = 0; i != NumElts; ++i)
24030       LMask[i] = i;
24031   }
24032
24033   // Likewise, view RHS in the form
24034   //   RHS = VECTOR_SHUFFLE C, D, RMask
24035   SDValue C, D;
24036   SmallVector<int, 16> RMask(NumElts);
24037   if (RHS.getOpcode() == ISD::VECTOR_SHUFFLE) {
24038     if (RHS.getOperand(0).getOpcode() != ISD::UNDEF)
24039       C = RHS.getOperand(0);
24040     if (RHS.getOperand(1).getOpcode() != ISD::UNDEF)
24041       D = RHS.getOperand(1);
24042     ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(RHS.getNode())->getMask();
24043     std::copy(Mask.begin(), Mask.end(), RMask.begin());
24044   } else {
24045     if (RHS.getOpcode() != ISD::UNDEF)
24046       C = RHS;
24047     for (unsigned i = 0; i != NumElts; ++i)
24048       RMask[i] = i;
24049   }
24050
24051   // Check that the shuffles are both shuffling the same vectors.
24052   if (!(A == C && B == D) && !(A == D && B == C))
24053     return false;
24054
24055   // If everything is UNDEF then bail out: it would be better to fold to UNDEF.
24056   if (!A.getNode() && !B.getNode())
24057     return false;
24058
24059   // If A and B occur in reverse order in RHS, then "swap" them (which means
24060   // rewriting the mask).
24061   if (A != C)
24062     ShuffleVectorSDNode::commuteMask(RMask);
24063
24064   // At this point LHS and RHS are equivalent to
24065   //   LHS = VECTOR_SHUFFLE A, B, LMask
24066   //   RHS = VECTOR_SHUFFLE A, B, RMask
24067   // Check that the masks correspond to performing a horizontal operation.
24068   for (unsigned l = 0; l != NumElts; l += NumLaneElts) {
24069     for (unsigned i = 0; i != NumLaneElts; ++i) {
24070       int LIdx = LMask[i+l], RIdx = RMask[i+l];
24071
24072       // Ignore any UNDEF components.
24073       if (LIdx < 0 || RIdx < 0 ||
24074           (!A.getNode() && (LIdx < (int)NumElts || RIdx < (int)NumElts)) ||
24075           (!B.getNode() && (LIdx >= (int)NumElts || RIdx >= (int)NumElts)))
24076         continue;
24077
24078       // Check that successive elements are being operated on.  If not, this is
24079       // not a horizontal operation.
24080       unsigned Src = (i/HalfLaneElts); // each lane is split between srcs
24081       int Index = 2*(i%HalfLaneElts) + NumElts*Src + l;
24082       if (!(LIdx == Index && RIdx == Index + 1) &&
24083           !(IsCommutative && LIdx == Index + 1 && RIdx == Index))
24084         return false;
24085     }
24086   }
24087
24088   LHS = A.getNode() ? A : B; // If A is 'UNDEF', use B for it.
24089   RHS = B.getNode() ? B : A; // If B is 'UNDEF', use A for it.
24090   return true;
24091 }
24092
24093 /// Do target-specific dag combines on floating point adds.
24094 static SDValue PerformFADDCombine(SDNode *N, SelectionDAG &DAG,
24095                                   const X86Subtarget *Subtarget) {
24096   EVT VT = N->getValueType(0);
24097   SDValue LHS = N->getOperand(0);
24098   SDValue RHS = N->getOperand(1);
24099
24100   // Try to synthesize horizontal adds from adds of shuffles.
24101   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24102        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24103       isHorizontalBinOp(LHS, RHS, true))
24104     return DAG.getNode(X86ISD::FHADD, SDLoc(N), VT, LHS, RHS);
24105   return SDValue();
24106 }
24107
24108 /// Do target-specific dag combines on floating point subs.
24109 static SDValue PerformFSUBCombine(SDNode *N, SelectionDAG &DAG,
24110                                   const X86Subtarget *Subtarget) {
24111   EVT VT = N->getValueType(0);
24112   SDValue LHS = N->getOperand(0);
24113   SDValue RHS = N->getOperand(1);
24114
24115   // Try to synthesize horizontal subs from subs of shuffles.
24116   if (((Subtarget->hasSSE3() && (VT == MVT::v4f32 || VT == MVT::v2f64)) ||
24117        (Subtarget->hasFp256() && (VT == MVT::v8f32 || VT == MVT::v4f64))) &&
24118       isHorizontalBinOp(LHS, RHS, false))
24119     return DAG.getNode(X86ISD::FHSUB, SDLoc(N), VT, LHS, RHS);
24120   return SDValue();
24121 }
24122
24123 /// Do target-specific dag combines on X86ISD::FOR and X86ISD::FXOR nodes.
24124 static SDValue PerformFORCombine(SDNode *N, SelectionDAG &DAG) {
24125   assert(N->getOpcode() == X86ISD::FOR || N->getOpcode() == X86ISD::FXOR);
24126
24127   // F[X]OR(0.0, x) -> x
24128   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24129     if (C->getValueAPF().isPosZero())
24130       return N->getOperand(1);
24131
24132   // F[X]OR(x, 0.0) -> x
24133   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24134     if (C->getValueAPF().isPosZero())
24135       return N->getOperand(0);
24136   return SDValue();
24137 }
24138
24139 /// Do target-specific dag combines on X86ISD::FMIN and X86ISD::FMAX nodes.
24140 static SDValue PerformFMinFMaxCombine(SDNode *N, SelectionDAG &DAG) {
24141   assert(N->getOpcode() == X86ISD::FMIN || N->getOpcode() == X86ISD::FMAX);
24142
24143   // Only perform optimizations if UnsafeMath is used.
24144   if (!DAG.getTarget().Options.UnsafeFPMath)
24145     return SDValue();
24146
24147   // If we run in unsafe-math mode, then convert the FMAX and FMIN nodes
24148   // into FMINC and FMAXC, which are Commutative operations.
24149   unsigned NewOp = 0;
24150   switch (N->getOpcode()) {
24151     default: llvm_unreachable("unknown opcode");
24152     case X86ISD::FMIN:  NewOp = X86ISD::FMINC; break;
24153     case X86ISD::FMAX:  NewOp = X86ISD::FMAXC; break;
24154   }
24155
24156   return DAG.getNode(NewOp, SDLoc(N), N->getValueType(0),
24157                      N->getOperand(0), N->getOperand(1));
24158 }
24159
24160 /// Do target-specific dag combines on X86ISD::FAND nodes.
24161 static SDValue PerformFANDCombine(SDNode *N, SelectionDAG &DAG) {
24162   // FAND(0.0, x) -> 0.0
24163   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24164     if (C->getValueAPF().isPosZero())
24165       return N->getOperand(0);
24166
24167   // FAND(x, 0.0) -> 0.0
24168   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24169     if (C->getValueAPF().isPosZero())
24170       return N->getOperand(1);
24171
24172   return SDValue();
24173 }
24174
24175 /// Do target-specific dag combines on X86ISD::FANDN nodes
24176 static SDValue PerformFANDNCombine(SDNode *N, SelectionDAG &DAG) {
24177   // FANDN(0.0, x) -> x
24178   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(0)))
24179     if (C->getValueAPF().isPosZero())
24180       return N->getOperand(1);
24181
24182   // FANDN(x, 0.0) -> 0.0
24183   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(N->getOperand(1)))
24184     if (C->getValueAPF().isPosZero())
24185       return N->getOperand(1);
24186
24187   return SDValue();
24188 }
24189
24190 static SDValue PerformBTCombine(SDNode *N,
24191                                 SelectionDAG &DAG,
24192                                 TargetLowering::DAGCombinerInfo &DCI) {
24193   // BT ignores high bits in the bit index operand.
24194   SDValue Op1 = N->getOperand(1);
24195   if (Op1.hasOneUse()) {
24196     unsigned BitWidth = Op1.getValueSizeInBits();
24197     APInt DemandedMask = APInt::getLowBitsSet(BitWidth, Log2_32(BitWidth));
24198     APInt KnownZero, KnownOne;
24199     TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
24200                                           !DCI.isBeforeLegalizeOps());
24201     const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24202     if (TLO.ShrinkDemandedConstant(Op1, DemandedMask) ||
24203         TLI.SimplifyDemandedBits(Op1, DemandedMask, KnownZero, KnownOne, TLO))
24204       DCI.CommitTargetLoweringOpt(TLO);
24205   }
24206   return SDValue();
24207 }
24208
24209 static SDValue PerformVZEXT_MOVLCombine(SDNode *N, SelectionDAG &DAG) {
24210   SDValue Op = N->getOperand(0);
24211   if (Op.getOpcode() == ISD::BITCAST)
24212     Op = Op.getOperand(0);
24213   EVT VT = N->getValueType(0), OpVT = Op.getValueType();
24214   if (Op.getOpcode() == X86ISD::VZEXT_LOAD &&
24215       VT.getVectorElementType().getSizeInBits() ==
24216       OpVT.getVectorElementType().getSizeInBits()) {
24217     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Op);
24218   }
24219   return SDValue();
24220 }
24221
24222 static SDValue PerformSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
24223                                                const X86Subtarget *Subtarget) {
24224   EVT VT = N->getValueType(0);
24225   if (!VT.isVector())
24226     return SDValue();
24227
24228   SDValue N0 = N->getOperand(0);
24229   SDValue N1 = N->getOperand(1);
24230   EVT ExtraVT = cast<VTSDNode>(N1)->getVT();
24231   SDLoc dl(N);
24232
24233   // The SIGN_EXTEND_INREG to v4i64 is expensive operation on the
24234   // both SSE and AVX2 since there is no sign-extended shift right
24235   // operation on a vector with 64-bit elements.
24236   //(sext_in_reg (v4i64 anyext (v4i32 x )), ExtraVT) ->
24237   // (v4i64 sext (v4i32 sext_in_reg (v4i32 x , ExtraVT)))
24238   if (VT == MVT::v4i64 && (N0.getOpcode() == ISD::ANY_EXTEND ||
24239       N0.getOpcode() == ISD::SIGN_EXTEND)) {
24240     SDValue N00 = N0.getOperand(0);
24241
24242     // EXTLOAD has a better solution on AVX2,
24243     // it may be replaced with X86ISD::VSEXT node.
24244     if (N00.getOpcode() == ISD::LOAD && Subtarget->hasInt256())
24245       if (!ISD::isNormalLoad(N00.getNode()))
24246         return SDValue();
24247
24248     if (N00.getValueType() == MVT::v4i32 && ExtraVT.getSizeInBits() < 128) {
24249         SDValue Tmp = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::v4i32,
24250                                   N00, N1);
24251       return DAG.getNode(ISD::SIGN_EXTEND, dl, MVT::v4i64, Tmp);
24252     }
24253   }
24254   return SDValue();
24255 }
24256
24257 static SDValue PerformSExtCombine(SDNode *N, SelectionDAG &DAG,
24258                                   TargetLowering::DAGCombinerInfo &DCI,
24259                                   const X86Subtarget *Subtarget) {
24260   SDValue N0 = N->getOperand(0);
24261   EVT VT = N->getValueType(0);
24262   EVT SVT = VT.getScalarType();
24263   EVT InVT = N0.getValueType();
24264   EVT InSVT = InVT.getScalarType();
24265   SDLoc DL(N);
24266
24267   // (i8,i32 sext (sdivrem (i8 x, i8 y)) ->
24268   // (i8,i32 (sdivrem_sext_hreg (i8 x, i8 y)
24269   // This exposes the sext to the sdivrem lowering, so that it directly extends
24270   // from AH (which we otherwise need to do contortions to access).
24271   if (N0.getOpcode() == ISD::SDIVREM && N0.getResNo() == 1 &&
24272       InVT == MVT::i8 && VT == MVT::i32) {
24273     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24274     SDValue R = DAG.getNode(X86ISD::SDIVREM8_SEXT_HREG, DL, NodeTys,
24275                             N0.getOperand(0), N0.getOperand(1));
24276     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24277     return R.getValue(1);
24278   }
24279
24280   if (!DCI.isBeforeLegalizeOps()) {
24281     if (InVT == MVT::i1) {
24282       SDValue Zero = DAG.getConstant(0, DL, VT);
24283       SDValue AllOnes =
24284         DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), DL, VT);
24285       return DAG.getNode(ISD::SELECT, DL, VT, N0, AllOnes, Zero);
24286     }
24287     return SDValue();
24288   }
24289
24290   if (VT.isVector() && Subtarget->hasSSE2()) {
24291     auto ExtendVecSize = [&DAG](SDLoc DL, SDValue N, unsigned Size) {
24292       EVT InVT = N.getValueType();
24293       EVT OutVT = EVT::getVectorVT(*DAG.getContext(), InVT.getScalarType(),
24294                                    Size / InVT.getScalarSizeInBits());
24295       SmallVector<SDValue, 8> Opnds(Size / InVT.getSizeInBits(),
24296                                     DAG.getUNDEF(InVT));
24297       Opnds[0] = N;
24298       return DAG.getNode(ISD::CONCAT_VECTORS, DL, OutVT, Opnds);
24299     };
24300
24301     // If target-size is less than 128-bits, extend to a type that would extend
24302     // to 128 bits, extend that and extract the original target vector.
24303     if (VT.getSizeInBits() < 128 && !(128 % VT.getSizeInBits()) &&
24304         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24305         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24306       unsigned Scale = 128 / VT.getSizeInBits();
24307       EVT ExVT =
24308           EVT::getVectorVT(*DAG.getContext(), SVT, 128 / SVT.getSizeInBits());
24309       SDValue Ex = ExtendVecSize(DL, N0, Scale * InVT.getSizeInBits());
24310       SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, ExVT, Ex);
24311       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, SExt,
24312                          DAG.getIntPtrConstant(0, DL));
24313     }
24314
24315     // If target-size is 128-bits, then convert to ISD::SIGN_EXTEND_VECTOR_INREG
24316     // which ensures lowering to X86ISD::VSEXT (pmovsx*).
24317     if (VT.getSizeInBits() == 128 &&
24318         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24319         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24320       SDValue ExOp = ExtendVecSize(DL, N0, 128);
24321       return DAG.getSignExtendVectorInReg(ExOp, DL, VT);
24322     }
24323
24324     // On pre-AVX2 targets, split into 128-bit nodes of
24325     // ISD::SIGN_EXTEND_VECTOR_INREG.
24326     if (!Subtarget->hasInt256() && !(VT.getSizeInBits() % 128) &&
24327         (SVT == MVT::i64 || SVT == MVT::i32 || SVT == MVT::i16) &&
24328         (InSVT == MVT::i32 || InSVT == MVT::i16 || InSVT == MVT::i8)) {
24329       unsigned NumVecs = VT.getSizeInBits() / 128;
24330       unsigned NumSubElts = 128 / SVT.getSizeInBits();
24331       EVT SubVT = EVT::getVectorVT(*DAG.getContext(), SVT, NumSubElts);
24332       EVT InSubVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumSubElts);
24333
24334       SmallVector<SDValue, 8> Opnds;
24335       for (unsigned i = 0, Offset = 0; i != NumVecs;
24336            ++i, Offset += NumSubElts) {
24337         SDValue SrcVec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InSubVT, N0,
24338                                      DAG.getIntPtrConstant(Offset, DL));
24339         SrcVec = ExtendVecSize(DL, SrcVec, 128);
24340         SrcVec = DAG.getSignExtendVectorInReg(SrcVec, DL, SubVT);
24341         Opnds.push_back(SrcVec);
24342       }
24343       return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Opnds);
24344     }
24345   }
24346
24347   if (!Subtarget->hasFp256())
24348     return SDValue();
24349
24350   if (VT.isVector() && VT.getSizeInBits() == 256)
24351     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24352       return R;
24353
24354   return SDValue();
24355 }
24356
24357 static SDValue PerformFMACombine(SDNode *N, SelectionDAG &DAG,
24358                                  const X86Subtarget* Subtarget) {
24359   SDLoc dl(N);
24360   EVT VT = N->getValueType(0);
24361
24362   // Let legalize expand this if it isn't a legal type yet.
24363   if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
24364     return SDValue();
24365
24366   EVT ScalarVT = VT.getScalarType();
24367   if ((ScalarVT != MVT::f32 && ScalarVT != MVT::f64) ||
24368       (!Subtarget->hasFMA() && !Subtarget->hasFMA4() &&
24369        !Subtarget->hasAVX512()))
24370     return SDValue();
24371
24372   SDValue A = N->getOperand(0);
24373   SDValue B = N->getOperand(1);
24374   SDValue C = N->getOperand(2);
24375
24376   bool NegA = (A.getOpcode() == ISD::FNEG);
24377   bool NegB = (B.getOpcode() == ISD::FNEG);
24378   bool NegC = (C.getOpcode() == ISD::FNEG);
24379
24380   // Negative multiplication when NegA xor NegB
24381   bool NegMul = (NegA != NegB);
24382   if (NegA)
24383     A = A.getOperand(0);
24384   if (NegB)
24385     B = B.getOperand(0);
24386   if (NegC)
24387     C = C.getOperand(0);
24388
24389   unsigned Opcode;
24390   if (!NegMul)
24391     Opcode = (!NegC) ? X86ISD::FMADD : X86ISD::FMSUB;
24392   else
24393     Opcode = (!NegC) ? X86ISD::FNMADD : X86ISD::FNMSUB;
24394
24395   return DAG.getNode(Opcode, dl, VT, A, B, C);
24396 }
24397
24398 static SDValue PerformZExtCombine(SDNode *N, SelectionDAG &DAG,
24399                                   TargetLowering::DAGCombinerInfo &DCI,
24400                                   const X86Subtarget *Subtarget) {
24401   // (i32 zext (and (i8  x86isd::setcc_carry), 1)) ->
24402   //           (and (i32 x86isd::setcc_carry), 1)
24403   // This eliminates the zext. This transformation is necessary because
24404   // ISD::SETCC is always legalized to i8.
24405   SDLoc dl(N);
24406   SDValue N0 = N->getOperand(0);
24407   EVT VT = N->getValueType(0);
24408
24409   if (N0.getOpcode() == ISD::AND &&
24410       N0.hasOneUse() &&
24411       N0.getOperand(0).hasOneUse()) {
24412     SDValue N00 = N0.getOperand(0);
24413     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24414       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
24415       if (!C || C->getZExtValue() != 1)
24416         return SDValue();
24417       return DAG.getNode(ISD::AND, dl, VT,
24418                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24419                                      N00.getOperand(0), N00.getOperand(1)),
24420                          DAG.getConstant(1, dl, VT));
24421     }
24422   }
24423
24424   if (N0.getOpcode() == ISD::TRUNCATE &&
24425       N0.hasOneUse() &&
24426       N0.getOperand(0).hasOneUse()) {
24427     SDValue N00 = N0.getOperand(0);
24428     if (N00.getOpcode() == X86ISD::SETCC_CARRY) {
24429       return DAG.getNode(ISD::AND, dl, VT,
24430                          DAG.getNode(X86ISD::SETCC_CARRY, dl, VT,
24431                                      N00.getOperand(0), N00.getOperand(1)),
24432                          DAG.getConstant(1, dl, VT));
24433     }
24434   }
24435
24436   if (VT.is256BitVector())
24437     if (SDValue R = WidenMaskArithmetic(N, DAG, DCI, Subtarget))
24438       return R;
24439
24440   // (i8,i32 zext (udivrem (i8 x, i8 y)) ->
24441   // (i8,i32 (udivrem_zext_hreg (i8 x, i8 y)
24442   // This exposes the zext to the udivrem lowering, so that it directly extends
24443   // from AH (which we otherwise need to do contortions to access).
24444   if (N0.getOpcode() == ISD::UDIVREM &&
24445       N0.getResNo() == 1 && N0.getValueType() == MVT::i8 &&
24446       (VT == MVT::i32 || VT == MVT::i64)) {
24447     SDVTList NodeTys = DAG.getVTList(MVT::i8, VT);
24448     SDValue R = DAG.getNode(X86ISD::UDIVREM8_ZEXT_HREG, dl, NodeTys,
24449                             N0.getOperand(0), N0.getOperand(1));
24450     DAG.ReplaceAllUsesOfValueWith(N0.getValue(0), R.getValue(0));
24451     return R.getValue(1);
24452   }
24453
24454   return SDValue();
24455 }
24456
24457 // Optimize x == -y --> x+y == 0
24458 //          x != -y --> x+y != 0
24459 static SDValue PerformISDSETCCCombine(SDNode *N, SelectionDAG &DAG,
24460                                       const X86Subtarget* Subtarget) {
24461   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
24462   SDValue LHS = N->getOperand(0);
24463   SDValue RHS = N->getOperand(1);
24464   EVT VT = N->getValueType(0);
24465   SDLoc DL(N);
24466
24467   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && LHS.getOpcode() == ISD::SUB)
24468     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(LHS.getOperand(0)))
24469       if (C->getAPIntValue() == 0 && LHS.hasOneUse()) {
24470         SDValue addV = DAG.getNode(ISD::ADD, DL, LHS.getValueType(), RHS,
24471                                    LHS.getOperand(1));
24472         return DAG.getSetCC(DL, N->getValueType(0), addV,
24473                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24474       }
24475   if ((CC == ISD::SETNE || CC == ISD::SETEQ) && RHS.getOpcode() == ISD::SUB)
24476     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(RHS.getOperand(0)))
24477       if (C->getAPIntValue() == 0 && RHS.hasOneUse()) {
24478         SDValue addV = DAG.getNode(ISD::ADD, DL, RHS.getValueType(), LHS,
24479                                    RHS.getOperand(1));
24480         return DAG.getSetCC(DL, N->getValueType(0), addV,
24481                             DAG.getConstant(0, DL, addV.getValueType()), CC);
24482       }
24483
24484   if (VT.getScalarType() == MVT::i1 &&
24485       (CC == ISD::SETNE || CC == ISD::SETEQ || ISD::isSignedIntSetCC(CC))) {
24486     bool IsSEXT0 =
24487         (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24488         (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24489     bool IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24490
24491     if (!IsSEXT0 || !IsVZero1) {
24492       // Swap the operands and update the condition code.
24493       std::swap(LHS, RHS);
24494       CC = ISD::getSetCCSwappedOperands(CC);
24495
24496       IsSEXT0 = (LHS.getOpcode() == ISD::SIGN_EXTEND) &&
24497                 (LHS.getOperand(0).getValueType().getScalarType() == MVT::i1);
24498       IsVZero1 = ISD::isBuildVectorAllZeros(RHS.getNode());
24499     }
24500
24501     if (IsSEXT0 && IsVZero1) {
24502       assert(VT == LHS.getOperand(0).getValueType() &&
24503              "Uexpected operand type");
24504       if (CC == ISD::SETGT)
24505         return DAG.getConstant(0, DL, VT);
24506       if (CC == ISD::SETLE)
24507         return DAG.getConstant(1, DL, VT);
24508       if (CC == ISD::SETEQ || CC == ISD::SETGE)
24509         return DAG.getNOT(DL, LHS.getOperand(0), VT);
24510
24511       assert((CC == ISD::SETNE || CC == ISD::SETLT) &&
24512              "Unexpected condition code!");
24513       return LHS.getOperand(0);
24514     }
24515   }
24516
24517   return SDValue();
24518 }
24519
24520 static SDValue NarrowVectorLoadToElement(LoadSDNode *Load, unsigned Index,
24521                                          SelectionDAG &DAG) {
24522   SDLoc dl(Load);
24523   MVT VT = Load->getSimpleValueType(0);
24524   MVT EVT = VT.getVectorElementType();
24525   SDValue Addr = Load->getOperand(1);
24526   SDValue NewAddr = DAG.getNode(
24527       ISD::ADD, dl, Addr.getSimpleValueType(), Addr,
24528       DAG.getConstant(Index * EVT.getStoreSize(), dl,
24529                       Addr.getSimpleValueType()));
24530
24531   SDValue NewLoad =
24532       DAG.getLoad(EVT, dl, Load->getChain(), NewAddr,
24533                   DAG.getMachineFunction().getMachineMemOperand(
24534                       Load->getMemOperand(), 0, EVT.getStoreSize()));
24535   return NewLoad;
24536 }
24537
24538 static SDValue PerformINSERTPSCombine(SDNode *N, SelectionDAG &DAG,
24539                                       const X86Subtarget *Subtarget) {
24540   SDLoc dl(N);
24541   MVT VT = N->getOperand(1)->getSimpleValueType(0);
24542   assert((VT == MVT::v4f32 || VT == MVT::v4i32) &&
24543          "X86insertps is only defined for v4x32");
24544
24545   SDValue Ld = N->getOperand(1);
24546   if (MayFoldLoad(Ld)) {
24547     // Extract the countS bits from the immediate so we can get the proper
24548     // address when narrowing the vector load to a specific element.
24549     // When the second source op is a memory address, insertps doesn't use
24550     // countS and just gets an f32 from that address.
24551     unsigned DestIndex =
24552         cast<ConstantSDNode>(N->getOperand(2))->getZExtValue() >> 6;
24553
24554     Ld = NarrowVectorLoadToElement(cast<LoadSDNode>(Ld), DestIndex, DAG);
24555
24556     // Create this as a scalar to vector to match the instruction pattern.
24557     SDValue LoadScalarToVector = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Ld);
24558     // countS bits are ignored when loading from memory on insertps, which
24559     // means we don't need to explicitly set them to 0.
24560     return DAG.getNode(X86ISD::INSERTPS, dl, VT, N->getOperand(0),
24561                        LoadScalarToVector, N->getOperand(2));
24562   }
24563   return SDValue();
24564 }
24565
24566 static SDValue PerformBLENDICombine(SDNode *N, SelectionDAG &DAG) {
24567   SDValue V0 = N->getOperand(0);
24568   SDValue V1 = N->getOperand(1);
24569   SDLoc DL(N);
24570   EVT VT = N->getValueType(0);
24571
24572   // Canonicalize a v2f64 blend with a mask of 2 by swapping the vector
24573   // operands and changing the mask to 1. This saves us a bunch of
24574   // pattern-matching possibilities related to scalar math ops in SSE/AVX.
24575   // x86InstrInfo knows how to commute this back after instruction selection
24576   // if it would help register allocation.
24577
24578   // TODO: If optimizing for size or a processor that doesn't suffer from
24579   // partial register update stalls, this should be transformed into a MOVSD
24580   // instruction because a MOVSD is 1-2 bytes smaller than a BLENDPD.
24581
24582   if (VT == MVT::v2f64)
24583     if (auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(2)))
24584       if (Mask->getZExtValue() == 2 && !isShuffleFoldableLoad(V0)) {
24585         SDValue NewMask = DAG.getConstant(1, DL, MVT::i8);
24586         return DAG.getNode(X86ISD::BLENDI, DL, VT, V1, V0, NewMask);
24587       }
24588
24589   return SDValue();
24590 }
24591
24592 // Helper function of PerformSETCCCombine. It is to materialize "setb reg"
24593 // as "sbb reg,reg", since it can be extended without zext and produces
24594 // an all-ones bit which is more useful than 0/1 in some cases.
24595 static SDValue MaterializeSETB(SDLoc DL, SDValue EFLAGS, SelectionDAG &DAG,
24596                                MVT VT) {
24597   if (VT == MVT::i8)
24598     return DAG.getNode(ISD::AND, DL, VT,
24599                        DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24600                                    DAG.getConstant(X86::COND_B, DL, MVT::i8),
24601                                    EFLAGS),
24602                        DAG.getConstant(1, DL, VT));
24603   assert (VT == MVT::i1 && "Unexpected type for SECCC node");
24604   return DAG.getNode(ISD::TRUNCATE, DL, MVT::i1,
24605                      DAG.getNode(X86ISD::SETCC_CARRY, DL, MVT::i8,
24606                                  DAG.getConstant(X86::COND_B, DL, MVT::i8),
24607                                  EFLAGS));
24608 }
24609
24610 // Optimize  RES = X86ISD::SETCC CONDCODE, EFLAG_INPUT
24611 static SDValue PerformSETCCCombine(SDNode *N, SelectionDAG &DAG,
24612                                    TargetLowering::DAGCombinerInfo &DCI,
24613                                    const X86Subtarget *Subtarget) {
24614   SDLoc DL(N);
24615   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(0));
24616   SDValue EFLAGS = N->getOperand(1);
24617
24618   if (CC == X86::COND_A) {
24619     // Try to convert COND_A into COND_B in an attempt to facilitate
24620     // materializing "setb reg".
24621     //
24622     // Do not flip "e > c", where "c" is a constant, because Cmp instruction
24623     // cannot take an immediate as its first operand.
24624     //
24625     if (EFLAGS.getOpcode() == X86ISD::SUB && EFLAGS.hasOneUse() &&
24626         EFLAGS.getValueType().isInteger() &&
24627         !isa<ConstantSDNode>(EFLAGS.getOperand(1))) {
24628       SDValue NewSub = DAG.getNode(X86ISD::SUB, SDLoc(EFLAGS),
24629                                    EFLAGS.getNode()->getVTList(),
24630                                    EFLAGS.getOperand(1), EFLAGS.getOperand(0));
24631       SDValue NewEFLAGS = SDValue(NewSub.getNode(), EFLAGS.getResNo());
24632       return MaterializeSETB(DL, NewEFLAGS, DAG, N->getSimpleValueType(0));
24633     }
24634   }
24635
24636   // Materialize "setb reg" as "sbb reg,reg", since it can be extended without
24637   // a zext and produces an all-ones bit which is more useful than 0/1 in some
24638   // cases.
24639   if (CC == X86::COND_B)
24640     return MaterializeSETB(DL, EFLAGS, DAG, N->getSimpleValueType(0));
24641
24642   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24643     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24644     return DAG.getNode(X86ISD::SETCC, DL, N->getVTList(), Cond, Flags);
24645   }
24646
24647   return SDValue();
24648 }
24649
24650 // Optimize branch condition evaluation.
24651 //
24652 static SDValue PerformBrCondCombine(SDNode *N, SelectionDAG &DAG,
24653                                     TargetLowering::DAGCombinerInfo &DCI,
24654                                     const X86Subtarget *Subtarget) {
24655   SDLoc DL(N);
24656   SDValue Chain = N->getOperand(0);
24657   SDValue Dest = N->getOperand(1);
24658   SDValue EFLAGS = N->getOperand(3);
24659   X86::CondCode CC = X86::CondCode(N->getConstantOperandVal(2));
24660
24661   if (SDValue Flags = checkBoolTestSetCCCombine(EFLAGS, CC)) {
24662     SDValue Cond = DAG.getConstant(CC, DL, MVT::i8);
24663     return DAG.getNode(X86ISD::BRCOND, DL, N->getVTList(), Chain, Dest, Cond,
24664                        Flags);
24665   }
24666
24667   return SDValue();
24668 }
24669
24670 static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
24671                                                          SelectionDAG &DAG) {
24672   // Take advantage of vector comparisons producing 0 or -1 in each lane to
24673   // optimize away operation when it's from a constant.
24674   //
24675   // The general transformation is:
24676   //    UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
24677   //       AND(VECTOR_CMP(x,y), constant2)
24678   //    constant2 = UNARYOP(constant)
24679
24680   // Early exit if this isn't a vector operation, the operand of the
24681   // unary operation isn't a bitwise AND, or if the sizes of the operations
24682   // aren't the same.
24683   EVT VT = N->getValueType(0);
24684   if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
24685       N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
24686       VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
24687     return SDValue();
24688
24689   // Now check that the other operand of the AND is a constant. We could
24690   // make the transformation for non-constant splats as well, but it's unclear
24691   // that would be a benefit as it would not eliminate any operations, just
24692   // perform one more step in scalar code before moving to the vector unit.
24693   if (BuildVectorSDNode *BV =
24694           dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
24695     // Bail out if the vector isn't a constant.
24696     if (!BV->isConstant())
24697       return SDValue();
24698
24699     // Everything checks out. Build up the new and improved node.
24700     SDLoc DL(N);
24701     EVT IntVT = BV->getValueType(0);
24702     // Create a new constant of the appropriate type for the transformed
24703     // DAG.
24704     SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
24705     // The AND node needs bitcasts to/from an integer vector type around it.
24706     SDValue MaskConst = DAG.getBitcast(IntVT, SourceConst);
24707     SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
24708                                  N->getOperand(0)->getOperand(0), MaskConst);
24709     SDValue Res = DAG.getBitcast(VT, NewAnd);
24710     return Res;
24711   }
24712
24713   return SDValue();
24714 }
24715
24716 static SDValue PerformUINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24717                                         const X86Subtarget *Subtarget) {
24718   SDValue Op0 = N->getOperand(0);
24719   EVT VT = N->getValueType(0);
24720   EVT InVT = Op0.getValueType();
24721   EVT InSVT = InVT.getScalarType();
24722   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
24723
24724   // UINT_TO_FP(vXi8) -> SINT_TO_FP(ZEXT(vXi8 to vXi32))
24725   // UINT_TO_FP(vXi16) -> SINT_TO_FP(ZEXT(vXi16 to vXi32))
24726   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24727     SDLoc dl(N);
24728     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24729                                  InVT.getVectorNumElements());
24730     SDValue P = DAG.getNode(ISD::ZERO_EXTEND, dl, DstVT, Op0);
24731
24732     if (TLI.isOperationLegal(ISD::UINT_TO_FP, DstVT))
24733       return DAG.getNode(ISD::UINT_TO_FP, dl, VT, P);
24734
24735     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24736   }
24737
24738   return SDValue();
24739 }
24740
24741 static SDValue PerformSINT_TO_FPCombine(SDNode *N, SelectionDAG &DAG,
24742                                         const X86Subtarget *Subtarget) {
24743   // First try to optimize away the conversion entirely when it's
24744   // conditionally from a constant. Vectors only.
24745   if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
24746     return Res;
24747
24748   // Now move on to more general possibilities.
24749   SDValue Op0 = N->getOperand(0);
24750   EVT VT = N->getValueType(0);
24751   EVT InVT = Op0.getValueType();
24752   EVT InSVT = InVT.getScalarType();
24753
24754   // SINT_TO_FP(vXi8) -> SINT_TO_FP(SEXT(vXi8 to vXi32))
24755   // SINT_TO_FP(vXi16) -> SINT_TO_FP(SEXT(vXi16 to vXi32))
24756   if (InVT.isVector() && (InSVT == MVT::i8 || InSVT == MVT::i16)) {
24757     SDLoc dl(N);
24758     EVT DstVT = EVT::getVectorVT(*DAG.getContext(), MVT::i32,
24759                                  InVT.getVectorNumElements());
24760     SDValue P = DAG.getNode(ISD::SIGN_EXTEND, dl, DstVT, Op0);
24761     return DAG.getNode(ISD::SINT_TO_FP, dl, VT, P);
24762   }
24763
24764   // Transform (SINT_TO_FP (i64 ...)) into an x87 operation if we have
24765   // a 32-bit target where SSE doesn't support i64->FP operations.
24766   if (Op0.getOpcode() == ISD::LOAD) {
24767     LoadSDNode *Ld = cast<LoadSDNode>(Op0.getNode());
24768     EVT LdVT = Ld->getValueType(0);
24769
24770     // This transformation is not supported if the result type is f16
24771     if (VT == MVT::f16)
24772       return SDValue();
24773
24774     if (!Ld->isVolatile() && !VT.isVector() &&
24775         ISD::isNON_EXTLoad(Op0.getNode()) && Op0.hasOneUse() &&
24776         !Subtarget->is64Bit() && LdVT == MVT::i64) {
24777       SDValue FILDChain = Subtarget->getTargetLowering()->BuildFILD(
24778           SDValue(N, 0), LdVT, Ld->getChain(), Op0, DAG);
24779       DAG.ReplaceAllUsesOfValueWith(Op0.getValue(1), FILDChain.getValue(1));
24780       return FILDChain;
24781     }
24782   }
24783   return SDValue();
24784 }
24785
24786 // Optimize RES, EFLAGS = X86ISD::ADC LHS, RHS, EFLAGS
24787 static SDValue PerformADCCombine(SDNode *N, SelectionDAG &DAG,
24788                                  X86TargetLowering::DAGCombinerInfo &DCI) {
24789   // If the LHS and RHS of the ADC node are zero, then it can't overflow and
24790   // the result is either zero or one (depending on the input carry bit).
24791   // Strength reduce this down to a "set on carry" aka SETCC_CARRY&1.
24792   if (X86::isZeroNode(N->getOperand(0)) &&
24793       X86::isZeroNode(N->getOperand(1)) &&
24794       // We don't have a good way to replace an EFLAGS use, so only do this when
24795       // dead right now.
24796       SDValue(N, 1).use_empty()) {
24797     SDLoc DL(N);
24798     EVT VT = N->getValueType(0);
24799     SDValue CarryOut = DAG.getConstant(0, DL, N->getValueType(1));
24800     SDValue Res1 = DAG.getNode(ISD::AND, DL, VT,
24801                                DAG.getNode(X86ISD::SETCC_CARRY, DL, VT,
24802                                            DAG.getConstant(X86::COND_B, DL,
24803                                                            MVT::i8),
24804                                            N->getOperand(2)),
24805                                DAG.getConstant(1, DL, VT));
24806     return DCI.CombineTo(N, Res1, CarryOut);
24807   }
24808
24809   return SDValue();
24810 }
24811
24812 // fold (add Y, (sete  X, 0)) -> adc  0, Y
24813 //      (add Y, (setne X, 0)) -> sbb -1, Y
24814 //      (sub (sete  X, 0), Y) -> sbb  0, Y
24815 //      (sub (setne X, 0), Y) -> adc -1, Y
24816 static SDValue OptimizeConditionalInDecrement(SDNode *N, SelectionDAG &DAG) {
24817   SDLoc DL(N);
24818
24819   // Look through ZExts.
24820   SDValue Ext = N->getOperand(N->getOpcode() == ISD::SUB ? 1 : 0);
24821   if (Ext.getOpcode() != ISD::ZERO_EXTEND || !Ext.hasOneUse())
24822     return SDValue();
24823
24824   SDValue SetCC = Ext.getOperand(0);
24825   if (SetCC.getOpcode() != X86ISD::SETCC || !SetCC.hasOneUse())
24826     return SDValue();
24827
24828   X86::CondCode CC = (X86::CondCode)SetCC.getConstantOperandVal(0);
24829   if (CC != X86::COND_E && CC != X86::COND_NE)
24830     return SDValue();
24831
24832   SDValue Cmp = SetCC.getOperand(1);
24833   if (Cmp.getOpcode() != X86ISD::CMP || !Cmp.hasOneUse() ||
24834       !X86::isZeroNode(Cmp.getOperand(1)) ||
24835       !Cmp.getOperand(0).getValueType().isInteger())
24836     return SDValue();
24837
24838   SDValue CmpOp0 = Cmp.getOperand(0);
24839   SDValue NewCmp = DAG.getNode(X86ISD::CMP, DL, MVT::i32, CmpOp0,
24840                                DAG.getConstant(1, DL, CmpOp0.getValueType()));
24841
24842   SDValue OtherVal = N->getOperand(N->getOpcode() == ISD::SUB ? 0 : 1);
24843   if (CC == X86::COND_NE)
24844     return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::ADC : X86ISD::SBB,
24845                        DL, OtherVal.getValueType(), OtherVal,
24846                        DAG.getConstant(-1ULL, DL, OtherVal.getValueType()),
24847                        NewCmp);
24848   return DAG.getNode(N->getOpcode() == ISD::SUB ? X86ISD::SBB : X86ISD::ADC,
24849                      DL, OtherVal.getValueType(), OtherVal,
24850                      DAG.getConstant(0, DL, OtherVal.getValueType()), NewCmp);
24851 }
24852
24853 /// PerformADDCombine - Do target-specific dag combines on integer adds.
24854 static SDValue PerformAddCombine(SDNode *N, SelectionDAG &DAG,
24855                                  const X86Subtarget *Subtarget) {
24856   EVT VT = N->getValueType(0);
24857   SDValue Op0 = N->getOperand(0);
24858   SDValue Op1 = N->getOperand(1);
24859
24860   // Try to synthesize horizontal adds from adds of shuffles.
24861   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24862        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24863       isHorizontalBinOp(Op0, Op1, true))
24864     return DAG.getNode(X86ISD::HADD, SDLoc(N), VT, Op0, Op1);
24865
24866   return OptimizeConditionalInDecrement(N, DAG);
24867 }
24868
24869 static SDValue PerformSubCombine(SDNode *N, SelectionDAG &DAG,
24870                                  const X86Subtarget *Subtarget) {
24871   SDValue Op0 = N->getOperand(0);
24872   SDValue Op1 = N->getOperand(1);
24873
24874   // X86 can't encode an immediate LHS of a sub. See if we can push the
24875   // negation into a preceding instruction.
24876   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op0)) {
24877     // If the RHS of the sub is a XOR with one use and a constant, invert the
24878     // immediate. Then add one to the LHS of the sub so we can turn
24879     // X-Y -> X+~Y+1, saving one register.
24880     if (Op1->hasOneUse() && Op1.getOpcode() == ISD::XOR &&
24881         isa<ConstantSDNode>(Op1.getOperand(1))) {
24882       APInt XorC = cast<ConstantSDNode>(Op1.getOperand(1))->getAPIntValue();
24883       EVT VT = Op0.getValueType();
24884       SDValue NewXor = DAG.getNode(ISD::XOR, SDLoc(Op1), VT,
24885                                    Op1.getOperand(0),
24886                                    DAG.getConstant(~XorC, SDLoc(Op1), VT));
24887       return DAG.getNode(ISD::ADD, SDLoc(N), VT, NewXor,
24888                          DAG.getConstant(C->getAPIntValue() + 1, SDLoc(N), VT));
24889     }
24890   }
24891
24892   // Try to synthesize horizontal adds from adds of shuffles.
24893   EVT VT = N->getValueType(0);
24894   if (((Subtarget->hasSSSE3() && (VT == MVT::v8i16 || VT == MVT::v4i32)) ||
24895        (Subtarget->hasInt256() && (VT == MVT::v16i16 || VT == MVT::v8i32))) &&
24896       isHorizontalBinOp(Op0, Op1, true))
24897     return DAG.getNode(X86ISD::HSUB, SDLoc(N), VT, Op0, Op1);
24898
24899   return OptimizeConditionalInDecrement(N, DAG);
24900 }
24901
24902 /// performVZEXTCombine - Performs build vector combines
24903 static SDValue performVZEXTCombine(SDNode *N, SelectionDAG &DAG,
24904                                    TargetLowering::DAGCombinerInfo &DCI,
24905                                    const X86Subtarget *Subtarget) {
24906   SDLoc DL(N);
24907   MVT VT = N->getSimpleValueType(0);
24908   SDValue Op = N->getOperand(0);
24909   MVT OpVT = Op.getSimpleValueType();
24910   MVT OpEltVT = OpVT.getVectorElementType();
24911   unsigned InputBits = OpEltVT.getSizeInBits() * VT.getVectorNumElements();
24912
24913   // (vzext (bitcast (vzext (x)) -> (vzext x)
24914   SDValue V = Op;
24915   while (V.getOpcode() == ISD::BITCAST)
24916     V = V.getOperand(0);
24917
24918   if (V != Op && V.getOpcode() == X86ISD::VZEXT) {
24919     MVT InnerVT = V.getSimpleValueType();
24920     MVT InnerEltVT = InnerVT.getVectorElementType();
24921
24922     // If the element sizes match exactly, we can just do one larger vzext. This
24923     // is always an exact type match as vzext operates on integer types.
24924     if (OpEltVT == InnerEltVT) {
24925       assert(OpVT == InnerVT && "Types must match for vzext!");
24926       return DAG.getNode(X86ISD::VZEXT, DL, VT, V.getOperand(0));
24927     }
24928
24929     // The only other way we can combine them is if only a single element of the
24930     // inner vzext is used in the input to the outer vzext.
24931     if (InnerEltVT.getSizeInBits() < InputBits)
24932       return SDValue();
24933
24934     // In this case, the inner vzext is completely dead because we're going to
24935     // only look at bits inside of the low element. Just do the outer vzext on
24936     // a bitcast of the input to the inner.
24937     return DAG.getNode(X86ISD::VZEXT, DL, VT, DAG.getBitcast(OpVT, V));
24938   }
24939
24940   // Check if we can bypass extracting and re-inserting an element of an input
24941   // vector. Essentialy:
24942   // (bitcast (sclr2vec (ext_vec_elt x))) -> (bitcast x)
24943   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR &&
24944       V.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
24945       V.getOperand(0).getSimpleValueType().getSizeInBits() == InputBits) {
24946     SDValue ExtractedV = V.getOperand(0);
24947     SDValue OrigV = ExtractedV.getOperand(0);
24948     if (auto *ExtractIdx = dyn_cast<ConstantSDNode>(ExtractedV.getOperand(1)))
24949       if (ExtractIdx->getZExtValue() == 0) {
24950         MVT OrigVT = OrigV.getSimpleValueType();
24951         // Extract a subvector if necessary...
24952         if (OrigVT.getSizeInBits() > OpVT.getSizeInBits()) {
24953           int Ratio = OrigVT.getSizeInBits() / OpVT.getSizeInBits();
24954           OrigVT = MVT::getVectorVT(OrigVT.getVectorElementType(),
24955                                     OrigVT.getVectorNumElements() / Ratio);
24956           OrigV = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, OrigVT, OrigV,
24957                               DAG.getIntPtrConstant(0, DL));
24958         }
24959         Op = DAG.getBitcast(OpVT, OrigV);
24960         return DAG.getNode(X86ISD::VZEXT, DL, VT, Op);
24961       }
24962   }
24963
24964   return SDValue();
24965 }
24966
24967 SDValue X86TargetLowering::PerformDAGCombine(SDNode *N,
24968                                              DAGCombinerInfo &DCI) const {
24969   SelectionDAG &DAG = DCI.DAG;
24970   switch (N->getOpcode()) {
24971   default: break;
24972   case ISD::EXTRACT_VECTOR_ELT:
24973     return PerformEXTRACT_VECTOR_ELTCombine(N, DAG, DCI);
24974   case ISD::VSELECT:
24975   case ISD::SELECT:
24976   case X86ISD::SHRUNKBLEND:
24977     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
24978   case ISD::BITCAST:        return PerformBITCASTCombine(N, DAG);
24979   case X86ISD::CMOV:        return PerformCMOVCombine(N, DAG, DCI, Subtarget);
24980   case ISD::ADD:            return PerformAddCombine(N, DAG, Subtarget);
24981   case ISD::SUB:            return PerformSubCombine(N, DAG, Subtarget);
24982   case X86ISD::ADC:         return PerformADCCombine(N, DAG, DCI);
24983   case ISD::MUL:            return PerformMulCombine(N, DAG, DCI);
24984   case ISD::SHL:
24985   case ISD::SRA:
24986   case ISD::SRL:            return PerformShiftCombine(N, DAG, DCI, Subtarget);
24987   case ISD::AND:            return PerformAndCombine(N, DAG, DCI, Subtarget);
24988   case ISD::OR:             return PerformOrCombine(N, DAG, DCI, Subtarget);
24989   case ISD::XOR:            return PerformXorCombine(N, DAG, DCI, Subtarget);
24990   case ISD::LOAD:           return PerformLOADCombine(N, DAG, DCI, Subtarget);
24991   case ISD::MLOAD:          return PerformMLOADCombine(N, DAG, DCI, Subtarget);
24992   case ISD::STORE:          return PerformSTORECombine(N, DAG, Subtarget);
24993   case ISD::MSTORE:         return PerformMSTORECombine(N, DAG, Subtarget);
24994   case ISD::SINT_TO_FP:     return PerformSINT_TO_FPCombine(N, DAG, Subtarget);
24995   case ISD::UINT_TO_FP:     return PerformUINT_TO_FPCombine(N, DAG, Subtarget);
24996   case ISD::FADD:           return PerformFADDCombine(N, DAG, Subtarget);
24997   case ISD::FSUB:           return PerformFSUBCombine(N, DAG, Subtarget);
24998   case X86ISD::FXOR:
24999   case X86ISD::FOR:         return PerformFORCombine(N, DAG);
25000   case X86ISD::FMIN:
25001   case X86ISD::FMAX:        return PerformFMinFMaxCombine(N, DAG);
25002   case X86ISD::FAND:        return PerformFANDCombine(N, DAG);
25003   case X86ISD::FANDN:       return PerformFANDNCombine(N, DAG);
25004   case X86ISD::BT:          return PerformBTCombine(N, DAG, DCI);
25005   case X86ISD::VZEXT_MOVL:  return PerformVZEXT_MOVLCombine(N, DAG);
25006   case ISD::ANY_EXTEND:
25007   case ISD::ZERO_EXTEND:    return PerformZExtCombine(N, DAG, DCI, Subtarget);
25008   case ISD::SIGN_EXTEND:    return PerformSExtCombine(N, DAG, DCI, Subtarget);
25009   case ISD::SIGN_EXTEND_INREG:
25010     return PerformSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
25011   case ISD::SETCC:          return PerformISDSETCCCombine(N, DAG, Subtarget);
25012   case X86ISD::SETCC:       return PerformSETCCCombine(N, DAG, DCI, Subtarget);
25013   case X86ISD::BRCOND:      return PerformBrCondCombine(N, DAG, DCI, Subtarget);
25014   case X86ISD::VZEXT:       return performVZEXTCombine(N, DAG, DCI, Subtarget);
25015   case X86ISD::SHUFP:       // Handle all target specific shuffles
25016   case X86ISD::PALIGNR:
25017   case X86ISD::UNPCKH:
25018   case X86ISD::UNPCKL:
25019   case X86ISD::MOVHLPS:
25020   case X86ISD::MOVLHPS:
25021   case X86ISD::PSHUFB:
25022   case X86ISD::PSHUFD:
25023   case X86ISD::PSHUFHW:
25024   case X86ISD::PSHUFLW:
25025   case X86ISD::MOVSS:
25026   case X86ISD::MOVSD:
25027   case X86ISD::VPERMILPI:
25028   case X86ISD::VPERM2X128:
25029   case ISD::VECTOR_SHUFFLE: return PerformShuffleCombine(N, DAG, DCI,Subtarget);
25030   case ISD::FMA:            return PerformFMACombine(N, DAG, Subtarget);
25031   case ISD::INTRINSIC_WO_CHAIN:
25032     return PerformINTRINSIC_WO_CHAINCombine(N, DAG, Subtarget);
25033   case X86ISD::INSERTPS: {
25034     if (getTargetMachine().getOptLevel() > CodeGenOpt::None)
25035       return PerformINSERTPSCombine(N, DAG, Subtarget);
25036     break;
25037   }
25038   case X86ISD::BLENDI:    return PerformBLENDICombine(N, DAG);
25039   }
25040
25041   return SDValue();
25042 }
25043
25044 /// isTypeDesirableForOp - Return true if the target has native support for
25045 /// the specified value type and it is 'desirable' to use the type for the
25046 /// given node type. e.g. On x86 i16 is legal, but undesirable since i16
25047 /// instruction encodings are longer and some i16 instructions are slow.
25048 bool X86TargetLowering::isTypeDesirableForOp(unsigned Opc, EVT VT) const {
25049   if (!isTypeLegal(VT))
25050     return false;
25051   if (VT != MVT::i16)
25052     return true;
25053
25054   switch (Opc) {
25055   default:
25056     return true;
25057   case ISD::LOAD:
25058   case ISD::SIGN_EXTEND:
25059   case ISD::ZERO_EXTEND:
25060   case ISD::ANY_EXTEND:
25061   case ISD::SHL:
25062   case ISD::SRL:
25063   case ISD::SUB:
25064   case ISD::ADD:
25065   case ISD::MUL:
25066   case ISD::AND:
25067   case ISD::OR:
25068   case ISD::XOR:
25069     return false;
25070   }
25071 }
25072
25073 /// IsDesirableToPromoteOp - This method query the target whether it is
25074 /// beneficial for dag combiner to promote the specified node. If true, it
25075 /// should return the desired promotion type by reference.
25076 bool X86TargetLowering::IsDesirableToPromoteOp(SDValue Op, EVT &PVT) const {
25077   EVT VT = Op.getValueType();
25078   if (VT != MVT::i16)
25079     return false;
25080
25081   bool Promote = false;
25082   bool Commute = false;
25083   switch (Op.getOpcode()) {
25084   default: break;
25085   case ISD::LOAD: {
25086     LoadSDNode *LD = cast<LoadSDNode>(Op);
25087     // If the non-extending load has a single use and it's not live out, then it
25088     // might be folded.
25089     if (LD->getExtensionType() == ISD::NON_EXTLOAD /*&&
25090                                                      Op.hasOneUse()*/) {
25091       for (SDNode::use_iterator UI = Op.getNode()->use_begin(),
25092              UE = Op.getNode()->use_end(); UI != UE; ++UI) {
25093         // The only case where we'd want to promote LOAD (rather then it being
25094         // promoted as an operand is when it's only use is liveout.
25095         if (UI->getOpcode() != ISD::CopyToReg)
25096           return false;
25097       }
25098     }
25099     Promote = true;
25100     break;
25101   }
25102   case ISD::SIGN_EXTEND:
25103   case ISD::ZERO_EXTEND:
25104   case ISD::ANY_EXTEND:
25105     Promote = true;
25106     break;
25107   case ISD::SHL:
25108   case ISD::SRL: {
25109     SDValue N0 = Op.getOperand(0);
25110     // Look out for (store (shl (load), x)).
25111     if (MayFoldLoad(N0) && MayFoldIntoStore(Op))
25112       return false;
25113     Promote = true;
25114     break;
25115   }
25116   case ISD::ADD:
25117   case ISD::MUL:
25118   case ISD::AND:
25119   case ISD::OR:
25120   case ISD::XOR:
25121     Commute = true;
25122     // fallthrough
25123   case ISD::SUB: {
25124     SDValue N0 = Op.getOperand(0);
25125     SDValue N1 = Op.getOperand(1);
25126     if (!Commute && MayFoldLoad(N1))
25127       return false;
25128     // Avoid disabling potential load folding opportunities.
25129     if (MayFoldLoad(N0) && (!isa<ConstantSDNode>(N1) || MayFoldIntoStore(Op)))
25130       return false;
25131     if (MayFoldLoad(N1) && (!isa<ConstantSDNode>(N0) || MayFoldIntoStore(Op)))
25132       return false;
25133     Promote = true;
25134   }
25135   }
25136
25137   PVT = MVT::i32;
25138   return Promote;
25139 }
25140
25141 //===----------------------------------------------------------------------===//
25142 //                           X86 Inline Assembly Support
25143 //===----------------------------------------------------------------------===//
25144
25145 // Helper to match a string separated by whitespace.
25146 static bool matchAsm(StringRef S, ArrayRef<const char *> Pieces) {
25147   S = S.substr(S.find_first_not_of(" \t")); // Skip leading whitespace.
25148
25149   for (StringRef Piece : Pieces) {
25150     if (!S.startswith(Piece)) // Check if the piece matches.
25151       return false;
25152
25153     S = S.substr(Piece.size());
25154     StringRef::size_type Pos = S.find_first_not_of(" \t");
25155     if (Pos == 0) // We matched a prefix.
25156       return false;
25157
25158     S = S.substr(Pos);
25159   }
25160
25161   return S.empty();
25162 }
25163
25164 static bool clobbersFlagRegisters(const SmallVector<StringRef, 4> &AsmPieces) {
25165
25166   if (AsmPieces.size() == 3 || AsmPieces.size() == 4) {
25167     if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{cc}") &&
25168         std::count(AsmPieces.begin(), AsmPieces.end(), "~{flags}") &&
25169         std::count(AsmPieces.begin(), AsmPieces.end(), "~{fpsr}")) {
25170
25171       if (AsmPieces.size() == 3)
25172         return true;
25173       else if (std::count(AsmPieces.begin(), AsmPieces.end(), "~{dirflag}"))
25174         return true;
25175     }
25176   }
25177   return false;
25178 }
25179
25180 bool X86TargetLowering::ExpandInlineAsm(CallInst *CI) const {
25181   InlineAsm *IA = cast<InlineAsm>(CI->getCalledValue());
25182
25183   std::string AsmStr = IA->getAsmString();
25184
25185   IntegerType *Ty = dyn_cast<IntegerType>(CI->getType());
25186   if (!Ty || Ty->getBitWidth() % 16 != 0)
25187     return false;
25188
25189   // TODO: should remove alternatives from the asmstring: "foo {a|b}" -> "foo a"
25190   SmallVector<StringRef, 4> AsmPieces;
25191   SplitString(AsmStr, AsmPieces, ";\n");
25192
25193   switch (AsmPieces.size()) {
25194   default: return false;
25195   case 1:
25196     // FIXME: this should verify that we are targeting a 486 or better.  If not,
25197     // we will turn this bswap into something that will be lowered to logical
25198     // ops instead of emitting the bswap asm.  For now, we don't support 486 or
25199     // lower so don't worry about this.
25200     // bswap $0
25201     if (matchAsm(AsmPieces[0], {"bswap", "$0"}) ||
25202         matchAsm(AsmPieces[0], {"bswapl", "$0"}) ||
25203         matchAsm(AsmPieces[0], {"bswapq", "$0"}) ||
25204         matchAsm(AsmPieces[0], {"bswap", "${0:q}"}) ||
25205         matchAsm(AsmPieces[0], {"bswapl", "${0:q}"}) ||
25206         matchAsm(AsmPieces[0], {"bswapq", "${0:q}"})) {
25207       // No need to check constraints, nothing other than the equivalent of
25208       // "=r,0" would be valid here.
25209       return IntrinsicLowering::LowerToByteSwap(CI);
25210     }
25211
25212     // rorw $$8, ${0:w}  -->  llvm.bswap.i16
25213     if (CI->getType()->isIntegerTy(16) &&
25214         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25215         (matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) ||
25216          matchAsm(AsmPieces[0], {"rolw", "$$8,", "${0:w}"}))) {
25217       AsmPieces.clear();
25218       StringRef ConstraintsStr = IA->getConstraintString();
25219       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25220       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25221       if (clobbersFlagRegisters(AsmPieces))
25222         return IntrinsicLowering::LowerToByteSwap(CI);
25223     }
25224     break;
25225   case 3:
25226     if (CI->getType()->isIntegerTy(32) &&
25227         IA->getConstraintString().compare(0, 5, "=r,0,") == 0 &&
25228         matchAsm(AsmPieces[0], {"rorw", "$$8,", "${0:w}"}) &&
25229         matchAsm(AsmPieces[1], {"rorl", "$$16,", "$0"}) &&
25230         matchAsm(AsmPieces[2], {"rorw", "$$8,", "${0:w}"})) {
25231       AsmPieces.clear();
25232       StringRef ConstraintsStr = IA->getConstraintString();
25233       SplitString(StringRef(ConstraintsStr).substr(5), AsmPieces, ",");
25234       array_pod_sort(AsmPieces.begin(), AsmPieces.end());
25235       if (clobbersFlagRegisters(AsmPieces))
25236         return IntrinsicLowering::LowerToByteSwap(CI);
25237     }
25238
25239     if (CI->getType()->isIntegerTy(64)) {
25240       InlineAsm::ConstraintInfoVector Constraints = IA->ParseConstraints();
25241       if (Constraints.size() >= 2 &&
25242           Constraints[0].Codes.size() == 1 && Constraints[0].Codes[0] == "A" &&
25243           Constraints[1].Codes.size() == 1 && Constraints[1].Codes[0] == "0") {
25244         // bswap %eax / bswap %edx / xchgl %eax, %edx  -> llvm.bswap.i64
25245         if (matchAsm(AsmPieces[0], {"bswap", "%eax"}) &&
25246             matchAsm(AsmPieces[1], {"bswap", "%edx"}) &&
25247             matchAsm(AsmPieces[2], {"xchgl", "%eax,", "%edx"}))
25248           return IntrinsicLowering::LowerToByteSwap(CI);
25249       }
25250     }
25251     break;
25252   }
25253   return false;
25254 }
25255
25256 /// getConstraintType - Given a constraint letter, return the type of
25257 /// constraint it is for this target.
25258 X86TargetLowering::ConstraintType
25259 X86TargetLowering::getConstraintType(StringRef Constraint) const {
25260   if (Constraint.size() == 1) {
25261     switch (Constraint[0]) {
25262     case 'R':
25263     case 'q':
25264     case 'Q':
25265     case 'f':
25266     case 't':
25267     case 'u':
25268     case 'y':
25269     case 'x':
25270     case 'Y':
25271     case 'l':
25272       return C_RegisterClass;
25273     case 'a':
25274     case 'b':
25275     case 'c':
25276     case 'd':
25277     case 'S':
25278     case 'D':
25279     case 'A':
25280       return C_Register;
25281     case 'I':
25282     case 'J':
25283     case 'K':
25284     case 'L':
25285     case 'M':
25286     case 'N':
25287     case 'G':
25288     case 'C':
25289     case 'e':
25290     case 'Z':
25291       return C_Other;
25292     default:
25293       break;
25294     }
25295   }
25296   return TargetLowering::getConstraintType(Constraint);
25297 }
25298
25299 /// Examine constraint type and operand type and determine a weight value.
25300 /// This object must already have been set up with the operand type
25301 /// and the current alternative constraint selected.
25302 TargetLowering::ConstraintWeight
25303   X86TargetLowering::getSingleConstraintMatchWeight(
25304     AsmOperandInfo &info, const char *constraint) const {
25305   ConstraintWeight weight = CW_Invalid;
25306   Value *CallOperandVal = info.CallOperandVal;
25307     // If we don't have a value, we can't do a match,
25308     // but allow it at the lowest weight.
25309   if (!CallOperandVal)
25310     return CW_Default;
25311   Type *type = CallOperandVal->getType();
25312   // Look at the constraint type.
25313   switch (*constraint) {
25314   default:
25315     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
25316   case 'R':
25317   case 'q':
25318   case 'Q':
25319   case 'a':
25320   case 'b':
25321   case 'c':
25322   case 'd':
25323   case 'S':
25324   case 'D':
25325   case 'A':
25326     if (CallOperandVal->getType()->isIntegerTy())
25327       weight = CW_SpecificReg;
25328     break;
25329   case 'f':
25330   case 't':
25331   case 'u':
25332     if (type->isFloatingPointTy())
25333       weight = CW_SpecificReg;
25334     break;
25335   case 'y':
25336     if (type->isX86_MMXTy() && Subtarget->hasMMX())
25337       weight = CW_SpecificReg;
25338     break;
25339   case 'x':
25340   case 'Y':
25341     if (((type->getPrimitiveSizeInBits() == 128) && Subtarget->hasSSE1()) ||
25342         ((type->getPrimitiveSizeInBits() == 256) && Subtarget->hasFp256()))
25343       weight = CW_Register;
25344     break;
25345   case 'I':
25346     if (ConstantInt *C = dyn_cast<ConstantInt>(info.CallOperandVal)) {
25347       if (C->getZExtValue() <= 31)
25348         weight = CW_Constant;
25349     }
25350     break;
25351   case 'J':
25352     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25353       if (C->getZExtValue() <= 63)
25354         weight = CW_Constant;
25355     }
25356     break;
25357   case 'K':
25358     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25359       if ((C->getSExtValue() >= -0x80) && (C->getSExtValue() <= 0x7f))
25360         weight = CW_Constant;
25361     }
25362     break;
25363   case 'L':
25364     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25365       if ((C->getZExtValue() == 0xff) || (C->getZExtValue() == 0xffff))
25366         weight = CW_Constant;
25367     }
25368     break;
25369   case 'M':
25370     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25371       if (C->getZExtValue() <= 3)
25372         weight = CW_Constant;
25373     }
25374     break;
25375   case 'N':
25376     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25377       if (C->getZExtValue() <= 0xff)
25378         weight = CW_Constant;
25379     }
25380     break;
25381   case 'G':
25382   case 'C':
25383     if (isa<ConstantFP>(CallOperandVal)) {
25384       weight = CW_Constant;
25385     }
25386     break;
25387   case 'e':
25388     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25389       if ((C->getSExtValue() >= -0x80000000LL) &&
25390           (C->getSExtValue() <= 0x7fffffffLL))
25391         weight = CW_Constant;
25392     }
25393     break;
25394   case 'Z':
25395     if (ConstantInt *C = dyn_cast<ConstantInt>(CallOperandVal)) {
25396       if (C->getZExtValue() <= 0xffffffff)
25397         weight = CW_Constant;
25398     }
25399     break;
25400   }
25401   return weight;
25402 }
25403
25404 /// LowerXConstraint - try to replace an X constraint, which matches anything,
25405 /// with another that has more specific requirements based on the type of the
25406 /// corresponding operand.
25407 const char *X86TargetLowering::
25408 LowerXConstraint(EVT ConstraintVT) const {
25409   // FP X constraints get lowered to SSE1/2 registers if available, otherwise
25410   // 'f' like normal targets.
25411   if (ConstraintVT.isFloatingPoint()) {
25412     if (Subtarget->hasSSE2())
25413       return "Y";
25414     if (Subtarget->hasSSE1())
25415       return "x";
25416   }
25417
25418   return TargetLowering::LowerXConstraint(ConstraintVT);
25419 }
25420
25421 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
25422 /// vector.  If it is invalid, don't add anything to Ops.
25423 void X86TargetLowering::LowerAsmOperandForConstraint(SDValue Op,
25424                                                      std::string &Constraint,
25425                                                      std::vector<SDValue>&Ops,
25426                                                      SelectionDAG &DAG) const {
25427   SDValue Result;
25428
25429   // Only support length 1 constraints for now.
25430   if (Constraint.length() > 1) return;
25431
25432   char ConstraintLetter = Constraint[0];
25433   switch (ConstraintLetter) {
25434   default: break;
25435   case 'I':
25436     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25437       if (C->getZExtValue() <= 31) {
25438         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25439                                        Op.getValueType());
25440         break;
25441       }
25442     }
25443     return;
25444   case 'J':
25445     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25446       if (C->getZExtValue() <= 63) {
25447         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25448                                        Op.getValueType());
25449         break;
25450       }
25451     }
25452     return;
25453   case 'K':
25454     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25455       if (isInt<8>(C->getSExtValue())) {
25456         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25457                                        Op.getValueType());
25458         break;
25459       }
25460     }
25461     return;
25462   case 'L':
25463     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25464       if (C->getZExtValue() == 0xff || C->getZExtValue() == 0xffff ||
25465           (Subtarget->is64Bit() && C->getZExtValue() == 0xffffffff)) {
25466         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op),
25467                                        Op.getValueType());
25468         break;
25469       }
25470     }
25471     return;
25472   case 'M':
25473     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25474       if (C->getZExtValue() <= 3) {
25475         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25476                                        Op.getValueType());
25477         break;
25478       }
25479     }
25480     return;
25481   case 'N':
25482     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25483       if (C->getZExtValue() <= 255) {
25484         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25485                                        Op.getValueType());
25486         break;
25487       }
25488     }
25489     return;
25490   case 'O':
25491     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25492       if (C->getZExtValue() <= 127) {
25493         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25494                                        Op.getValueType());
25495         break;
25496       }
25497     }
25498     return;
25499   case 'e': {
25500     // 32-bit signed value
25501     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25502       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25503                                            C->getSExtValue())) {
25504         // Widen to 64 bits here to get it sign extended.
25505         Result = DAG.getTargetConstant(C->getSExtValue(), SDLoc(Op), MVT::i64);
25506         break;
25507       }
25508     // FIXME gcc accepts some relocatable values here too, but only in certain
25509     // memory models; it's complicated.
25510     }
25511     return;
25512   }
25513   case 'Z': {
25514     // 32-bit unsigned value
25515     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
25516       if (ConstantInt::isValueValidForType(Type::getInt32Ty(*DAG.getContext()),
25517                                            C->getZExtValue())) {
25518         Result = DAG.getTargetConstant(C->getZExtValue(), SDLoc(Op),
25519                                        Op.getValueType());
25520         break;
25521       }
25522     }
25523     // FIXME gcc accepts some relocatable values here too, but only in certain
25524     // memory models; it's complicated.
25525     return;
25526   }
25527   case 'i': {
25528     // Literal immediates are always ok.
25529     if (ConstantSDNode *CST = dyn_cast<ConstantSDNode>(Op)) {
25530       // Widen to 64 bits here to get it sign extended.
25531       Result = DAG.getTargetConstant(CST->getSExtValue(), SDLoc(Op), MVT::i64);
25532       break;
25533     }
25534
25535     // In any sort of PIC mode addresses need to be computed at runtime by
25536     // adding in a register or some sort of table lookup.  These can't
25537     // be used as immediates.
25538     if (Subtarget->isPICStyleGOT() || Subtarget->isPICStyleStubPIC())
25539       return;
25540
25541     // If we are in non-pic codegen mode, we allow the address of a global (with
25542     // an optional displacement) to be used with 'i'.
25543     GlobalAddressSDNode *GA = nullptr;
25544     int64_t Offset = 0;
25545
25546     // Match either (GA), (GA+C), (GA+C1+C2), etc.
25547     while (1) {
25548       if ((GA = dyn_cast<GlobalAddressSDNode>(Op))) {
25549         Offset += GA->getOffset();
25550         break;
25551       } else if (Op.getOpcode() == ISD::ADD) {
25552         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25553           Offset += C->getZExtValue();
25554           Op = Op.getOperand(0);
25555           continue;
25556         }
25557       } else if (Op.getOpcode() == ISD::SUB) {
25558         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
25559           Offset += -C->getZExtValue();
25560           Op = Op.getOperand(0);
25561           continue;
25562         }
25563       }
25564
25565       // Otherwise, this isn't something we can handle, reject it.
25566       return;
25567     }
25568
25569     const GlobalValue *GV = GA->getGlobal();
25570     // If we require an extra load to get this address, as in PIC mode, we
25571     // can't accept it.
25572     if (isGlobalStubReference(
25573             Subtarget->ClassifyGlobalReference(GV, DAG.getTarget())))
25574       return;
25575
25576     Result = DAG.getTargetGlobalAddress(GV, SDLoc(Op),
25577                                         GA->getValueType(0), Offset);
25578     break;
25579   }
25580   }
25581
25582   if (Result.getNode()) {
25583     Ops.push_back(Result);
25584     return;
25585   }
25586   return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
25587 }
25588
25589 std::pair<unsigned, const TargetRegisterClass *>
25590 X86TargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
25591                                                 StringRef Constraint,
25592                                                 MVT VT) const {
25593   // First, see if this is a constraint that directly corresponds to an LLVM
25594   // register class.
25595   if (Constraint.size() == 1) {
25596     // GCC Constraint Letters
25597     switch (Constraint[0]) {
25598     default: break;
25599       // TODO: Slight differences here in allocation order and leaving
25600       // RIP in the class. Do they matter any more here than they do
25601       // in the normal allocation?
25602     case 'q':   // GENERAL_REGS in 64-bit mode, Q_REGS in 32-bit mode.
25603       if (Subtarget->is64Bit()) {
25604         if (VT == MVT::i32 || VT == MVT::f32)
25605           return std::make_pair(0U, &X86::GR32RegClass);
25606         if (VT == MVT::i16)
25607           return std::make_pair(0U, &X86::GR16RegClass);
25608         if (VT == MVT::i8 || VT == MVT::i1)
25609           return std::make_pair(0U, &X86::GR8RegClass);
25610         if (VT == MVT::i64 || VT == MVT::f64)
25611           return std::make_pair(0U, &X86::GR64RegClass);
25612         break;
25613       }
25614       // 32-bit fallthrough
25615     case 'Q':   // Q_REGS
25616       if (VT == MVT::i32 || VT == MVT::f32)
25617         return std::make_pair(0U, &X86::GR32_ABCDRegClass);
25618       if (VT == MVT::i16)
25619         return std::make_pair(0U, &X86::GR16_ABCDRegClass);
25620       if (VT == MVT::i8 || VT == MVT::i1)
25621         return std::make_pair(0U, &X86::GR8_ABCD_LRegClass);
25622       if (VT == MVT::i64)
25623         return std::make_pair(0U, &X86::GR64_ABCDRegClass);
25624       break;
25625     case 'r':   // GENERAL_REGS
25626     case 'l':   // INDEX_REGS
25627       if (VT == MVT::i8 || VT == MVT::i1)
25628         return std::make_pair(0U, &X86::GR8RegClass);
25629       if (VT == MVT::i16)
25630         return std::make_pair(0U, &X86::GR16RegClass);
25631       if (VT == MVT::i32 || VT == MVT::f32 || !Subtarget->is64Bit())
25632         return std::make_pair(0U, &X86::GR32RegClass);
25633       return std::make_pair(0U, &X86::GR64RegClass);
25634     case 'R':   // LEGACY_REGS
25635       if (VT == MVT::i8 || VT == MVT::i1)
25636         return std::make_pair(0U, &X86::GR8_NOREXRegClass);
25637       if (VT == MVT::i16)
25638         return std::make_pair(0U, &X86::GR16_NOREXRegClass);
25639       if (VT == MVT::i32 || !Subtarget->is64Bit())
25640         return std::make_pair(0U, &X86::GR32_NOREXRegClass);
25641       return std::make_pair(0U, &X86::GR64_NOREXRegClass);
25642     case 'f':  // FP Stack registers.
25643       // If SSE is enabled for this VT, use f80 to ensure the isel moves the
25644       // value to the correct fpstack register class.
25645       if (VT == MVT::f32 && !isScalarFPTypeInSSEReg(VT))
25646         return std::make_pair(0U, &X86::RFP32RegClass);
25647       if (VT == MVT::f64 && !isScalarFPTypeInSSEReg(VT))
25648         return std::make_pair(0U, &X86::RFP64RegClass);
25649       return std::make_pair(0U, &X86::RFP80RegClass);
25650     case 'y':   // MMX_REGS if MMX allowed.
25651       if (!Subtarget->hasMMX()) break;
25652       return std::make_pair(0U, &X86::VR64RegClass);
25653     case 'Y':   // SSE_REGS if SSE2 allowed
25654       if (!Subtarget->hasSSE2()) break;
25655       // FALL THROUGH.
25656     case 'x':   // SSE_REGS if SSE1 allowed or AVX_REGS if AVX allowed
25657       if (!Subtarget->hasSSE1()) break;
25658
25659       switch (VT.SimpleTy) {
25660       default: break;
25661       // Scalar SSE types.
25662       case MVT::f32:
25663       case MVT::i32:
25664         return std::make_pair(0U, &X86::FR32RegClass);
25665       case MVT::f64:
25666       case MVT::i64:
25667         return std::make_pair(0U, &X86::FR64RegClass);
25668       // Vector types.
25669       case MVT::v16i8:
25670       case MVT::v8i16:
25671       case MVT::v4i32:
25672       case MVT::v2i64:
25673       case MVT::v4f32:
25674       case MVT::v2f64:
25675         return std::make_pair(0U, &X86::VR128RegClass);
25676       // AVX types.
25677       case MVT::v32i8:
25678       case MVT::v16i16:
25679       case MVT::v8i32:
25680       case MVT::v4i64:
25681       case MVT::v8f32:
25682       case MVT::v4f64:
25683         return std::make_pair(0U, &X86::VR256RegClass);
25684       case MVT::v8f64:
25685       case MVT::v16f32:
25686       case MVT::v16i32:
25687       case MVT::v8i64:
25688         return std::make_pair(0U, &X86::VR512RegClass);
25689       }
25690       break;
25691     }
25692   }
25693
25694   // Use the default implementation in TargetLowering to convert the register
25695   // constraint into a member of a register class.
25696   std::pair<unsigned, const TargetRegisterClass*> Res;
25697   Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
25698
25699   // Not found as a standard register?
25700   if (!Res.second) {
25701     // Map st(0) -> st(7) -> ST0
25702     if (Constraint.size() == 7 && Constraint[0] == '{' &&
25703         tolower(Constraint[1]) == 's' &&
25704         tolower(Constraint[2]) == 't' &&
25705         Constraint[3] == '(' &&
25706         (Constraint[4] >= '0' && Constraint[4] <= '7') &&
25707         Constraint[5] == ')' &&
25708         Constraint[6] == '}') {
25709
25710       Res.first = X86::FP0+Constraint[4]-'0';
25711       Res.second = &X86::RFP80RegClass;
25712       return Res;
25713     }
25714
25715     // GCC allows "st(0)" to be called just plain "st".
25716     if (StringRef("{st}").equals_lower(Constraint)) {
25717       Res.first = X86::FP0;
25718       Res.second = &X86::RFP80RegClass;
25719       return Res;
25720     }
25721
25722     // flags -> EFLAGS
25723     if (StringRef("{flags}").equals_lower(Constraint)) {
25724       Res.first = X86::EFLAGS;
25725       Res.second = &X86::CCRRegClass;
25726       return Res;
25727     }
25728
25729     // 'A' means EAX + EDX.
25730     if (Constraint == "A") {
25731       Res.first = X86::EAX;
25732       Res.second = &X86::GR32_ADRegClass;
25733       return Res;
25734     }
25735     return Res;
25736   }
25737
25738   // Otherwise, check to see if this is a register class of the wrong value
25739   // type.  For example, we want to map "{ax},i32" -> {eax}, we don't want it to
25740   // turn into {ax},{dx}.
25741   // MVT::Other is used to specify clobber names.
25742   if (Res.second->hasType(VT) || VT == MVT::Other)
25743     return Res;   // Correct type already, nothing to do.
25744
25745   // Get a matching integer of the correct size. i.e. "ax" with MVT::32 should
25746   // return "eax". This should even work for things like getting 64bit integer
25747   // registers when given an f64 type.
25748   const TargetRegisterClass *Class = Res.second;
25749   if (Class == &X86::GR8RegClass || Class == &X86::GR16RegClass ||
25750       Class == &X86::GR32RegClass || Class == &X86::GR64RegClass) {
25751     unsigned Size = VT.getSizeInBits();
25752     MVT::SimpleValueType SimpleTy = Size == 1 || Size == 8 ? MVT::i8
25753                                   : Size == 16 ? MVT::i16
25754                                   : Size == 32 ? MVT::i32
25755                                   : Size == 64 ? MVT::i64
25756                                   : MVT::Other;
25757     unsigned DestReg = getX86SubSuperRegisterOrZero(Res.first, SimpleTy);
25758     if (DestReg > 0) {
25759       Res.first = DestReg;
25760       Res.second = SimpleTy == MVT::i8 ? &X86::GR8RegClass
25761                  : SimpleTy == MVT::i16 ? &X86::GR16RegClass
25762                  : SimpleTy == MVT::i32 ? &X86::GR32RegClass
25763                  : &X86::GR64RegClass;
25764       assert(Res.second->contains(Res.first) && "Register in register class");
25765     } else {
25766       // No register found/type mismatch.
25767       Res.first = 0;
25768       Res.second = nullptr;
25769     }
25770   } else if (Class == &X86::FR32RegClass || Class == &X86::FR64RegClass ||
25771              Class == &X86::VR128RegClass || Class == &X86::VR256RegClass ||
25772              Class == &X86::FR32XRegClass || Class == &X86::FR64XRegClass ||
25773              Class == &X86::VR128XRegClass || Class == &X86::VR256XRegClass ||
25774              Class == &X86::VR512RegClass) {
25775     // Handle references to XMM physical registers that got mapped into the
25776     // wrong class.  This can happen with constraints like {xmm0} where the
25777     // target independent register mapper will just pick the first match it can
25778     // find, ignoring the required type.
25779
25780     if (VT == MVT::f32 || VT == MVT::i32)
25781       Res.second = &X86::FR32RegClass;
25782     else if (VT == MVT::f64 || VT == MVT::i64)
25783       Res.second = &X86::FR64RegClass;
25784     else if (X86::VR128RegClass.hasType(VT))
25785       Res.second = &X86::VR128RegClass;
25786     else if (X86::VR256RegClass.hasType(VT))
25787       Res.second = &X86::VR256RegClass;
25788     else if (X86::VR512RegClass.hasType(VT))
25789       Res.second = &X86::VR512RegClass;
25790     else {
25791       // Type mismatch and not a clobber: Return an error;
25792       Res.first = 0;
25793       Res.second = nullptr;
25794     }
25795   }
25796
25797   return Res;
25798 }
25799
25800 int X86TargetLowering::getScalingFactorCost(const AddrMode &AM,
25801                                             Type *Ty,
25802                                             unsigned AS) const {
25803   // Scaling factors are not free at all.
25804   // An indexed folded instruction, i.e., inst (reg1, reg2, scale),
25805   // will take 2 allocations in the out of order engine instead of 1
25806   // for plain addressing mode, i.e. inst (reg1).
25807   // E.g.,
25808   // vaddps (%rsi,%drx), %ymm0, %ymm1
25809   // Requires two allocations (one for the load, one for the computation)
25810   // whereas:
25811   // vaddps (%rsi), %ymm0, %ymm1
25812   // Requires just 1 allocation, i.e., freeing allocations for other operations
25813   // and having less micro operations to execute.
25814   //
25815   // For some X86 architectures, this is even worse because for instance for
25816   // stores, the complex addressing mode forces the instruction to use the
25817   // "load" ports instead of the dedicated "store" port.
25818   // E.g., on Haswell:
25819   // vmovaps %ymm1, (%r8, %rdi) can use port 2 or 3.
25820   // vmovaps %ymm1, (%r8) can use port 2, 3, or 7.
25821   if (isLegalAddressingMode(AM, Ty, AS))
25822     // Scale represents reg2 * scale, thus account for 1
25823     // as soon as we use a second register.
25824     return AM.Scale != 0;
25825   return -1;
25826 }
25827
25828 bool X86TargetLowering::isTargetFTOL() const {
25829   return Subtarget->isTargetKnownWindowsMSVC() && !Subtarget->is64Bit();
25830 }